clang 20.0.0git
ExprConstant.cpp
Go to the documentation of this file.
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Expr constant evaluator.
10//
11// Constant expression evaluation produces four main results:
12//
13// * A success/failure flag indicating whether constant folding was successful.
14// This is the 'bool' return value used by most of the code in this file. A
15// 'false' return value indicates that constant folding has failed, and any
16// appropriate diagnostic has already been produced.
17//
18// * An evaluated result, valid only if constant folding has not failed.
19//
20// * A flag indicating if evaluation encountered (unevaluated) side-effects.
21// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22// where it is possible to determine the evaluated result regardless.
23//
24// * A set of notes indicating why the evaluation was not a constant expression
25// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26// too, why the expression could not be folded.
27//
28// If we are checking for a potential constant expression, failure to constant
29// fold a potential constant sub-expression will be indicated by a 'false'
30// return value (the expression could not be folded) and no diagnostic (the
31// expression is not necessarily non-constant).
32//
33//===----------------------------------------------------------------------===//
34
35#include "ByteCode/Context.h"
36#include "ByteCode/Frame.h"
37#include "ByteCode/State.h"
38#include "ExprConstShared.h"
39#include "clang/AST/APValue.h"
41#include "clang/AST/ASTLambda.h"
42#include "clang/AST/Attr.h"
44#include "clang/AST/CharUnits.h"
46#include "clang/AST/Expr.h"
47#include "clang/AST/OSLog.h"
51#include "clang/AST/TypeLoc.h"
56#include "llvm/ADT/APFixedPoint.h"
57#include "llvm/ADT/Sequence.h"
58#include "llvm/ADT/SmallBitVector.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/Debug.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/SipHash.h"
64#include "llvm/Support/TimeProfiler.h"
65#include "llvm/Support/raw_ostream.h"
66#include <cstring>
67#include <functional>
68#include <optional>
69
70#define DEBUG_TYPE "exprconstant"
71
72using namespace clang;
73using llvm::APFixedPoint;
74using llvm::APInt;
75using llvm::APSInt;
76using llvm::APFloat;
77using llvm::FixedPointSemantics;
78
79namespace {
80 struct LValue;
81 class CallStackFrame;
82 class EvalInfo;
83
84 using SourceLocExprScopeGuard =
86
87 static QualType getType(APValue::LValueBase B) {
88 return B.getType();
89 }
90
91 /// Get an LValue path entry, which is known to not be an array index, as a
92 /// field declaration.
93 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
94 return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
95 }
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// base class declaration.
98 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
99 return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
100 }
101 /// Determine whether this LValue path entry for a base class names a virtual
102 /// base class.
103 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
104 return E.getAsBaseOrMember().getInt();
105 }
106
107 /// Given an expression, determine the type used to store the result of
108 /// evaluating that expression.
109 static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
110 if (E->isPRValue())
111 return E->getType();
112 return Ctx.getLValueReferenceType(E->getType());
113 }
114
115 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
116 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
117 if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
118 return DirectCallee->getAttr<AllocSizeAttr>();
119 if (const Decl *IndirectCallee = CE->getCalleeDecl())
120 return IndirectCallee->getAttr<AllocSizeAttr>();
121 return nullptr;
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. In exotic cases, we might also see a
135 // top-level ExprWithCleanups. Ignore them either way.
136 if (const auto *FE = dyn_cast<FullExpr>(E))
137 E = FE->getSubExpr()->IgnoreParens();
138
139 if (const auto *Cast = dyn_cast<CastExpr>(E))
140 E = Cast->getSubExpr()->IgnoreParens();
141
142 if (const auto *CE = dyn_cast<CallExpr>(E))
143 return getAllocSizeAttr(CE) ? CE : nullptr;
144 return nullptr;
145 }
146
147 /// Determines whether or not the given Base contains a call to a function
148 /// with the alloc_size attribute.
149 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
150 const auto *E = Base.dyn_cast<const Expr *>();
151 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
152 }
153
154 /// Determines whether the given kind of constant expression is only ever
155 /// used for name mangling. If so, it's permitted to reference things that we
156 /// can't generate code for (in particular, dllimported functions).
157 static bool isForManglingOnly(ConstantExprKind Kind) {
158 switch (Kind) {
159 case ConstantExprKind::Normal:
160 case ConstantExprKind::ClassTemplateArgument:
161 case ConstantExprKind::ImmediateInvocation:
162 // Note that non-type template arguments of class type are emitted as
163 // template parameter objects.
164 return false;
165
166 case ConstantExprKind::NonClassTemplateArgument:
167 return true;
168 }
169 llvm_unreachable("unknown ConstantExprKind");
170 }
171
172 static bool isTemplateArgument(ConstantExprKind Kind) {
173 switch (Kind) {
174 case ConstantExprKind::Normal:
175 case ConstantExprKind::ImmediateInvocation:
176 return false;
177
178 case ConstantExprKind::ClassTemplateArgument:
179 case ConstantExprKind::NonClassTemplateArgument:
180 return true;
181 }
182 llvm_unreachable("unknown ConstantExprKind");
183 }
184
185 /// The bound to claim that an array of unknown bound has.
186 /// The value in MostDerivedArraySize is undefined in this case. So, set it
187 /// to an arbitrary value that's likely to loudly break things if it's used.
188 static const uint64_t AssumedSizeForUnsizedArray =
189 std::numeric_limits<uint64_t>::max() / 2;
190
191 /// Determines if an LValue with the given LValueBase will have an unsized
192 /// array in its designator.
193 /// Find the path length and type of the most-derived subobject in the given
194 /// path, and find the size of the containing array, if any.
195 static unsigned
196 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198 uint64_t &ArraySize, QualType &Type, bool &IsArray,
199 bool &FirstEntryIsUnsizedArray) {
200 // This only accepts LValueBases from APValues, and APValues don't support
201 // arrays that lack size info.
202 assert(!isBaseAnAllocSizeCall(Base) &&
203 "Unsized arrays shouldn't appear here");
204 unsigned MostDerivedLength = 0;
205 Type = getType(Base);
206
207 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
208 if (Type->isArrayType()) {
209 const ArrayType *AT = Ctx.getAsArrayType(Type);
210 Type = AT->getElementType();
211 MostDerivedLength = I + 1;
212 IsArray = true;
213
214 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
215 ArraySize = CAT->getZExtSize();
216 } else {
217 assert(I == 0 && "unexpected unsized array designator");
218 FirstEntryIsUnsizedArray = true;
219 ArraySize = AssumedSizeForUnsizedArray;
220 }
221 } else if (Type->isAnyComplexType()) {
222 const ComplexType *CT = Type->castAs<ComplexType>();
223 Type = CT->getElementType();
224 ArraySize = 2;
225 MostDerivedLength = I + 1;
226 IsArray = true;
227 } else if (const auto *VT = Type->getAs<VectorType>()) {
228 Type = VT->getElementType();
229 ArraySize = VT->getNumElements();
230 MostDerivedLength = I + 1;
231 IsArray = true;
232 } else if (const FieldDecl *FD = getAsField(Path[I])) {
233 Type = FD->getType();
234 ArraySize = 0;
235 MostDerivedLength = I + 1;
236 IsArray = false;
237 } else {
238 // Path[I] describes a base class.
239 ArraySize = 0;
240 IsArray = false;
241 }
242 }
243 return MostDerivedLength;
244 }
245
246 /// A path from a glvalue to a subobject of that glvalue.
247 struct SubobjectDesignator {
248 /// True if the subobject was named in a manner not supported by C++11. Such
249 /// lvalues can still be folded, but they are not core constant expressions
250 /// and we cannot perform lvalue-to-rvalue conversions on them.
251 LLVM_PREFERRED_TYPE(bool)
252 unsigned Invalid : 1;
253
254 /// Is this a pointer one past the end of an object?
255 LLVM_PREFERRED_TYPE(bool)
256 unsigned IsOnePastTheEnd : 1;
257
258 /// Indicator of whether the first entry is an unsized array.
259 LLVM_PREFERRED_TYPE(bool)
260 unsigned FirstEntryIsAnUnsizedArray : 1;
261
262 /// Indicator of whether the most-derived object is an array element.
263 LLVM_PREFERRED_TYPE(bool)
264 unsigned MostDerivedIsArrayElement : 1;
265
266 /// The length of the path to the most-derived object of which this is a
267 /// subobject.
268 unsigned MostDerivedPathLength : 28;
269
270 /// The size of the array of which the most-derived object is an element.
271 /// This will always be 0 if the most-derived object is not an array
272 /// element. 0 is not an indicator of whether or not the most-derived object
273 /// is an array, however, because 0-length arrays are allowed.
274 ///
275 /// If the current array is an unsized array, the value of this is
276 /// undefined.
277 uint64_t MostDerivedArraySize;
278 /// The type of the most derived object referred to by this address.
279 QualType MostDerivedType;
280
281 typedef APValue::LValuePathEntry PathEntry;
282
283 /// The entries on the path from the glvalue to the designated subobject.
285
286 SubobjectDesignator() : Invalid(true) {}
287
288 explicit SubobjectDesignator(QualType T)
289 : Invalid(false), IsOnePastTheEnd(false),
290 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
291 MostDerivedPathLength(0), MostDerivedArraySize(0),
292 MostDerivedType(T) {}
293
294 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
295 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
296 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
297 MostDerivedPathLength(0), MostDerivedArraySize(0) {
298 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
299 if (!Invalid) {
300 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
301 ArrayRef<PathEntry> VEntries = V.getLValuePath();
302 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
303 if (V.getLValueBase()) {
304 bool IsArray = false;
305 bool FirstIsUnsizedArray = false;
306 MostDerivedPathLength = findMostDerivedSubobject(
307 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
308 MostDerivedType, IsArray, FirstIsUnsizedArray);
309 MostDerivedIsArrayElement = IsArray;
310 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
311 }
312 }
313 }
314
315 void truncate(ASTContext &Ctx, APValue::LValueBase Base,
316 unsigned NewLength) {
317 if (Invalid)
318 return;
319
320 assert(Base && "cannot truncate path for null pointer");
321 assert(NewLength <= Entries.size() && "not a truncation");
322
323 if (NewLength == Entries.size())
324 return;
325 Entries.resize(NewLength);
326
327 bool IsArray = false;
328 bool FirstIsUnsizedArray = false;
329 MostDerivedPathLength = findMostDerivedSubobject(
330 Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
331 FirstIsUnsizedArray);
332 MostDerivedIsArrayElement = IsArray;
333 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
334 }
335
336 void setInvalid() {
337 Invalid = true;
338 Entries.clear();
339 }
340
341 /// Determine whether the most derived subobject is an array without a
342 /// known bound.
343 bool isMostDerivedAnUnsizedArray() const {
344 assert(!Invalid && "Calling this makes no sense on invalid designators");
345 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
346 }
347
348 /// Determine what the most derived array's size is. Results in an assertion
349 /// failure if the most derived array lacks a size.
350 uint64_t getMostDerivedArraySize() const {
351 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
352 return MostDerivedArraySize;
353 }
354
355 /// Determine whether this is a one-past-the-end pointer.
356 bool isOnePastTheEnd() const {
357 assert(!Invalid);
358 if (IsOnePastTheEnd)
359 return true;
360 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
361 Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
362 MostDerivedArraySize)
363 return true;
364 return false;
365 }
366
367 /// Get the range of valid index adjustments in the form
368 /// {maximum value that can be subtracted from this pointer,
369 /// maximum value that can be added to this pointer}
370 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
371 if (Invalid || isMostDerivedAnUnsizedArray())
372 return {0, 0};
373
374 // [expr.add]p4: For the purposes of these operators, a pointer to a
375 // nonarray object behaves the same as a pointer to the first element of
376 // an array of length one with the type of the object as its element type.
377 bool IsArray = MostDerivedPathLength == Entries.size() &&
378 MostDerivedIsArrayElement;
379 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
380 : (uint64_t)IsOnePastTheEnd;
381 uint64_t ArraySize =
382 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
383 return {ArrayIndex, ArraySize - ArrayIndex};
384 }
385
386 /// Check that this refers to a valid subobject.
387 bool isValidSubobject() const {
388 if (Invalid)
389 return false;
390 return !isOnePastTheEnd();
391 }
392 /// Check that this refers to a valid subobject, and if not, produce a
393 /// relevant diagnostic and set the designator as invalid.
394 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
395
396 /// Get the type of the designated object.
397 QualType getType(ASTContext &Ctx) const {
398 assert(!Invalid && "invalid designator has no subobject type");
399 return MostDerivedPathLength == Entries.size()
400 ? MostDerivedType
401 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
402 }
403
404 /// Update this designator to refer to the first element within this array.
405 void addArrayUnchecked(const ConstantArrayType *CAT) {
406 Entries.push_back(PathEntry::ArrayIndex(0));
407
408 // This is a most-derived object.
409 MostDerivedType = CAT->getElementType();
410 MostDerivedIsArrayElement = true;
411 MostDerivedArraySize = CAT->getZExtSize();
412 MostDerivedPathLength = Entries.size();
413 }
414 /// Update this designator to refer to the first element within the array of
415 /// elements of type T. This is an array of unknown size.
416 void addUnsizedArrayUnchecked(QualType ElemTy) {
417 Entries.push_back(PathEntry::ArrayIndex(0));
418
419 MostDerivedType = ElemTy;
420 MostDerivedIsArrayElement = true;
421 // The value in MostDerivedArraySize is undefined in this case. So, set it
422 // to an arbitrary value that's likely to loudly break things if it's
423 // used.
424 MostDerivedArraySize = AssumedSizeForUnsizedArray;
425 MostDerivedPathLength = Entries.size();
426 }
427 /// Update this designator to refer to the given base or member of this
428 /// object.
429 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
430 Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
431
432 // If this isn't a base class, it's a new most-derived object.
433 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434 MostDerivedType = FD->getType();
435 MostDerivedIsArrayElement = false;
436 MostDerivedArraySize = 0;
437 MostDerivedPathLength = Entries.size();
438 }
439 }
440 /// Update this designator to refer to the given complex component.
441 void addComplexUnchecked(QualType EltTy, bool Imag) {
442 Entries.push_back(PathEntry::ArrayIndex(Imag));
443
444 // This is technically a most-derived object, though in practice this
445 // is unlikely to matter.
446 MostDerivedType = EltTy;
447 MostDerivedIsArrayElement = true;
448 MostDerivedArraySize = 2;
449 MostDerivedPathLength = Entries.size();
450 }
451
452 void addVectorElementUnchecked(QualType EltTy, uint64_t Size,
453 uint64_t Idx) {
454 Entries.push_back(PathEntry::ArrayIndex(Idx));
455 MostDerivedType = EltTy;
456 MostDerivedPathLength = Entries.size();
457 MostDerivedArraySize = 0;
458 MostDerivedIsArrayElement = false;
459 }
460
461 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
462 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
463 const APSInt &N);
464 /// Add N to the address of this subobject.
465 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
466 if (Invalid || !N) return;
467 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
468 if (isMostDerivedAnUnsizedArray()) {
469 diagnoseUnsizedArrayPointerArithmetic(Info, E);
470 // Can't verify -- trust that the user is doing the right thing (or if
471 // not, trust that the caller will catch the bad behavior).
472 // FIXME: Should we reject if this overflows, at least?
473 Entries.back() = PathEntry::ArrayIndex(
474 Entries.back().getAsArrayIndex() + TruncatedN);
475 return;
476 }
477
478 // [expr.add]p4: For the purposes of these operators, a pointer to a
479 // nonarray object behaves the same as a pointer to the first element of
480 // an array of length one with the type of the object as its element type.
481 bool IsArray = MostDerivedPathLength == Entries.size() &&
482 MostDerivedIsArrayElement;
483 uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
484 : (uint64_t)IsOnePastTheEnd;
485 uint64_t ArraySize =
486 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
487
488 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
489 // Calculate the actual index in a wide enough type, so we can include
490 // it in the note.
491 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
492 (llvm::APInt&)N += ArrayIndex;
493 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
494 diagnosePointerArithmetic(Info, E, N);
495 setInvalid();
496 return;
497 }
498
499 ArrayIndex += TruncatedN;
500 assert(ArrayIndex <= ArraySize &&
501 "bounds check succeeded for out-of-bounds index");
502
503 if (IsArray)
504 Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
505 else
506 IsOnePastTheEnd = (ArrayIndex != 0);
507 }
508 };
509
510 /// A scope at the end of which an object can need to be destroyed.
511 enum class ScopeKind {
512 Block,
513 FullExpression,
514 Call
515 };
516
517 /// A reference to a particular call and its arguments.
518 struct CallRef {
519 CallRef() : OrigCallee(), CallIndex(0), Version() {}
520 CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
521 : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
522
523 explicit operator bool() const { return OrigCallee; }
524
525 /// Get the parameter that the caller initialized, corresponding to the
526 /// given parameter in the callee.
527 const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
528 return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
529 : PVD;
530 }
531
532 /// The callee at the point where the arguments were evaluated. This might
533 /// be different from the actual callee (a different redeclaration, or a
534 /// virtual override), but this function's parameters are the ones that
535 /// appear in the parameter map.
536 const FunctionDecl *OrigCallee;
537 /// The call index of the frame that holds the argument values.
538 unsigned CallIndex;
539 /// The version of the parameters corresponding to this call.
540 unsigned Version;
541 };
542
543 /// A stack frame in the constexpr call stack.
544 class CallStackFrame : public interp::Frame {
545 public:
546 EvalInfo &Info;
547
548 /// Parent - The caller of this stack frame.
549 CallStackFrame *Caller;
550
551 /// Callee - The function which was called.
552 const FunctionDecl *Callee;
553
554 /// This - The binding for the this pointer in this call, if any.
555 const LValue *This;
556
557 /// CallExpr - The syntactical structure of member function calls
558 const Expr *CallExpr;
559
560 /// Information on how to find the arguments to this call. Our arguments
561 /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
562 /// key and this value as the version.
563 CallRef Arguments;
564
565 /// Source location information about the default argument or default
566 /// initializer expression we're evaluating, if any.
567 CurrentSourceLocExprScope CurSourceLocExprScope;
568
569 // Note that we intentionally use std::map here so that references to
570 // values are stable.
571 typedef std::pair<const void *, unsigned> MapKeyTy;
572 typedef std::map<MapKeyTy, APValue> MapTy;
573 /// Temporaries - Temporary lvalues materialized within this stack frame.
574 MapTy Temporaries;
575 MapTy ConstexprUnknownAPValues;
576
577 /// CallRange - The source range of the call expression for this call.
578 SourceRange CallRange;
579
580 /// Index - The call index of this call.
581 unsigned Index;
582
583 /// The stack of integers for tracking version numbers for temporaries.
584 SmallVector<unsigned, 2> TempVersionStack = {1};
585 unsigned CurTempVersion = TempVersionStack.back();
586
587 unsigned getTempVersion() const { return TempVersionStack.back(); }
588
589 void pushTempVersion() {
590 TempVersionStack.push_back(++CurTempVersion);
591 }
592
593 void popTempVersion() {
594 TempVersionStack.pop_back();
595 }
596
597 CallRef createCall(const FunctionDecl *Callee) {
598 return {Callee, Index, ++CurTempVersion};
599 }
600
601 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
602 // on the overall stack usage of deeply-recursing constexpr evaluations.
603 // (We should cache this map rather than recomputing it repeatedly.)
604 // But let's try this and see how it goes; we can look into caching the map
605 // as a later change.
606
607 /// LambdaCaptureFields - Mapping from captured variables/this to
608 /// corresponding data members in the closure class.
609 llvm::DenseMap<const ValueDecl *, FieldDecl *> LambdaCaptureFields;
610 FieldDecl *LambdaThisCaptureField = nullptr;
611
612 CallStackFrame(EvalInfo &Info, SourceRange CallRange,
613 const FunctionDecl *Callee, const LValue *This,
614 const Expr *CallExpr, CallRef Arguments);
615 ~CallStackFrame();
616
617 // Return the temporary for Key whose version number is Version.
618 APValue *getTemporary(const void *Key, unsigned Version) {
619 MapKeyTy KV(Key, Version);
620 auto LB = Temporaries.lower_bound(KV);
621 if (LB != Temporaries.end() && LB->first == KV)
622 return &LB->second;
623 return nullptr;
624 }
625
626 // Return the current temporary for Key in the map.
627 APValue *getCurrentTemporary(const void *Key) {
628 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
629 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
630 return &std::prev(UB)->second;
631 return nullptr;
632 }
633
634 // Return the version number of the current temporary for Key.
635 unsigned getCurrentTemporaryVersion(const void *Key) const {
636 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
637 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
638 return std::prev(UB)->first.second;
639 return 0;
640 }
641
642 /// Allocate storage for an object of type T in this stack frame.
643 /// Populates LV with a handle to the created object. Key identifies
644 /// the temporary within the stack frame, and must not be reused without
645 /// bumping the temporary version number.
646 template<typename KeyT>
647 APValue &createTemporary(const KeyT *Key, QualType T,
648 ScopeKind Scope, LValue &LV);
649
650 APValue &createConstexprUnknownAPValues(const VarDecl *Key,
652
653 /// Allocate storage for a parameter of a function call made in this frame.
654 APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
655
656 void describe(llvm::raw_ostream &OS) const override;
657
658 Frame *getCaller() const override { return Caller; }
659 SourceRange getCallRange() const override { return CallRange; }
660 const FunctionDecl *getCallee() const override { return Callee; }
661
662 bool isStdFunction() const {
663 for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
664 if (DC->isStdNamespace())
665 return true;
666 return false;
667 }
668
669 /// Whether we're in a context where [[msvc::constexpr]] evaluation is
670 /// permitted. See MSConstexprDocs for description of permitted contexts.
671 bool CanEvalMSConstexpr = false;
672
673 private:
674 APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
675 ScopeKind Scope);
676 };
677
678 /// Temporarily override 'this'.
679 class ThisOverrideRAII {
680 public:
681 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
682 : Frame(Frame), OldThis(Frame.This) {
683 if (Enable)
684 Frame.This = NewThis;
685 }
686 ~ThisOverrideRAII() {
687 Frame.This = OldThis;
688 }
689 private:
690 CallStackFrame &Frame;
691 const LValue *OldThis;
692 };
693
694 // A shorthand time trace scope struct, prints source range, for example
695 // {"name":"EvaluateAsRValue","args":{"detail":"<test.cc:8:21, col:25>"}}}
696 class ExprTimeTraceScope {
697 public:
698 ExprTimeTraceScope(const Expr *E, const ASTContext &Ctx, StringRef Name)
699 : TimeScope(Name, [E, &Ctx] {
700 return E->getSourceRange().printToString(Ctx.getSourceManager());
701 }) {}
702
703 private:
704 llvm::TimeTraceScope TimeScope;
705 };
706
707 /// RAII object used to change the current ability of
708 /// [[msvc::constexpr]] evaulation.
709 struct MSConstexprContextRAII {
710 CallStackFrame &Frame;
711 bool OldValue;
712 explicit MSConstexprContextRAII(CallStackFrame &Frame, bool Value)
713 : Frame(Frame), OldValue(Frame.CanEvalMSConstexpr) {
714 Frame.CanEvalMSConstexpr = Value;
715 }
716
717 ~MSConstexprContextRAII() { Frame.CanEvalMSConstexpr = OldValue; }
718 };
719}
720
721static bool HandleDestruction(EvalInfo &Info, const Expr *E,
722 const LValue &This, QualType ThisType);
723static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
725 QualType T);
726
727namespace {
728 /// A cleanup, and a flag indicating whether it is lifetime-extended.
729 class Cleanup {
730 llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
732 QualType T;
733
734 public:
735 Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
736 ScopeKind Scope)
737 : Value(Val, Scope), Base(Base), T(T) {}
738
739 /// Determine whether this cleanup should be performed at the end of the
740 /// given kind of scope.
741 bool isDestroyedAtEndOf(ScopeKind K) const {
742 return (int)Value.getInt() >= (int)K;
743 }
744 bool endLifetime(EvalInfo &Info, bool RunDestructors) {
745 if (RunDestructors) {
747 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
748 Loc = VD->getLocation();
749 else if (const Expr *E = Base.dyn_cast<const Expr*>())
750 Loc = E->getExprLoc();
751 return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
752 }
753 *Value.getPointer() = APValue();
754 return true;
755 }
756
757 bool hasSideEffect() {
758 return T.isDestructedType();
759 }
760 };
761
762 /// A reference to an object whose construction we are currently evaluating.
763 struct ObjectUnderConstruction {
766 friend bool operator==(const ObjectUnderConstruction &LHS,
767 const ObjectUnderConstruction &RHS) {
768 return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
769 }
770 friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
771 return llvm::hash_combine(Obj.Base, Obj.Path);
772 }
773 };
774 enum class ConstructionPhase {
775 None,
776 Bases,
777 AfterBases,
778 AfterFields,
779 Destroying,
780 DestroyingBases
781 };
782}
783
784namespace llvm {
785template<> struct DenseMapInfo<ObjectUnderConstruction> {
786 using Base = DenseMapInfo<APValue::LValueBase>;
787 static ObjectUnderConstruction getEmptyKey() {
788 return {Base::getEmptyKey(), {}}; }
789 static ObjectUnderConstruction getTombstoneKey() {
790 return {Base::getTombstoneKey(), {}};
791 }
792 static unsigned getHashValue(const ObjectUnderConstruction &Object) {
793 return hash_value(Object);
794 }
795 static bool isEqual(const ObjectUnderConstruction &LHS,
796 const ObjectUnderConstruction &RHS) {
797 return LHS == RHS;
798 }
799};
800}
801
802namespace {
803 /// A dynamically-allocated heap object.
804 struct DynAlloc {
805 /// The value of this heap-allocated object.
807 /// The allocating expression; used for diagnostics. Either a CXXNewExpr
808 /// or a CallExpr (the latter is for direct calls to operator new inside
809 /// std::allocator<T>::allocate).
810 const Expr *AllocExpr = nullptr;
811
812 enum Kind {
813 New,
814 ArrayNew,
815 StdAllocator
816 };
817
818 /// Get the kind of the allocation. This must match between allocation
819 /// and deallocation.
820 Kind getKind() const {
821 if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
822 return NE->isArray() ? ArrayNew : New;
823 assert(isa<CallExpr>(AllocExpr));
824 return StdAllocator;
825 }
826 };
827
828 struct DynAllocOrder {
829 bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
830 return L.getIndex() < R.getIndex();
831 }
832 };
833
834 /// EvalInfo - This is a private struct used by the evaluator to capture
835 /// information about a subexpression as it is folded. It retains information
836 /// about the AST context, but also maintains information about the folded
837 /// expression.
838 ///
839 /// If an expression could be evaluated, it is still possible it is not a C
840 /// "integer constant expression" or constant expression. If not, this struct
841 /// captures information about how and why not.
842 ///
843 /// One bit of information passed *into* the request for constant folding
844 /// indicates whether the subexpression is "evaluated" or not according to C
845 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
846 /// evaluate the expression regardless of what the RHS is, but C only allows
847 /// certain things in certain situations.
848 class EvalInfo : public interp::State {
849 public:
850 ASTContext &Ctx;
851
852 /// EvalStatus - Contains information about the evaluation.
853 Expr::EvalStatus &EvalStatus;
854
855 /// CurrentCall - The top of the constexpr call stack.
856 CallStackFrame *CurrentCall;
857
858 /// CallStackDepth - The number of calls in the call stack right now.
859 unsigned CallStackDepth;
860
861 /// NextCallIndex - The next call index to assign.
862 unsigned NextCallIndex;
863
864 /// StepsLeft - The remaining number of evaluation steps we're permitted
865 /// to perform. This is essentially a limit for the number of statements
866 /// we will evaluate.
867 unsigned StepsLeft;
868
869 /// Enable the experimental new constant interpreter. If an expression is
870 /// not supported by the interpreter, an error is triggered.
871 bool EnableNewConstInterp;
872
873 /// BottomFrame - The frame in which evaluation started. This must be
874 /// initialized after CurrentCall and CallStackDepth.
875 CallStackFrame BottomFrame;
876
877 /// A stack of values whose lifetimes end at the end of some surrounding
878 /// evaluation frame.
880
881 /// EvaluatingDecl - This is the declaration whose initializer is being
882 /// evaluated, if any.
883 APValue::LValueBase EvaluatingDecl;
884
885 enum class EvaluatingDeclKind {
886 None,
887 /// We're evaluating the construction of EvaluatingDecl.
888 Ctor,
889 /// We're evaluating the destruction of EvaluatingDecl.
890 Dtor,
891 };
892 EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
893
894 /// EvaluatingDeclValue - This is the value being constructed for the
895 /// declaration whose initializer is being evaluated, if any.
896 APValue *EvaluatingDeclValue;
897
898 /// Set of objects that are currently being constructed.
899 llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
900 ObjectsUnderConstruction;
901
902 /// Current heap allocations, along with the location where each was
903 /// allocated. We use std::map here because we need stable addresses
904 /// for the stored APValues.
905 std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
906
907 /// The number of heap allocations performed so far in this evaluation.
908 unsigned NumHeapAllocs = 0;
909
910 struct EvaluatingConstructorRAII {
911 EvalInfo &EI;
912 ObjectUnderConstruction Object;
913 bool DidInsert;
914 EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
915 bool HasBases)
916 : EI(EI), Object(Object) {
917 DidInsert =
918 EI.ObjectsUnderConstruction
919 .insert({Object, HasBases ? ConstructionPhase::Bases
920 : ConstructionPhase::AfterBases})
921 .second;
922 }
923 void finishedConstructingBases() {
924 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
925 }
926 void finishedConstructingFields() {
927 EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
928 }
929 ~EvaluatingConstructorRAII() {
930 if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
931 }
932 };
933
934 struct EvaluatingDestructorRAII {
935 EvalInfo &EI;
936 ObjectUnderConstruction Object;
937 bool DidInsert;
938 EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
939 : EI(EI), Object(Object) {
940 DidInsert = EI.ObjectsUnderConstruction
941 .insert({Object, ConstructionPhase::Destroying})
942 .second;
943 }
944 void startedDestroyingBases() {
945 EI.ObjectsUnderConstruction[Object] =
946 ConstructionPhase::DestroyingBases;
947 }
948 ~EvaluatingDestructorRAII() {
949 if (DidInsert)
950 EI.ObjectsUnderConstruction.erase(Object);
951 }
952 };
953
954 ConstructionPhase
955 isEvaluatingCtorDtor(APValue::LValueBase Base,
957 return ObjectsUnderConstruction.lookup({Base, Path});
958 }
959
960 /// If we're currently speculatively evaluating, the outermost call stack
961 /// depth at which we can mutate state, otherwise 0.
962 unsigned SpeculativeEvaluationDepth = 0;
963
964 /// The current array initialization index, if we're performing array
965 /// initialization.
966 uint64_t ArrayInitIndex = -1;
967
968 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
969 /// notes attached to it will also be stored, otherwise they will not be.
970 bool HasActiveDiagnostic;
971
972 /// Have we emitted a diagnostic explaining why we couldn't constant
973 /// fold (not just why it's not strictly a constant expression)?
974 bool HasFoldFailureDiagnostic;
975
976 /// Whether we're checking that an expression is a potential constant
977 /// expression. If so, do not fail on constructs that could become constant
978 /// later on (such as a use of an undefined global).
979 bool CheckingPotentialConstantExpression = false;
980
981 /// Whether we're checking for an expression that has undefined behavior.
982 /// If so, we will produce warnings if we encounter an operation that is
983 /// always undefined.
984 ///
985 /// Note that we still need to evaluate the expression normally when this
986 /// is set; this is used when evaluating ICEs in C.
987 bool CheckingForUndefinedBehavior = false;
988
989 enum EvaluationMode {
990 /// Evaluate as a constant expression. Stop if we find that the expression
991 /// is not a constant expression.
992 EM_ConstantExpression,
993
994 /// Evaluate as a constant expression. Stop if we find that the expression
995 /// is not a constant expression. Some expressions can be retried in the
996 /// optimizer if we don't constant fold them here, but in an unevaluated
997 /// context we try to fold them immediately since the optimizer never
998 /// gets a chance to look at it.
999 EM_ConstantExpressionUnevaluated,
1000
1001 /// Fold the expression to a constant. Stop if we hit a side-effect that
1002 /// we can't model.
1003 EM_ConstantFold,
1004
1005 /// Evaluate in any way we know how. Don't worry about side-effects that
1006 /// can't be modeled.
1007 EM_IgnoreSideEffects,
1008 } EvalMode;
1009
1010 /// Are we checking whether the expression is a potential constant
1011 /// expression?
1012 bool checkingPotentialConstantExpression() const override {
1013 return CheckingPotentialConstantExpression;
1014 }
1015
1016 /// Are we checking an expression for overflow?
1017 // FIXME: We should check for any kind of undefined or suspicious behavior
1018 // in such constructs, not just overflow.
1019 bool checkingForUndefinedBehavior() const override {
1020 return CheckingForUndefinedBehavior;
1021 }
1022
1023 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
1024 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
1025 CallStackDepth(0), NextCallIndex(1),
1026 StepsLeft(C.getLangOpts().ConstexprStepLimit),
1027 EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
1028 BottomFrame(*this, SourceLocation(), /*Callee=*/nullptr,
1029 /*This=*/nullptr,
1030 /*CallExpr=*/nullptr, CallRef()),
1031 EvaluatingDecl((const ValueDecl *)nullptr),
1032 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
1033 HasFoldFailureDiagnostic(false), EvalMode(Mode) {}
1034
1035 ~EvalInfo() {
1036 discardCleanups();
1037 }
1038
1039 ASTContext &getASTContext() const override { return Ctx; }
1040
1041 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
1042 EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
1043 EvaluatingDecl = Base;
1044 IsEvaluatingDecl = EDK;
1045 EvaluatingDeclValue = &Value;
1046 }
1047
1048 bool CheckCallLimit(SourceLocation Loc) {
1049 // Don't perform any constexpr calls (other than the call we're checking)
1050 // when checking a potential constant expression.
1051 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1052 return false;
1053 if (NextCallIndex == 0) {
1054 // NextCallIndex has wrapped around.
1055 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1056 return false;
1057 }
1058 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1059 return true;
1060 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1061 << getLangOpts().ConstexprCallDepth;
1062 return false;
1063 }
1064
1065 bool CheckArraySize(SourceLocation Loc, unsigned BitWidth,
1066 uint64_t ElemCount, bool Diag) {
1067 // FIXME: GH63562
1068 // APValue stores array extents as unsigned,
1069 // so anything that is greater that unsigned would overflow when
1070 // constructing the array, we catch this here.
1071 if (BitWidth > ConstantArrayType::getMaxSizeBits(Ctx) ||
1072 ElemCount > uint64_t(std::numeric_limits<unsigned>::max())) {
1073 if (Diag)
1074 FFDiag(Loc, diag::note_constexpr_new_too_large) << ElemCount;
1075 return false;
1076 }
1077
1078 // FIXME: GH63562
1079 // Arrays allocate an APValue per element.
1080 // We use the number of constexpr steps as a proxy for the maximum size
1081 // of arrays to avoid exhausting the system resources, as initialization
1082 // of each element is likely to take some number of steps anyway.
1083 uint64_t Limit = Ctx.getLangOpts().ConstexprStepLimit;
1084 if (ElemCount > Limit) {
1085 if (Diag)
1086 FFDiag(Loc, diag::note_constexpr_new_exceeds_limits)
1087 << ElemCount << Limit;
1088 return false;
1089 }
1090 return true;
1091 }
1092
1093 std::pair<CallStackFrame *, unsigned>
1094 getCallFrameAndDepth(unsigned CallIndex) {
1095 assert(CallIndex && "no call index in getCallFrameAndDepth");
1096 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1097 // be null in this loop.
1098 unsigned Depth = CallStackDepth;
1099 CallStackFrame *Frame = CurrentCall;
1100 while (Frame->Index > CallIndex) {
1101 Frame = Frame->Caller;
1102 --Depth;
1103 }
1104 if (Frame->Index == CallIndex)
1105 return {Frame, Depth};
1106 return {nullptr, 0};
1107 }
1108
1109 bool nextStep(const Stmt *S) {
1110 if (!StepsLeft) {
1111 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1112 return false;
1113 }
1114 --StepsLeft;
1115 return true;
1116 }
1117
1118 APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1119
1120 std::optional<DynAlloc *> lookupDynamicAlloc(DynamicAllocLValue DA) {
1121 std::optional<DynAlloc *> Result;
1122 auto It = HeapAllocs.find(DA);
1123 if (It != HeapAllocs.end())
1124 Result = &It->second;
1125 return Result;
1126 }
1127
1128 /// Get the allocated storage for the given parameter of the given call.
1129 APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1130 CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1131 return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1132 : nullptr;
1133 }
1134
1135 /// Information about a stack frame for std::allocator<T>::[de]allocate.
1136 struct StdAllocatorCaller {
1137 unsigned FrameIndex;
1138 QualType ElemType;
1139 const Expr *Call;
1140 explicit operator bool() const { return FrameIndex != 0; };
1141 };
1142
1143 StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1144 for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1145 Call = Call->Caller) {
1146 const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1147 if (!MD)
1148 continue;
1149 const IdentifierInfo *FnII = MD->getIdentifier();
1150 if (!FnII || !FnII->isStr(FnName))
1151 continue;
1152
1153 const auto *CTSD =
1154 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1155 if (!CTSD)
1156 continue;
1157
1158 const IdentifierInfo *ClassII = CTSD->getIdentifier();
1159 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1160 if (CTSD->isInStdNamespace() && ClassII &&
1161 ClassII->isStr("allocator") && TAL.size() >= 1 &&
1162 TAL[0].getKind() == TemplateArgument::Type)
1163 return {Call->Index, TAL[0].getAsType(), Call->CallExpr};
1164 }
1165
1166 return {};
1167 }
1168
1169 void performLifetimeExtension() {
1170 // Disable the cleanups for lifetime-extended temporaries.
1171 llvm::erase_if(CleanupStack, [](Cleanup &C) {
1172 return !C.isDestroyedAtEndOf(ScopeKind::FullExpression);
1173 });
1174 }
1175
1176 /// Throw away any remaining cleanups at the end of evaluation. If any
1177 /// cleanups would have had a side-effect, note that as an unmodeled
1178 /// side-effect and return false. Otherwise, return true.
1179 bool discardCleanups() {
1180 for (Cleanup &C : CleanupStack) {
1181 if (C.hasSideEffect() && !noteSideEffect()) {
1182 CleanupStack.clear();
1183 return false;
1184 }
1185 }
1186 CleanupStack.clear();
1187 return true;
1188 }
1189
1190 private:
1191 interp::Frame *getCurrentFrame() override { return CurrentCall; }
1192 const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1193
1194 bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1195 void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1196
1197 void setFoldFailureDiagnostic(bool Flag) override {
1198 HasFoldFailureDiagnostic = Flag;
1199 }
1200
1201 Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1202
1203 // If we have a prior diagnostic, it will be noting that the expression
1204 // isn't a constant expression. This diagnostic is more important,
1205 // unless we require this evaluation to produce a constant expression.
1206 //
1207 // FIXME: We might want to show both diagnostics to the user in
1208 // EM_ConstantFold mode.
1209 bool hasPriorDiagnostic() override {
1210 if (!EvalStatus.Diag->empty()) {
1211 switch (EvalMode) {
1212 case EM_ConstantFold:
1213 case EM_IgnoreSideEffects:
1214 if (!HasFoldFailureDiagnostic)
1215 break;
1216 // We've already failed to fold something. Keep that diagnostic.
1217 [[fallthrough]];
1218 case EM_ConstantExpression:
1219 case EM_ConstantExpressionUnevaluated:
1220 setActiveDiagnostic(false);
1221 return true;
1222 }
1223 }
1224 return false;
1225 }
1226
1227 unsigned getCallStackDepth() override { return CallStackDepth; }
1228
1229 public:
1230 /// Should we continue evaluation after encountering a side-effect that we
1231 /// couldn't model?
1232 bool keepEvaluatingAfterSideEffect() const override {
1233 switch (EvalMode) {
1234 case EM_IgnoreSideEffects:
1235 return true;
1236
1237 case EM_ConstantExpression:
1238 case EM_ConstantExpressionUnevaluated:
1239 case EM_ConstantFold:
1240 // By default, assume any side effect might be valid in some other
1241 // evaluation of this expression from a different context.
1242 return checkingPotentialConstantExpression() ||
1243 checkingForUndefinedBehavior();
1244 }
1245 llvm_unreachable("Missed EvalMode case");
1246 }
1247
1248 /// Note that we have had a side-effect, and determine whether we should
1249 /// keep evaluating.
1250 bool noteSideEffect() override {
1251 EvalStatus.HasSideEffects = true;
1252 return keepEvaluatingAfterSideEffect();
1253 }
1254
1255 /// Should we continue evaluation after encountering undefined behavior?
1256 bool keepEvaluatingAfterUndefinedBehavior() {
1257 switch (EvalMode) {
1258 case EM_IgnoreSideEffects:
1259 case EM_ConstantFold:
1260 return true;
1261
1262 case EM_ConstantExpression:
1263 case EM_ConstantExpressionUnevaluated:
1264 return checkingForUndefinedBehavior();
1265 }
1266 llvm_unreachable("Missed EvalMode case");
1267 }
1268
1269 /// Note that we hit something that was technically undefined behavior, but
1270 /// that we can evaluate past it (such as signed overflow or floating-point
1271 /// division by zero.)
1272 bool noteUndefinedBehavior() override {
1273 EvalStatus.HasUndefinedBehavior = true;
1274 return keepEvaluatingAfterUndefinedBehavior();
1275 }
1276
1277 /// Should we continue evaluation as much as possible after encountering a
1278 /// construct which can't be reduced to a value?
1279 bool keepEvaluatingAfterFailure() const override {
1280 if (!StepsLeft)
1281 return false;
1282
1283 switch (EvalMode) {
1284 case EM_ConstantExpression:
1285 case EM_ConstantExpressionUnevaluated:
1286 case EM_ConstantFold:
1287 case EM_IgnoreSideEffects:
1288 return checkingPotentialConstantExpression() ||
1289 checkingForUndefinedBehavior();
1290 }
1291 llvm_unreachable("Missed EvalMode case");
1292 }
1293
1294 /// Notes that we failed to evaluate an expression that other expressions
1295 /// directly depend on, and determine if we should keep evaluating. This
1296 /// should only be called if we actually intend to keep evaluating.
1297 ///
1298 /// Call noteSideEffect() instead if we may be able to ignore the value that
1299 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1300 ///
1301 /// (Foo(), 1) // use noteSideEffect
1302 /// (Foo() || true) // use noteSideEffect
1303 /// Foo() + 1 // use noteFailure
1304 [[nodiscard]] bool noteFailure() {
1305 // Failure when evaluating some expression often means there is some
1306 // subexpression whose evaluation was skipped. Therefore, (because we
1307 // don't track whether we skipped an expression when unwinding after an
1308 // evaluation failure) every evaluation failure that bubbles up from a
1309 // subexpression implies that a side-effect has potentially happened. We
1310 // skip setting the HasSideEffects flag to true until we decide to
1311 // continue evaluating after that point, which happens here.
1312 bool KeepGoing = keepEvaluatingAfterFailure();
1313 EvalStatus.HasSideEffects |= KeepGoing;
1314 return KeepGoing;
1315 }
1316
1317 class ArrayInitLoopIndex {
1318 EvalInfo &Info;
1319 uint64_t OuterIndex;
1320
1321 public:
1322 ArrayInitLoopIndex(EvalInfo &Info)
1323 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1324 Info.ArrayInitIndex = 0;
1325 }
1326 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1327
1328 operator uint64_t&() { return Info.ArrayInitIndex; }
1329 };
1330 };
1331
1332 /// Object used to treat all foldable expressions as constant expressions.
1333 struct FoldConstant {
1334 EvalInfo &Info;
1335 bool Enabled;
1336 bool HadNoPriorDiags;
1337 EvalInfo::EvaluationMode OldMode;
1338
1339 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1340 : Info(Info),
1341 Enabled(Enabled),
1342 HadNoPriorDiags(Info.EvalStatus.Diag &&
1343 Info.EvalStatus.Diag->empty() &&
1344 !Info.EvalStatus.HasSideEffects),
1345 OldMode(Info.EvalMode) {
1346 if (Enabled)
1347 Info.EvalMode = EvalInfo::EM_ConstantFold;
1348 }
1349 void keepDiagnostics() { Enabled = false; }
1350 ~FoldConstant() {
1351 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1352 !Info.EvalStatus.HasSideEffects)
1353 Info.EvalStatus.Diag->clear();
1354 Info.EvalMode = OldMode;
1355 }
1356 };
1357
1358 /// RAII object used to set the current evaluation mode to ignore
1359 /// side-effects.
1360 struct IgnoreSideEffectsRAII {
1361 EvalInfo &Info;
1362 EvalInfo::EvaluationMode OldMode;
1363 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1364 : Info(Info), OldMode(Info.EvalMode) {
1365 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1366 }
1367
1368 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1369 };
1370
1371 /// RAII object used to optionally suppress diagnostics and side-effects from
1372 /// a speculative evaluation.
1373 class SpeculativeEvaluationRAII {
1374 EvalInfo *Info = nullptr;
1375 Expr::EvalStatus OldStatus;
1376 unsigned OldSpeculativeEvaluationDepth = 0;
1377
1378 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1379 Info = Other.Info;
1380 OldStatus = Other.OldStatus;
1381 OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1382 Other.Info = nullptr;
1383 }
1384
1385 void maybeRestoreState() {
1386 if (!Info)
1387 return;
1388
1389 Info->EvalStatus = OldStatus;
1390 Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1391 }
1392
1393 public:
1394 SpeculativeEvaluationRAII() = default;
1395
1396 SpeculativeEvaluationRAII(
1397 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1398 : Info(&Info), OldStatus(Info.EvalStatus),
1399 OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1400 Info.EvalStatus.Diag = NewDiag;
1401 Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1402 }
1403
1404 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1405 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1406 moveFromAndCancel(std::move(Other));
1407 }
1408
1409 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1410 maybeRestoreState();
1411 moveFromAndCancel(std::move(Other));
1412 return *this;
1413 }
1414
1415 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1416 };
1417
1418 /// RAII object wrapping a full-expression or block scope, and handling
1419 /// the ending of the lifetime of temporaries created within it.
1420 template<ScopeKind Kind>
1421 class ScopeRAII {
1422 EvalInfo &Info;
1423 unsigned OldStackSize;
1424 public:
1425 ScopeRAII(EvalInfo &Info)
1426 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1427 // Push a new temporary version. This is needed to distinguish between
1428 // temporaries created in different iterations of a loop.
1429 Info.CurrentCall->pushTempVersion();
1430 }
1431 bool destroy(bool RunDestructors = true) {
1432 bool OK = cleanup(Info, RunDestructors, OldStackSize);
1433 OldStackSize = -1U;
1434 return OK;
1435 }
1436 ~ScopeRAII() {
1437 if (OldStackSize != -1U)
1438 destroy(false);
1439 // Body moved to a static method to encourage the compiler to inline away
1440 // instances of this class.
1441 Info.CurrentCall->popTempVersion();
1442 }
1443 private:
1444 static bool cleanup(EvalInfo &Info, bool RunDestructors,
1445 unsigned OldStackSize) {
1446 assert(OldStackSize <= Info.CleanupStack.size() &&
1447 "running cleanups out of order?");
1448
1449 // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1450 // for a full-expression scope.
1451 bool Success = true;
1452 for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1453 if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1454 if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1455 Success = false;
1456 break;
1457 }
1458 }
1459 }
1460
1461 // Compact any retained cleanups.
1462 auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1463 if (Kind != ScopeKind::Block)
1464 NewEnd =
1465 std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1466 return C.isDestroyedAtEndOf(Kind);
1467 });
1468 Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1469 return Success;
1470 }
1471 };
1472 typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1473 typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1474 typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1475}
1476
1477bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1478 CheckSubobjectKind CSK) {
1479 if (Invalid)
1480 return false;
1481 if (isOnePastTheEnd()) {
1482 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1483 << CSK;
1484 setInvalid();
1485 return false;
1486 }
1487 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1488 // must actually be at least one array element; even a VLA cannot have a
1489 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1490 return true;
1491}
1492
1493void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1494 const Expr *E) {
1495 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1496 // Do not set the designator as invalid: we can represent this situation,
1497 // and correct handling of __builtin_object_size requires us to do so.
1498}
1499
1500void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1501 const Expr *E,
1502 const APSInt &N) {
1503 // If we're complaining, we must be able to statically determine the size of
1504 // the most derived array.
1505 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1506 Info.CCEDiag(E, diag::note_constexpr_array_index)
1507 << N << /*array*/ 0
1508 << static_cast<unsigned>(getMostDerivedArraySize());
1509 else
1510 Info.CCEDiag(E, diag::note_constexpr_array_index)
1511 << N << /*non-array*/ 1;
1512 setInvalid();
1513}
1514
1515CallStackFrame::CallStackFrame(EvalInfo &Info, SourceRange CallRange,
1516 const FunctionDecl *Callee, const LValue *This,
1517 const Expr *CallExpr, CallRef Call)
1518 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1519 CallExpr(CallExpr), Arguments(Call), CallRange(CallRange),
1520 Index(Info.NextCallIndex++) {
1521 Info.CurrentCall = this;
1522 ++Info.CallStackDepth;
1523}
1524
1525CallStackFrame::~CallStackFrame() {
1526 assert(Info.CurrentCall == this && "calls retired out of order");
1527 --Info.CallStackDepth;
1528 Info.CurrentCall = Caller;
1529}
1530
1531static bool isRead(AccessKinds AK) {
1532 return AK == AK_Read || AK == AK_ReadObjectRepresentation ||
1533 AK == AK_IsWithinLifetime;
1534}
1535
1537 switch (AK) {
1538 case AK_Read:
1540 case AK_MemberCall:
1541 case AK_DynamicCast:
1542 case AK_TypeId:
1544 return false;
1545 case AK_Assign:
1546 case AK_Increment:
1547 case AK_Decrement:
1548 case AK_Construct:
1549 case AK_Destroy:
1550 return true;
1551 }
1552 llvm_unreachable("unknown access kind");
1553}
1554
1555static bool isAnyAccess(AccessKinds AK) {
1556 return isRead(AK) || isModification(AK);
1557}
1558
1559/// Is this an access per the C++ definition?
1561 return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy &&
1562 AK != AK_IsWithinLifetime;
1563}
1564
1565/// Is this kind of axcess valid on an indeterminate object value?
1567 switch (AK) {
1568 case AK_Read:
1569 case AK_Increment:
1570 case AK_Decrement:
1571 // These need the object's value.
1572 return false;
1573
1576 case AK_Assign:
1577 case AK_Construct:
1578 case AK_Destroy:
1579 // Construction and destruction don't need the value.
1580 return true;
1581
1582 case AK_MemberCall:
1583 case AK_DynamicCast:
1584 case AK_TypeId:
1585 // These aren't really meaningful on scalars.
1586 return true;
1587 }
1588 llvm_unreachable("unknown access kind");
1589}
1590
1591namespace {
1592 struct ComplexValue {
1593 private:
1594 bool IsInt;
1595
1596 public:
1597 APSInt IntReal, IntImag;
1598 APFloat FloatReal, FloatImag;
1599
1600 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1601
1602 void makeComplexFloat() { IsInt = false; }
1603 bool isComplexFloat() const { return !IsInt; }
1604 APFloat &getComplexFloatReal() { return FloatReal; }
1605 APFloat &getComplexFloatImag() { return FloatImag; }
1606
1607 void makeComplexInt() { IsInt = true; }
1608 bool isComplexInt() const { return IsInt; }
1609 APSInt &getComplexIntReal() { return IntReal; }
1610 APSInt &getComplexIntImag() { return IntImag; }
1611
1612 void moveInto(APValue &v) const {
1613 if (isComplexFloat())
1614 v = APValue(FloatReal, FloatImag);
1615 else
1616 v = APValue(IntReal, IntImag);
1617 }
1618 void setFrom(const APValue &v) {
1619 assert(v.isComplexFloat() || v.isComplexInt());
1620 if (v.isComplexFloat()) {
1621 makeComplexFloat();
1622 FloatReal = v.getComplexFloatReal();
1623 FloatImag = v.getComplexFloatImag();
1624 } else {
1625 makeComplexInt();
1626 IntReal = v.getComplexIntReal();
1627 IntImag = v.getComplexIntImag();
1628 }
1629 }
1630 };
1631
1632 struct LValue {
1634 CharUnits Offset;
1635 SubobjectDesignator Designator;
1636 bool IsNullPtr : 1;
1637 bool InvalidBase : 1;
1638 // P2280R4 track if we have an unknown reference or pointer.
1639 bool AllowConstexprUnknown = false;
1640
1641 const APValue::LValueBase getLValueBase() const { return Base; }
1642 bool allowConstexprUnknown() const { return AllowConstexprUnknown; }
1643 CharUnits &getLValueOffset() { return Offset; }
1644 const CharUnits &getLValueOffset() const { return Offset; }
1645 SubobjectDesignator &getLValueDesignator() { return Designator; }
1646 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1647 bool isNullPointer() const { return IsNullPtr;}
1648
1649 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1650 unsigned getLValueVersion() const { return Base.getVersion(); }
1651
1652 void moveInto(APValue &V) const {
1653 if (Designator.Invalid)
1654 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1655 else {
1656 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1657 V = APValue(Base, Offset, Designator.Entries,
1658 Designator.IsOnePastTheEnd, IsNullPtr);
1659 }
1660 if (AllowConstexprUnknown)
1661 V.setConstexprUnknown();
1662 }
1663 void setFrom(ASTContext &Ctx, const APValue &V) {
1664 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1665 Base = V.getLValueBase();
1666 Offset = V.getLValueOffset();
1667 InvalidBase = false;
1668 Designator = SubobjectDesignator(Ctx, V);
1669 IsNullPtr = V.isNullPointer();
1670 AllowConstexprUnknown = V.allowConstexprUnknown();
1671 }
1672
1673 void set(APValue::LValueBase B, bool BInvalid = false) {
1674#ifndef NDEBUG
1675 // We only allow a few types of invalid bases. Enforce that here.
1676 if (BInvalid) {
1677 const auto *E = B.get<const Expr *>();
1678 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1679 "Unexpected type of invalid base");
1680 }
1681#endif
1682
1683 Base = B;
1684 Offset = CharUnits::fromQuantity(0);
1685 InvalidBase = BInvalid;
1686 Designator = SubobjectDesignator(getType(B));
1687 IsNullPtr = false;
1688 AllowConstexprUnknown = false;
1689 }
1690
1691 void setNull(ASTContext &Ctx, QualType PointerTy) {
1692 Base = (const ValueDecl *)nullptr;
1693 Offset =
1695 InvalidBase = false;
1696 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1697 IsNullPtr = true;
1698 AllowConstexprUnknown = false;
1699 }
1700
1701 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1702 set(B, true);
1703 }
1704
1705 std::string toString(ASTContext &Ctx, QualType T) const {
1706 APValue Printable;
1707 moveInto(Printable);
1708 return Printable.getAsString(Ctx, T);
1709 }
1710
1711 private:
1712 // Check that this LValue is not based on a null pointer. If it is, produce
1713 // a diagnostic and mark the designator as invalid.
1714 template <typename GenDiagType>
1715 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1716 if (Designator.Invalid)
1717 return false;
1718 if (IsNullPtr) {
1719 GenDiag();
1720 Designator.setInvalid();
1721 return false;
1722 }
1723 return true;
1724 }
1725
1726 public:
1727 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1728 CheckSubobjectKind CSK) {
1729 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1730 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1731 });
1732 }
1733
1734 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1735 AccessKinds AK) {
1736 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1737 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1738 });
1739 }
1740
1741 // Check this LValue refers to an object. If not, set the designator to be
1742 // invalid and emit a diagnostic.
1743 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1744 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1745 Designator.checkSubobject(Info, E, CSK);
1746 }
1747
1748 void addDecl(EvalInfo &Info, const Expr *E,
1749 const Decl *D, bool Virtual = false) {
1750 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1751 Designator.addDeclUnchecked(D, Virtual);
1752 }
1753 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1754 if (!Designator.Entries.empty()) {
1755 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1756 Designator.setInvalid();
1757 return;
1758 }
1759 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1760 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1761 Designator.FirstEntryIsAnUnsizedArray = true;
1762 Designator.addUnsizedArrayUnchecked(ElemTy);
1763 }
1764 }
1765 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1766 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1767 Designator.addArrayUnchecked(CAT);
1768 }
1769 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1770 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1771 Designator.addComplexUnchecked(EltTy, Imag);
1772 }
1773 void addVectorElement(EvalInfo &Info, const Expr *E, QualType EltTy,
1774 uint64_t Size, uint64_t Idx) {
1775 if (checkSubobject(Info, E, CSK_VectorElement))
1776 Designator.addVectorElementUnchecked(EltTy, Size, Idx);
1777 }
1778 void clearIsNullPointer() {
1779 IsNullPtr = false;
1780 }
1781 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1782 const APSInt &Index, CharUnits ElementSize) {
1783 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1784 // but we're not required to diagnose it and it's valid in C++.)
1785 if (!Index)
1786 return;
1787
1788 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1789 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1790 // offsets.
1791 uint64_t Offset64 = Offset.getQuantity();
1792 uint64_t ElemSize64 = ElementSize.getQuantity();
1793 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1794 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1795
1796 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1797 Designator.adjustIndex(Info, E, Index);
1798 clearIsNullPointer();
1799 }
1800 void adjustOffset(CharUnits N) {
1801 Offset += N;
1802 if (N.getQuantity())
1803 clearIsNullPointer();
1804 }
1805 };
1806
1807 struct MemberPtr {
1808 MemberPtr() {}
1809 explicit MemberPtr(const ValueDecl *Decl)
1810 : DeclAndIsDerivedMember(Decl, false) {}
1811
1812 /// The member or (direct or indirect) field referred to by this member
1813 /// pointer, or 0 if this is a null member pointer.
1814 const ValueDecl *getDecl() const {
1815 return DeclAndIsDerivedMember.getPointer();
1816 }
1817 /// Is this actually a member of some type derived from the relevant class?
1818 bool isDerivedMember() const {
1819 return DeclAndIsDerivedMember.getInt();
1820 }
1821 /// Get the class which the declaration actually lives in.
1822 const CXXRecordDecl *getContainingRecord() const {
1823 return cast<CXXRecordDecl>(
1824 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1825 }
1826
1827 void moveInto(APValue &V) const {
1828 V = APValue(getDecl(), isDerivedMember(), Path);
1829 }
1830 void setFrom(const APValue &V) {
1831 assert(V.isMemberPointer());
1832 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1833 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1834 Path.clear();
1835 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1836 Path.insert(Path.end(), P.begin(), P.end());
1837 }
1838
1839 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1840 /// whether the member is a member of some class derived from the class type
1841 /// of the member pointer.
1842 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1843 /// Path - The path of base/derived classes from the member declaration's
1844 /// class (exclusive) to the class type of the member pointer (inclusive).
1846
1847 /// Perform a cast towards the class of the Decl (either up or down the
1848 /// hierarchy).
1849 bool castBack(const CXXRecordDecl *Class) {
1850 assert(!Path.empty());
1851 const CXXRecordDecl *Expected;
1852 if (Path.size() >= 2)
1853 Expected = Path[Path.size() - 2];
1854 else
1855 Expected = getContainingRecord();
1856 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1857 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1858 // if B does not contain the original member and is not a base or
1859 // derived class of the class containing the original member, the result
1860 // of the cast is undefined.
1861 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1862 // (D::*). We consider that to be a language defect.
1863 return false;
1864 }
1865 Path.pop_back();
1866 return true;
1867 }
1868 /// Perform a base-to-derived member pointer cast.
1869 bool castToDerived(const CXXRecordDecl *Derived) {
1870 if (!getDecl())
1871 return true;
1872 if (!isDerivedMember()) {
1873 Path.push_back(Derived);
1874 return true;
1875 }
1876 if (!castBack(Derived))
1877 return false;
1878 if (Path.empty())
1879 DeclAndIsDerivedMember.setInt(false);
1880 return true;
1881 }
1882 /// Perform a derived-to-base member pointer cast.
1883 bool castToBase(const CXXRecordDecl *Base) {
1884 if (!getDecl())
1885 return true;
1886 if (Path.empty())
1887 DeclAndIsDerivedMember.setInt(true);
1888 if (isDerivedMember()) {
1889 Path.push_back(Base);
1890 return true;
1891 }
1892 return castBack(Base);
1893 }
1894 };
1895
1896 /// Compare two member pointers, which are assumed to be of the same type.
1897 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1898 if (!LHS.getDecl() || !RHS.getDecl())
1899 return !LHS.getDecl() && !RHS.getDecl();
1900 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1901 return false;
1902 return LHS.Path == RHS.Path;
1903 }
1904}
1905
1906static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1907static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1908 const LValue &This, const Expr *E,
1909 bool AllowNonLiteralTypes = false);
1910static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1911 bool InvalidBaseOK = false);
1912static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1913 bool InvalidBaseOK = false);
1914static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1915 EvalInfo &Info);
1916static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1917static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1918static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1919 EvalInfo &Info);
1920static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1921static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1922static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1923 EvalInfo &Info);
1924static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1925static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1926 EvalInfo &Info,
1927 std::string *StringResult = nullptr);
1928
1929/// Evaluate an integer or fixed point expression into an APResult.
1930static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1931 EvalInfo &Info);
1932
1933/// Evaluate only a fixed point expression into an APResult.
1934static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1935 EvalInfo &Info);
1936
1937//===----------------------------------------------------------------------===//
1938// Misc utilities
1939//===----------------------------------------------------------------------===//
1940
1941/// Negate an APSInt in place, converting it to a signed form if necessary, and
1942/// preserving its value (by extending by up to one bit as needed).
1943static void negateAsSigned(APSInt &Int) {
1944 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1945 Int = Int.extend(Int.getBitWidth() + 1);
1946 Int.setIsSigned(true);
1947 }
1948 Int = -Int;
1949}
1950
1951template<typename KeyT>
1952APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1953 ScopeKind Scope, LValue &LV) {
1954 unsigned Version = getTempVersion();
1955 APValue::LValueBase Base(Key, Index, Version);
1956 LV.set(Base);
1957 return createLocal(Base, Key, T, Scope);
1958}
1959
1960APValue &
1961CallStackFrame::createConstexprUnknownAPValues(const VarDecl *Key,
1963 APValue &Result = ConstexprUnknownAPValues[MapKeyTy(Key, Base.getVersion())];
1965
1966 return Result;
1967}
1968
1969/// Allocate storage for a parameter of a function call made in this frame.
1970APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1971 LValue &LV) {
1972 assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1973 APValue::LValueBase Base(PVD, Index, Args.Version);
1974 LV.set(Base);
1975 // We always destroy parameters at the end of the call, even if we'd allow
1976 // them to live to the end of the full-expression at runtime, in order to
1977 // give portable results and match other compilers.
1978 return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1979}
1980
1981APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1982 QualType T, ScopeKind Scope) {
1983 assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1984 unsigned Version = Base.getVersion();
1985 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1986 assert(Result.isAbsent() && "local created multiple times");
1987
1988 // If we're creating a local immediately in the operand of a speculative
1989 // evaluation, don't register a cleanup to be run outside the speculative
1990 // evaluation context, since we won't actually be able to initialize this
1991 // object.
1992 if (Index <= Info.SpeculativeEvaluationDepth) {
1993 if (T.isDestructedType())
1994 Info.noteSideEffect();
1995 } else {
1996 Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1997 }
1998 return Result;
1999}
2000
2001APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
2002 if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
2003 FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
2004 return nullptr;
2005 }
2006
2007 DynamicAllocLValue DA(NumHeapAllocs++);
2009 auto Result = HeapAllocs.emplace(std::piecewise_construct,
2010 std::forward_as_tuple(DA), std::tuple<>());
2011 assert(Result.second && "reused a heap alloc index?");
2012 Result.first->second.AllocExpr = E;
2013 return &Result.first->second.Value;
2014}
2015
2016/// Produce a string describing the given constexpr call.
2017void CallStackFrame::describe(raw_ostream &Out) const {
2018 unsigned ArgIndex = 0;
2019 bool IsMemberCall =
2020 isa<CXXMethodDecl>(Callee) && !isa<CXXConstructorDecl>(Callee) &&
2021 cast<CXXMethodDecl>(Callee)->isImplicitObjectMemberFunction();
2022
2023 if (!IsMemberCall)
2024 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2025 /*Qualified=*/false);
2026
2027 if (This && IsMemberCall) {
2028 if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {
2029 const Expr *Object = MCE->getImplicitObjectArgument();
2030 Object->printPretty(Out, /*Helper=*/nullptr, Info.Ctx.getPrintingPolicy(),
2031 /*Indentation=*/0);
2032 if (Object->getType()->isPointerType())
2033 Out << "->";
2034 else
2035 Out << ".";
2036 } else if (const auto *OCE =
2037 dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {
2038 OCE->getArg(0)->printPretty(Out, /*Helper=*/nullptr,
2039 Info.Ctx.getPrintingPolicy(),
2040 /*Indentation=*/0);
2041 Out << ".";
2042 } else {
2043 APValue Val;
2044 This->moveInto(Val);
2045 Val.printPretty(
2046 Out, Info.Ctx,
2047 Info.Ctx.getLValueReferenceType(This->Designator.MostDerivedType));
2048 Out << ".";
2049 }
2050 Callee->getNameForDiagnostic(Out, Info.Ctx.getPrintingPolicy(),
2051 /*Qualified=*/false);
2052 IsMemberCall = false;
2053 }
2054
2055 Out << '(';
2056
2057 for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
2058 E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
2059 if (ArgIndex > (unsigned)IsMemberCall)
2060 Out << ", ";
2061
2062 const ParmVarDecl *Param = *I;
2063 APValue *V = Info.getParamSlot(Arguments, Param);
2064 if (V)
2065 V->printPretty(Out, Info.Ctx, Param->getType());
2066 else
2067 Out << "<...>";
2068
2069 if (ArgIndex == 0 && IsMemberCall)
2070 Out << "->" << *Callee << '(';
2071 }
2072
2073 Out << ')';
2074}
2075
2076/// Evaluate an expression to see if it had side-effects, and discard its
2077/// result.
2078/// \return \c true if the caller should keep evaluating.
2079static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
2080 assert(!E->isValueDependent());
2081 APValue Scratch;
2082 if (!Evaluate(Scratch, Info, E))
2083 // We don't need the value, but we might have skipped a side effect here.
2084 return Info.noteSideEffect();
2085 return true;
2086}
2087
2088/// Should this call expression be treated as forming an opaque constant?
2089static bool IsOpaqueConstantCall(const CallExpr *E) {
2090 unsigned Builtin = E->getBuiltinCallee();
2091 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
2092 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
2093 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
2094 Builtin == Builtin::BI__builtin_function_start);
2095}
2096
2097static bool IsOpaqueConstantCall(const LValue &LVal) {
2098 const auto *BaseExpr =
2099 llvm::dyn_cast_if_present<CallExpr>(LVal.Base.dyn_cast<const Expr *>());
2100 return BaseExpr && IsOpaqueConstantCall(BaseExpr);
2101}
2102
2104 // C++11 [expr.const]p3 An address constant expression is a prvalue core
2105 // constant expression of pointer type that evaluates to...
2106
2107 // ... a null pointer value, or a prvalue core constant expression of type
2108 // std::nullptr_t.
2109 if (!B)
2110 return true;
2111
2112 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2113 // ... the address of an object with static storage duration,
2114 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
2115 return VD->hasGlobalStorage();
2116 if (isa<TemplateParamObjectDecl>(D))
2117 return true;
2118 // ... the address of a function,
2119 // ... the address of a GUID [MS extension],
2120 // ... the address of an unnamed global constant
2121 return isa<FunctionDecl, MSGuidDecl, UnnamedGlobalConstantDecl>(D);
2122 }
2123
2124 if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
2125 return true;
2126
2127 const Expr *E = B.get<const Expr*>();
2128 switch (E->getStmtClass()) {
2129 default:
2130 return false;
2131 case Expr::CompoundLiteralExprClass: {
2132 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
2133 return CLE->isFileScope() && CLE->isLValue();
2134 }
2135 case Expr::MaterializeTemporaryExprClass:
2136 // A materialized temporary might have been lifetime-extended to static
2137 // storage duration.
2138 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2139 // A string literal has static storage duration.
2140 case Expr::StringLiteralClass:
2141 case Expr::PredefinedExprClass:
2142 case Expr::ObjCStringLiteralClass:
2143 case Expr::ObjCEncodeExprClass:
2144 return true;
2145 case Expr::ObjCBoxedExprClass:
2146 return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2147 case Expr::CallExprClass:
2148 return IsOpaqueConstantCall(cast<CallExpr>(E));
2149 // For GCC compatibility, &&label has static storage duration.
2150 case Expr::AddrLabelExprClass:
2151 return true;
2152 // A Block literal expression may be used as the initialization value for
2153 // Block variables at global or local static scope.
2154 case Expr::BlockExprClass:
2155 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2156 // The APValue generated from a __builtin_source_location will be emitted as a
2157 // literal.
2158 case Expr::SourceLocExprClass:
2159 return true;
2160 case Expr::ImplicitValueInitExprClass:
2161 // FIXME:
2162 // We can never form an lvalue with an implicit value initialization as its
2163 // base through expression evaluation, so these only appear in one case: the
2164 // implicit variable declaration we invent when checking whether a constexpr
2165 // constructor can produce a constant expression. We must assume that such
2166 // an expression might be a global lvalue.
2167 return true;
2168 }
2169}
2170
2171static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2172 return LVal.Base.dyn_cast<const ValueDecl*>();
2173}
2174
2175// Information about an LValueBase that is some kind of string.
2178 StringRef Bytes;
2180};
2181
2182// Gets the lvalue base of LVal as a string.
2183static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal,
2184 LValueBaseString &AsString) {
2185 const auto *BaseExpr = LVal.Base.dyn_cast<const Expr *>();
2186 if (!BaseExpr)
2187 return false;
2188
2189 // For ObjCEncodeExpr, we need to compute and store the string.
2190 if (const auto *EE = dyn_cast<ObjCEncodeExpr>(BaseExpr)) {
2191 Info.Ctx.getObjCEncodingForType(EE->getEncodedType(),
2192 AsString.ObjCEncodeStorage);
2193 AsString.Bytes = AsString.ObjCEncodeStorage;
2194 AsString.CharWidth = 1;
2195 return true;
2196 }
2197
2198 // Otherwise, we have a StringLiteral.
2199 const auto *Lit = dyn_cast<StringLiteral>(BaseExpr);
2200 if (const auto *PE = dyn_cast<PredefinedExpr>(BaseExpr))
2201 Lit = PE->getFunctionName();
2202
2203 if (!Lit)
2204 return false;
2205
2206 AsString.Bytes = Lit->getBytes();
2207 AsString.CharWidth = Lit->getCharByteWidth();
2208 return true;
2209}
2210
2211// Determine whether two string literals potentially overlap. This will be the
2212// case if they agree on the values of all the bytes on the overlapping region
2213// between them.
2214//
2215// The overlapping region is the portion of the two string literals that must
2216// overlap in memory if the pointers actually point to the same address at
2217// runtime. For example, if LHS is "abcdef" + 3 and RHS is "cdef\0gh" + 1 then
2218// the overlapping region is "cdef\0", which in this case does agree, so the
2219// strings are potentially overlapping. Conversely, for "foobar" + 3 versus
2220// "bazbar" + 3, the overlapping region contains all of both strings, so they
2221// are not potentially overlapping, even though they agree from the given
2222// addresses onwards.
2223//
2224// See open core issue CWG2765 which is discussing the desired rule here.
2225static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info,
2226 const LValue &LHS,
2227 const LValue &RHS) {
2228 LValueBaseString LHSString, RHSString;
2229 if (!GetLValueBaseAsString(Info, LHS, LHSString) ||
2230 !GetLValueBaseAsString(Info, RHS, RHSString))
2231 return false;
2232
2233 // This is the byte offset to the location of the first character of LHS
2234 // within RHS. We don't need to look at the characters of one string that
2235 // would appear before the start of the other string if they were merged.
2236 CharUnits Offset = RHS.Offset - LHS.Offset;
2237 if (Offset.isNegative())
2238 LHSString.Bytes = LHSString.Bytes.drop_front(-Offset.getQuantity());
2239 else
2240 RHSString.Bytes = RHSString.Bytes.drop_front(Offset.getQuantity());
2241
2242 bool LHSIsLonger = LHSString.Bytes.size() > RHSString.Bytes.size();
2243 StringRef Longer = LHSIsLonger ? LHSString.Bytes : RHSString.Bytes;
2244 StringRef Shorter = LHSIsLonger ? RHSString.Bytes : LHSString.Bytes;
2245 int ShorterCharWidth = (LHSIsLonger ? RHSString : LHSString).CharWidth;
2246
2247 // The null terminator isn't included in the string data, so check for it
2248 // manually. If the longer string doesn't have a null terminator where the
2249 // shorter string ends, they aren't potentially overlapping.
2250 for (int NullByte : llvm::seq(ShorterCharWidth)) {
2251 if (Shorter.size() + NullByte >= Longer.size())
2252 break;
2253 if (Longer[Shorter.size() + NullByte])
2254 return false;
2255 }
2256
2257 // Otherwise, they're potentially overlapping if and only if the overlapping
2258 // region is the same.
2259 return Shorter == Longer.take_front(Shorter.size());
2260}
2261
2262static bool IsWeakLValue(const LValue &Value) {
2264 return Decl && Decl->isWeak();
2265}
2266
2267static bool isZeroSized(const LValue &Value) {
2269 if (isa_and_nonnull<VarDecl>(Decl)) {
2270 QualType Ty = Decl->getType();
2271 if (Ty->isArrayType())
2272 return Ty->isIncompleteType() ||
2273 Decl->getASTContext().getTypeSize(Ty) == 0;
2274 }
2275 return false;
2276}
2277
2278static bool HasSameBase(const LValue &A, const LValue &B) {
2279 if (!A.getLValueBase())
2280 return !B.getLValueBase();
2281 if (!B.getLValueBase())
2282 return false;
2283
2284 if (A.getLValueBase().getOpaqueValue() !=
2285 B.getLValueBase().getOpaqueValue())
2286 return false;
2287
2288 return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2289 A.getLValueVersion() == B.getLValueVersion();
2290}
2291
2292static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2293 assert(Base && "no location for a null lvalue");
2294 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2295
2296 // For a parameter, find the corresponding call stack frame (if it still
2297 // exists), and point at the parameter of the function definition we actually
2298 // invoked.
2299 if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2300 unsigned Idx = PVD->getFunctionScopeIndex();
2301 for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2302 if (F->Arguments.CallIndex == Base.getCallIndex() &&
2303 F->Arguments.Version == Base.getVersion() && F->Callee &&
2304 Idx < F->Callee->getNumParams()) {
2305 VD = F->Callee->getParamDecl(Idx);
2306 break;
2307 }
2308 }
2309 }
2310
2311 if (VD)
2312 Info.Note(VD->getLocation(), diag::note_declared_at);
2313 else if (const Expr *E = Base.dyn_cast<const Expr*>())
2314 Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2315 else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2316 // FIXME: Produce a note for dangling pointers too.
2317 if (std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA))
2318 Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2319 diag::note_constexpr_dynamic_alloc_here);
2320 }
2321
2322 // We have no information to show for a typeid(T) object.
2323}
2324
2328};
2329
2330/// Materialized temporaries that we've already checked to determine if they're
2331/// initializsed by a constant expression.
2334
2336 EvalInfo &Info, SourceLocation DiagLoc,
2337 QualType Type, const APValue &Value,
2338 ConstantExprKind Kind,
2339 const FieldDecl *SubobjectDecl,
2340 CheckedTemporaries &CheckedTemps);
2341
2342/// Check that this reference or pointer core constant expression is a valid
2343/// value for an address or reference constant expression. Return true if we
2344/// can fold this expression, whether or not it's a constant expression.
2346 QualType Type, const LValue &LVal,
2347 ConstantExprKind Kind,
2348 CheckedTemporaries &CheckedTemps) {
2349 bool IsReferenceType = Type->isReferenceType();
2350
2351 APValue::LValueBase Base = LVal.getLValueBase();
2352 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2353
2354 const Expr *BaseE = Base.dyn_cast<const Expr *>();
2355 const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2356
2357 // Additional restrictions apply in a template argument. We only enforce the
2358 // C++20 restrictions here; additional syntactic and semantic restrictions
2359 // are applied elsewhere.
2360 if (isTemplateArgument(Kind)) {
2361 int InvalidBaseKind = -1;
2362 StringRef Ident;
2363 if (Base.is<TypeInfoLValue>())
2364 InvalidBaseKind = 0;
2365 else if (isa_and_nonnull<StringLiteral>(BaseE))
2366 InvalidBaseKind = 1;
2367 else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2368 isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2369 InvalidBaseKind = 2;
2370 else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2371 InvalidBaseKind = 3;
2372 Ident = PE->getIdentKindName();
2373 }
2374
2375 if (InvalidBaseKind != -1) {
2376 Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2377 << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2378 << Ident;
2379 return false;
2380 }
2381 }
2382
2383 if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD);
2384 FD && FD->isImmediateFunction()) {
2385 Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2386 << !Type->isAnyPointerType();
2387 Info.Note(FD->getLocation(), diag::note_declared_at);
2388 return false;
2389 }
2390
2391 // Check that the object is a global. Note that the fake 'this' object we
2392 // manufacture when checking potential constant expressions is conservatively
2393 // assumed to be global here.
2394 if (!IsGlobalLValue(Base)) {
2395 if (Info.getLangOpts().CPlusPlus11) {
2396 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2397 << IsReferenceType << !Designator.Entries.empty() << !!BaseVD
2398 << BaseVD;
2399 auto *VarD = dyn_cast_or_null<VarDecl>(BaseVD);
2400 if (VarD && VarD->isConstexpr()) {
2401 // Non-static local constexpr variables have unintuitive semantics:
2402 // constexpr int a = 1;
2403 // constexpr const int *p = &a;
2404 // ... is invalid because the address of 'a' is not constant. Suggest
2405 // adding a 'static' in this case.
2406 Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2407 << VarD
2408 << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2409 } else {
2410 NoteLValueLocation(Info, Base);
2411 }
2412 } else {
2413 Info.FFDiag(Loc);
2414 }
2415 // Don't allow references to temporaries to escape.
2416 return false;
2417 }
2418 assert((Info.checkingPotentialConstantExpression() ||
2419 LVal.getLValueCallIndex() == 0) &&
2420 "have call index for global lvalue");
2421
2422 if (Base.is<DynamicAllocLValue>()) {
2423 Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2424 << IsReferenceType << !Designator.Entries.empty();
2425 NoteLValueLocation(Info, Base);
2426 return false;
2427 }
2428
2429 if (BaseVD) {
2430 if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2431 // Check if this is a thread-local variable.
2432 if (Var->getTLSKind())
2433 // FIXME: Diagnostic!
2434 return false;
2435
2436 // A dllimport variable never acts like a constant, unless we're
2437 // evaluating a value for use only in name mangling.
2438 if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2439 // FIXME: Diagnostic!
2440 return false;
2441
2442 // In CUDA/HIP device compilation, only device side variables have
2443 // constant addresses.
2444 if (Info.getASTContext().getLangOpts().CUDA &&
2445 Info.getASTContext().getLangOpts().CUDAIsDevice &&
2446 Info.getASTContext().CUDAConstantEvalCtx.NoWrongSidedVars) {
2447 if ((!Var->hasAttr<CUDADeviceAttr>() &&
2448 !Var->hasAttr<CUDAConstantAttr>() &&
2449 !Var->getType()->isCUDADeviceBuiltinSurfaceType() &&
2450 !Var->getType()->isCUDADeviceBuiltinTextureType()) ||
2451 Var->hasAttr<HIPManagedAttr>())
2452 return false;
2453 }
2454 }
2455 if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2456 // __declspec(dllimport) must be handled very carefully:
2457 // We must never initialize an expression with the thunk in C++.
2458 // Doing otherwise would allow the same id-expression to yield
2459 // different addresses for the same function in different translation
2460 // units. However, this means that we must dynamically initialize the
2461 // expression with the contents of the import address table at runtime.
2462 //
2463 // The C language has no notion of ODR; furthermore, it has no notion of
2464 // dynamic initialization. This means that we are permitted to
2465 // perform initialization with the address of the thunk.
2466 if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2467 FD->hasAttr<DLLImportAttr>())
2468 // FIXME: Diagnostic!
2469 return false;
2470 }
2471 } else if (const auto *MTE =
2472 dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2473 if (CheckedTemps.insert(MTE).second) {
2474 QualType TempType = getType(Base);
2475 if (TempType.isDestructedType()) {
2476 Info.FFDiag(MTE->getExprLoc(),
2477 diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2478 << TempType;
2479 return false;
2480 }
2481
2482 APValue *V = MTE->getOrCreateValue(false);
2483 assert(V && "evasluation result refers to uninitialised temporary");
2484 if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2485 Info, MTE->getExprLoc(), TempType, *V, Kind,
2486 /*SubobjectDecl=*/nullptr, CheckedTemps))
2487 return false;
2488 }
2489 }
2490
2491 // Allow address constant expressions to be past-the-end pointers. This is
2492 // an extension: the standard requires them to point to an object.
2493 if (!IsReferenceType)
2494 return true;
2495
2496 // A reference constant expression must refer to an object.
2497 if (!Base) {
2498 // FIXME: diagnostic
2499 Info.CCEDiag(Loc);
2500 return true;
2501 }
2502
2503 // Does this refer one past the end of some object?
2504 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2505 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2506 << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2507 NoteLValueLocation(Info, Base);
2508 }
2509
2510 return true;
2511}
2512
2513/// Member pointers are constant expressions unless they point to a
2514/// non-virtual dllimport member function.
2515static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2517 QualType Type,
2518 const APValue &Value,
2519 ConstantExprKind Kind) {
2520 const ValueDecl *Member = Value.getMemberPointerDecl();
2521 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2522 if (!FD)
2523 return true;
2524 if (FD->isImmediateFunction()) {
2525 Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2526 Info.Note(FD->getLocation(), diag::note_declared_at);
2527 return false;
2528 }
2529 return isForManglingOnly(Kind) || FD->isVirtual() ||
2530 !FD->hasAttr<DLLImportAttr>();
2531}
2532
2533/// Check that this core constant expression is of literal type, and if not,
2534/// produce an appropriate diagnostic.
2535static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2536 const LValue *This = nullptr) {
2537 // The restriction to literal types does not exist in C++23 anymore.
2538 if (Info.getLangOpts().CPlusPlus23)
2539 return true;
2540
2541 if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2542 return true;
2543
2544 // C++1y: A constant initializer for an object o [...] may also invoke
2545 // constexpr constructors for o and its subobjects even if those objects
2546 // are of non-literal class types.
2547 //
2548 // C++11 missed this detail for aggregates, so classes like this:
2549 // struct foo_t { union { int i; volatile int j; } u; };
2550 // are not (obviously) initializable like so:
2551 // __attribute__((__require_constant_initialization__))
2552 // static const foo_t x = {{0}};
2553 // because "i" is a subobject with non-literal initialization (due to the
2554 // volatile member of the union). See:
2555 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2556 // Therefore, we use the C++1y behavior.
2557 if (This && Info.EvaluatingDecl == This->getLValueBase())
2558 return true;
2559
2560 // Prvalue constant expressions must be of literal types.
2561 if (Info.getLangOpts().CPlusPlus11)
2562 Info.FFDiag(E, diag::note_constexpr_nonliteral)
2563 << E->getType();
2564 else
2565 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2566 return false;
2567}
2568
2570 EvalInfo &Info, SourceLocation DiagLoc,
2571 QualType Type, const APValue &Value,
2572 ConstantExprKind Kind,
2573 const FieldDecl *SubobjectDecl,
2574 CheckedTemporaries &CheckedTemps) {
2575 if (!Value.hasValue()) {
2576 if (SubobjectDecl) {
2577 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2578 << /*(name)*/ 1 << SubobjectDecl;
2579 Info.Note(SubobjectDecl->getLocation(),
2580 diag::note_constexpr_subobject_declared_here);
2581 } else {
2582 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2583 << /*of type*/ 0 << Type;
2584 }
2585 return false;
2586 }
2587
2588 // We allow _Atomic(T) to be initialized from anything that T can be
2589 // initialized from.
2590 if (const AtomicType *AT = Type->getAs<AtomicType>())
2591 Type = AT->getValueType();
2592
2593 // Core issue 1454: For a literal constant expression of array or class type,
2594 // each subobject of its value shall have been initialized by a constant
2595 // expression.
2596 if (Value.isArray()) {
2598 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2599 if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2600 Value.getArrayInitializedElt(I), Kind,
2601 SubobjectDecl, CheckedTemps))
2602 return false;
2603 }
2604 if (!Value.hasArrayFiller())
2605 return true;
2606 return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2607 Value.getArrayFiller(), Kind, SubobjectDecl,
2608 CheckedTemps);
2609 }
2610 if (Value.isUnion() && Value.getUnionField()) {
2611 return CheckEvaluationResult(
2612 CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2613 Value.getUnionValue(), Kind, Value.getUnionField(), CheckedTemps);
2614 }
2615 if (Value.isStruct()) {
2616 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2617 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2618 unsigned BaseIndex = 0;
2619 for (const CXXBaseSpecifier &BS : CD->bases()) {
2620 const APValue &BaseValue = Value.getStructBase(BaseIndex);
2621 if (!BaseValue.hasValue()) {
2622 SourceLocation TypeBeginLoc = BS.getBaseTypeLoc();
2623 Info.FFDiag(TypeBeginLoc, diag::note_constexpr_uninitialized_base)
2624 << BS.getType() << SourceRange(TypeBeginLoc, BS.getEndLoc());
2625 return false;
2626 }
2627 if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(), BaseValue,
2628 Kind, /*SubobjectDecl=*/nullptr,
2629 CheckedTemps))
2630 return false;
2631 ++BaseIndex;
2632 }
2633 }
2634 for (const auto *I : RD->fields()) {
2635 if (I->isUnnamedBitField())
2636 continue;
2637
2638 if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2639 Value.getStructField(I->getFieldIndex()), Kind,
2640 I, CheckedTemps))
2641 return false;
2642 }
2643 }
2644
2645 if (Value.isLValue() &&
2646 CERK == CheckEvaluationResultKind::ConstantExpression) {
2647 LValue LVal;
2648 LVal.setFrom(Info.Ctx, Value);
2649 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2650 CheckedTemps);
2651 }
2652
2653 if (Value.isMemberPointer() &&
2654 CERK == CheckEvaluationResultKind::ConstantExpression)
2655 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2656
2657 // Everything else is fine.
2658 return true;
2659}
2660
2661/// Check that this core constant expression value is a valid value for a
2662/// constant expression. If not, report an appropriate diagnostic. Does not
2663/// check that the expression is of literal type.
2664static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2665 QualType Type, const APValue &Value,
2666 ConstantExprKind Kind) {
2667 // Nothing to check for a constant expression of type 'cv void'.
2668 if (Type->isVoidType())
2669 return true;
2670
2671 CheckedTemporaries CheckedTemps;
2672 return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2673 Info, DiagLoc, Type, Value, Kind,
2674 /*SubobjectDecl=*/nullptr, CheckedTemps);
2675}
2676
2677/// Check that this evaluated value is fully-initialized and can be loaded by
2678/// an lvalue-to-rvalue conversion.
2679static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2680 QualType Type, const APValue &Value) {
2681 CheckedTemporaries CheckedTemps;
2682 return CheckEvaluationResult(
2683 CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2684 ConstantExprKind::Normal, /*SubobjectDecl=*/nullptr, CheckedTemps);
2685}
2686
2687/// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2688/// "the allocated storage is deallocated within the evaluation".
2689static bool CheckMemoryLeaks(EvalInfo &Info) {
2690 if (!Info.HeapAllocs.empty()) {
2691 // We can still fold to a constant despite a compile-time memory leak,
2692 // so long as the heap allocation isn't referenced in the result (we check
2693 // that in CheckConstantExpression).
2694 Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2695 diag::note_constexpr_memory_leak)
2696 << unsigned(Info.HeapAllocs.size() - 1);
2697 }
2698 return true;
2699}
2700
2701static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2702 // A null base expression indicates a null pointer. These are always
2703 // evaluatable, and they are false unless the offset is zero.
2704 if (!Value.getLValueBase()) {
2705 // TODO: Should a non-null pointer with an offset of zero evaluate to true?
2706 Result = !Value.getLValueOffset().isZero();
2707 return true;
2708 }
2709
2710 // We have a non-null base. These are generally known to be true, but if it's
2711 // a weak declaration it can be null at runtime.
2712 Result = true;
2713 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2714 return !Decl || !Decl->isWeak();
2715}
2716
2717static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2718 // TODO: This function should produce notes if it fails.
2719 switch (Val.getKind()) {
2720 case APValue::None:
2722 return false;
2723 case APValue::Int:
2724 Result = Val.getInt().getBoolValue();
2725 return true;
2727 Result = Val.getFixedPoint().getBoolValue();
2728 return true;
2729 case APValue::Float:
2730 Result = !Val.getFloat().isZero();
2731 return true;
2733 Result = Val.getComplexIntReal().getBoolValue() ||
2734 Val.getComplexIntImag().getBoolValue();
2735 return true;
2737 Result = !Val.getComplexFloatReal().isZero() ||
2738 !Val.getComplexFloatImag().isZero();
2739 return true;
2740 case APValue::LValue:
2741 return EvalPointerValueAsBool(Val, Result);
2743 if (Val.getMemberPointerDecl() && Val.getMemberPointerDecl()->isWeak()) {
2744 return false;
2745 }
2746 Result = Val.getMemberPointerDecl();
2747 return true;
2748 case APValue::Vector:
2749 case APValue::Array:
2750 case APValue::Struct:
2751 case APValue::Union:
2753 return false;
2754 }
2755
2756 llvm_unreachable("unknown APValue kind");
2757}
2758
2759static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2760 EvalInfo &Info) {
2761 assert(!E->isValueDependent());
2762 assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2763 APValue Val;
2764 if (!Evaluate(Val, Info, E))
2765 return false;
2766 return HandleConversionToBool(Val, Result);
2767}
2768
2769template<typename T>
2770static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2771 const T &SrcValue, QualType DestType) {
2772 Info.CCEDiag(E, diag::note_constexpr_overflow)
2773 << SrcValue << DestType;
2774 return Info.noteUndefinedBehavior();
2775}
2776
2777static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2778 QualType SrcType, const APFloat &Value,
2779 QualType DestType, APSInt &Result) {
2780 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2781 // Determine whether we are converting to unsigned or signed.
2782 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2783
2784 Result = APSInt(DestWidth, !DestSigned);
2785 bool ignored;
2786 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2787 & APFloat::opInvalidOp)
2788 return HandleOverflow(Info, E, Value, DestType);
2789 return true;
2790}
2791
2792/// Get rounding mode to use in evaluation of the specified expression.
2793///
2794/// If rounding mode is unknown at compile time, still try to evaluate the
2795/// expression. If the result is exact, it does not depend on rounding mode.
2796/// So return "tonearest" mode instead of "dynamic".
2797static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E) {
2798 llvm::RoundingMode RM =
2799 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2800 if (RM == llvm::RoundingMode::Dynamic)
2801 RM = llvm::RoundingMode::NearestTiesToEven;
2802 return RM;
2803}
2804
2805/// Check if the given evaluation result is allowed for constant evaluation.
2806static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2807 APFloat::opStatus St) {
2808 // In a constant context, assume that any dynamic rounding mode or FP
2809 // exception state matches the default floating-point environment.
2810 if (Info.InConstantContext)
2811 return true;
2812
2813 FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2814 if ((St & APFloat::opInexact) &&
2815 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2816 // Inexact result means that it depends on rounding mode. If the requested
2817 // mode is dynamic, the evaluation cannot be made in compile time.
2818 Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2819 return false;
2820 }
2821
2822 if ((St != APFloat::opOK) &&
2823 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2824 FPO.getExceptionMode() != LangOptions::FPE_Ignore ||
2825 FPO.getAllowFEnvAccess())) {
2826 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2827 return false;
2828 }
2829
2830 if ((St & APFloat::opStatus::opInvalidOp) &&
2831 FPO.getExceptionMode() != LangOptions::FPE_Ignore) {
2832 // There is no usefully definable result.
2833 Info.FFDiag(E);
2834 return false;
2835 }
2836
2837 // FIXME: if:
2838 // - evaluation triggered other FP exception, and
2839 // - exception mode is not "ignore", and
2840 // - the expression being evaluated is not a part of global variable
2841 // initializer,
2842 // the evaluation probably need to be rejected.
2843 return true;
2844}
2845
2846static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2847 QualType SrcType, QualType DestType,
2848 APFloat &Result) {
2849 assert((isa<CastExpr>(E) || isa<CompoundAssignOperator>(E) ||
2850 isa<ConvertVectorExpr>(E)) &&
2851 "HandleFloatToFloatCast has been checked with only CastExpr, "
2852 "CompoundAssignOperator and ConvertVectorExpr. Please either validate "
2853 "the new expression or address the root cause of this usage.");
2854 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2855 APFloat::opStatus St;
2856 APFloat Value = Result;
2857 bool ignored;
2858 St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2859 return checkFloatingPointResult(Info, E, St);
2860}
2861
2862static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2863 QualType DestType, QualType SrcType,
2864 const APSInt &Value) {
2865 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2866 // Figure out if this is a truncate, extend or noop cast.
2867 // If the input is signed, do a sign extend, noop, or truncate.
2868 APSInt Result = Value.extOrTrunc(DestWidth);
2869 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2870 if (DestType->isBooleanType())
2871 Result = Value.getBoolValue();
2872 return Result;
2873}
2874
2875static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2876 const FPOptions FPO,
2877 QualType SrcType, const APSInt &Value,
2878 QualType DestType, APFloat &Result) {
2879 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2880 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
2881 APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(), RM);
2882 return checkFloatingPointResult(Info, E, St);
2883}
2884
2885static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2886 APValue &Value, const FieldDecl *FD) {
2887 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2888
2889 if (!Value.isInt()) {
2890 // Trying to store a pointer-cast-to-integer into a bitfield.
2891 // FIXME: In this case, we should provide the diagnostic for casting
2892 // a pointer to an integer.
2893 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2894 Info.FFDiag(E);
2895 return false;
2896 }
2897
2898 APSInt &Int = Value.getInt();
2899 unsigned OldBitWidth = Int.getBitWidth();
2900 unsigned NewBitWidth = FD->getBitWidthValue();
2901 if (NewBitWidth < OldBitWidth)
2902 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2903 return true;
2904}
2905
2906/// Perform the given integer operation, which is known to need at most BitWidth
2907/// bits, and check for overflow in the original type (if that type was not an
2908/// unsigned type).
2909template<typename Operation>
2910static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2911 const APSInt &LHS, const APSInt &RHS,
2912 unsigned BitWidth, Operation Op,
2913 APSInt &Result) {
2914 if (LHS.isUnsigned()) {
2915 Result = Op(LHS, RHS);
2916 return true;
2917 }
2918
2919 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2920 Result = Value.trunc(LHS.getBitWidth());
2921 if (Result.extend(BitWidth) != Value) {
2922 if (Info.checkingForUndefinedBehavior())
2923 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2924 diag::warn_integer_constant_overflow)
2925 << toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
2926 /*UpperCase=*/true, /*InsertSeparators=*/true)
2927 << E->getType() << E->getSourceRange();
2928 return HandleOverflow(Info, E, Value, E->getType());
2929 }
2930 return true;
2931}
2932
2933/// Perform the given binary integer operation.
2934static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E,
2935 const APSInt &LHS, BinaryOperatorKind Opcode,
2936 APSInt RHS, APSInt &Result) {
2937 bool HandleOverflowResult = true;
2938 switch (Opcode) {
2939 default:
2940 Info.FFDiag(E);
2941 return false;
2942 case BO_Mul:
2943 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2944 std::multiplies<APSInt>(), Result);
2945 case BO_Add:
2946 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2947 std::plus<APSInt>(), Result);
2948 case BO_Sub:
2949 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2950 std::minus<APSInt>(), Result);
2951 case BO_And: Result = LHS & RHS; return true;
2952 case BO_Xor: Result = LHS ^ RHS; return true;
2953 case BO_Or: Result = LHS | RHS; return true;
2954 case BO_Div:
2955 case BO_Rem:
2956 if (RHS == 0) {
2957 Info.FFDiag(E, diag::note_expr_divide_by_zero)
2958 << E->getRHS()->getSourceRange();
2959 return false;
2960 }
2961 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2962 // this operation and gives the two's complement result.
2963 if (RHS.isNegative() && RHS.isAllOnes() && LHS.isSigned() &&
2964 LHS.isMinSignedValue())
2965 HandleOverflowResult = HandleOverflow(
2966 Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
2967 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2968 return HandleOverflowResult;
2969 case BO_Shl: {
2970 if (Info.getLangOpts().OpenCL)
2971 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2972 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2973 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2974 RHS.isUnsigned());
2975 else if (RHS.isSigned() && RHS.isNegative()) {
2976 // During constant-folding, a negative shift is an opposite shift. Such
2977 // a shift is not a constant expression.
2978 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2979 if (!Info.noteUndefinedBehavior())
2980 return false;
2981 RHS = -RHS;
2982 goto shift_right;
2983 }
2984 shift_left:
2985 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2986 // the shifted type.
2987 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2988 if (SA != RHS) {
2989 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2990 << RHS << E->getType() << LHS.getBitWidth();
2991 if (!Info.noteUndefinedBehavior())
2992 return false;
2993 } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2994 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2995 // operand, and must not overflow the corresponding unsigned type.
2996 // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2997 // E1 x 2^E2 module 2^N.
2998 if (LHS.isNegative()) {
2999 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
3000 if (!Info.noteUndefinedBehavior())
3001 return false;
3002 } else if (LHS.countl_zero() < SA) {
3003 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
3004 if (!Info.noteUndefinedBehavior())
3005 return false;
3006 }
3007 }
3008 Result = LHS << SA;
3009 return true;
3010 }
3011 case BO_Shr: {
3012 if (Info.getLangOpts().OpenCL)
3013 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3014 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
3015 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
3016 RHS.isUnsigned());
3017 else if (RHS.isSigned() && RHS.isNegative()) {
3018 // During constant-folding, a negative shift is an opposite shift. Such a
3019 // shift is not a constant expression.
3020 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
3021 if (!Info.noteUndefinedBehavior())
3022 return false;
3023 RHS = -RHS;
3024 goto shift_left;
3025 }
3026 shift_right:
3027 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
3028 // shifted type.
3029 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3030 if (SA != RHS) {
3031 Info.CCEDiag(E, diag::note_constexpr_large_shift)
3032 << RHS << E->getType() << LHS.getBitWidth();
3033 if (!Info.noteUndefinedBehavior())
3034 return false;
3035 }
3036
3037 Result = LHS >> SA;
3038 return true;
3039 }
3040
3041 case BO_LT: Result = LHS < RHS; return true;
3042 case BO_GT: Result = LHS > RHS; return true;
3043 case BO_LE: Result = LHS <= RHS; return true;
3044 case BO_GE: Result = LHS >= RHS; return true;
3045 case BO_EQ: Result = LHS == RHS; return true;
3046 case BO_NE: Result = LHS != RHS; return true;
3047 case BO_Cmp:
3048 llvm_unreachable("BO_Cmp should be handled elsewhere");
3049 }
3050}
3051
3052/// Perform the given binary floating-point operation, in-place, on LHS.
3053static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
3054 APFloat &LHS, BinaryOperatorKind Opcode,
3055 const APFloat &RHS) {
3056 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
3057 APFloat::opStatus St;
3058 switch (Opcode) {
3059 default:
3060 Info.FFDiag(E);
3061 return false;
3062 case BO_Mul:
3063 St = LHS.multiply(RHS, RM);
3064 break;
3065 case BO_Add:
3066 St = LHS.add(RHS, RM);
3067 break;
3068 case BO_Sub:
3069 St = LHS.subtract(RHS, RM);
3070 break;
3071 case BO_Div:
3072 // [expr.mul]p4:
3073 // If the second operand of / or % is zero the behavior is undefined.
3074 if (RHS.isZero())
3075 Info.CCEDiag(E, diag::note_expr_divide_by_zero);
3076 St = LHS.divide(RHS, RM);
3077 break;
3078 }
3079
3080 // [expr.pre]p4:
3081 // If during the evaluation of an expression, the result is not
3082 // mathematically defined [...], the behavior is undefined.
3083 // FIXME: C++ rules require us to not conform to IEEE 754 here.
3084 if (LHS.isNaN()) {
3085 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
3086 return Info.noteUndefinedBehavior();
3087 }
3088
3089 return checkFloatingPointResult(Info, E, St);
3090}
3091
3092static bool handleLogicalOpForVector(const APInt &LHSValue,
3093 BinaryOperatorKind Opcode,
3094 const APInt &RHSValue, APInt &Result) {
3095 bool LHS = (LHSValue != 0);
3096 bool RHS = (RHSValue != 0);
3097
3098 if (Opcode == BO_LAnd)
3099 Result = LHS && RHS;
3100 else
3101 Result = LHS || RHS;
3102 return true;
3103}
3104static bool handleLogicalOpForVector(const APFloat &LHSValue,
3105 BinaryOperatorKind Opcode,
3106 const APFloat &RHSValue, APInt &Result) {
3107 bool LHS = !LHSValue.isZero();
3108 bool RHS = !RHSValue.isZero();
3109
3110 if (Opcode == BO_LAnd)
3111 Result = LHS && RHS;
3112 else
3113 Result = LHS || RHS;
3114 return true;
3115}
3116
3117static bool handleLogicalOpForVector(const APValue &LHSValue,
3118 BinaryOperatorKind Opcode,
3119 const APValue &RHSValue, APInt &Result) {
3120 // The result is always an int type, however operands match the first.
3121 if (LHSValue.getKind() == APValue::Int)
3122 return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
3123 RHSValue.getInt(), Result);
3124 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3125 return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
3126 RHSValue.getFloat(), Result);
3127}
3128
3129template <typename APTy>
3130static bool
3132 const APTy &RHSValue, APInt &Result) {
3133 switch (Opcode) {
3134 default:
3135 llvm_unreachable("unsupported binary operator");
3136 case BO_EQ:
3137 Result = (LHSValue == RHSValue);
3138 break;
3139 case BO_NE:
3140 Result = (LHSValue != RHSValue);
3141 break;
3142 case BO_LT:
3143 Result = (LHSValue < RHSValue);
3144 break;
3145 case BO_GT:
3146 Result = (LHSValue > RHSValue);
3147 break;
3148 case BO_LE:
3149 Result = (LHSValue <= RHSValue);
3150 break;
3151 case BO_GE:
3152 Result = (LHSValue >= RHSValue);
3153 break;
3154 }
3155
3156 // The boolean operations on these vector types use an instruction that
3157 // results in a mask of '-1' for the 'truth' value. Ensure that we negate 1
3158 // to -1 to make sure that we produce the correct value.
3159 Result.negate();
3160
3161 return true;
3162}
3163
3164static bool handleCompareOpForVector(const APValue &LHSValue,
3165 BinaryOperatorKind Opcode,
3166 const APValue &RHSValue, APInt &Result) {
3167 // The result is always an int type, however operands match the first.
3168 if (LHSValue.getKind() == APValue::Int)
3169 return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
3170 RHSValue.getInt(), Result);
3171 assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
3172 return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
3173 RHSValue.getFloat(), Result);
3174}
3175
3176// Perform binary operations for vector types, in place on the LHS.
3177static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
3178 BinaryOperatorKind Opcode,
3179 APValue &LHSValue,
3180 const APValue &RHSValue) {
3181 assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
3182 "Operation not supported on vector types");
3183
3184 const auto *VT = E->getType()->castAs<VectorType>();
3185 unsigned NumElements = VT->getNumElements();
3186 QualType EltTy = VT->getElementType();
3187
3188 // In the cases (typically C as I've observed) where we aren't evaluating
3189 // constexpr but are checking for cases where the LHS isn't yet evaluatable,
3190 // just give up.
3191 if (!LHSValue.isVector()) {
3192 assert(LHSValue.isLValue() &&
3193 "A vector result that isn't a vector OR uncalculated LValue");
3194 Info.FFDiag(E);
3195 return false;
3196 }
3197
3198 assert(LHSValue.getVectorLength() == NumElements &&
3199 RHSValue.getVectorLength() == NumElements && "Different vector sizes");
3200
3201 SmallVector<APValue, 4> ResultElements;
3202
3203 for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
3204 APValue LHSElt = LHSValue.getVectorElt(EltNum);
3205 APValue RHSElt = RHSValue.getVectorElt(EltNum);
3206
3207 if (EltTy->isIntegerType()) {
3208 APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
3209 EltTy->isUnsignedIntegerType()};
3210 bool Success = true;
3211
3212 if (BinaryOperator::isLogicalOp(Opcode))
3213 Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3214 else if (BinaryOperator::isComparisonOp(Opcode))
3215 Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
3216 else
3217 Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
3218 RHSElt.getInt(), EltResult);
3219
3220 if (!Success) {
3221 Info.FFDiag(E);
3222 return false;
3223 }
3224 ResultElements.emplace_back(EltResult);
3225
3226 } else if (EltTy->isFloatingType()) {
3227 assert(LHSElt.getKind() == APValue::Float &&
3228 RHSElt.getKind() == APValue::Float &&
3229 "Mismatched LHS/RHS/Result Type");
3230 APFloat LHSFloat = LHSElt.getFloat();
3231
3232 if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3233 RHSElt.getFloat())) {
3234 Info.FFDiag(E);
3235 return false;
3236 }
3237
3238 ResultElements.emplace_back(LHSFloat);
3239 }
3240 }
3241
3242 LHSValue = APValue(ResultElements.data(), ResultElements.size());
3243 return true;
3244}
3245
3246/// Cast an lvalue referring to a base subobject to a derived class, by
3247/// truncating the lvalue's path to the given length.
3248static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3249 const RecordDecl *TruncatedType,
3250 unsigned TruncatedElements) {
3251 SubobjectDesignator &D = Result.Designator;
3252
3253 // Check we actually point to a derived class object.
3254 if (TruncatedElements == D.Entries.size())
3255 return true;
3256 assert(TruncatedElements >= D.MostDerivedPathLength &&
3257 "not casting to a derived class");
3258 if (!Result.checkSubobject(Info, E, CSK_Derived))
3259 return false;
3260
3261 // Truncate the path to the subobject, and remove any derived-to-base offsets.
3262 const RecordDecl *RD = TruncatedType;
3263 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3264 if (RD->isInvalidDecl()) return false;
3265 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3266 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3267 if (isVirtualBaseClass(D.Entries[I]))
3268 Result.Offset -= Layout.getVBaseClassOffset(Base);
3269 else
3270 Result.Offset -= Layout.getBaseClassOffset(Base);
3271 RD = Base;
3272 }
3273 D.Entries.resize(TruncatedElements);
3274 return true;
3275}
3276
3277static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3278 const CXXRecordDecl *Derived,
3279 const CXXRecordDecl *Base,
3280 const ASTRecordLayout *RL = nullptr) {
3281 if (!RL) {
3282 if (Derived->isInvalidDecl()) return false;
3283 RL = &Info.Ctx.getASTRecordLayout(Derived);
3284 }
3285
3286 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3287 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3288 return true;
3289}
3290
3291static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3292 const CXXRecordDecl *DerivedDecl,
3293 const CXXBaseSpecifier *Base) {
3294 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3295
3296 if (!Base->isVirtual())
3297 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3298
3299 SubobjectDesignator &D = Obj.Designator;
3300 if (D.Invalid)
3301 return false;
3302
3303 // Extract most-derived object and corresponding type.
3304 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3305 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3306 return false;
3307
3308 // Find the virtual base class.
3309 if (DerivedDecl->isInvalidDecl()) return false;
3310 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3311 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3312 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3313 return true;
3314}
3315
3316static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3317 QualType Type, LValue &Result) {
3318 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3319 PathE = E->path_end();
3320 PathI != PathE; ++PathI) {
3321 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3322 *PathI))
3323 return false;
3324 Type = (*PathI)->getType();
3325 }
3326 return true;
3327}
3328
3329/// Cast an lvalue referring to a derived class to a known base subobject.
3330static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3331 const CXXRecordDecl *DerivedRD,
3332 const CXXRecordDecl *BaseRD) {
3333 CXXBasePaths Paths(/*FindAmbiguities=*/false,
3334 /*RecordPaths=*/true, /*DetectVirtual=*/false);
3335 if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3336 llvm_unreachable("Class must be derived from the passed in base class!");
3337
3338 for (CXXBasePathElement &Elem : Paths.front())
3339 if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3340 return false;
3341 return true;
3342}
3343
3344/// Update LVal to refer to the given field, which must be a member of the type
3345/// currently described by LVal.
3346static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3347 const FieldDecl *FD,
3348 const ASTRecordLayout *RL = nullptr) {
3349 if (!RL) {
3350 if (FD->getParent()->isInvalidDecl()) return false;
3351 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3352 }
3353
3354 unsigned I = FD->getFieldIndex();
3355 LVal.addDecl(Info, E, FD);
3356 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3357 return true;
3358}
3359
3360/// Update LVal to refer to the given indirect field.
3361static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3362 LValue &LVal,
3363 const IndirectFieldDecl *IFD) {
3364 for (const auto *C : IFD->chain())
3365 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3366 return false;
3367 return true;
3368}
3369
3370enum class SizeOfType {
3371 SizeOf,
3372 DataSizeOf,
3373};
3374
3375/// Get the size of the given type in char units.
3376static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type,
3377 CharUnits &Size, SizeOfType SOT = SizeOfType::SizeOf) {
3378 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3379 // extension.
3380 if (Type->isVoidType() || Type->isFunctionType()) {
3381 Size = CharUnits::One();
3382 return true;
3383 }
3384
3385 if (Type->isDependentType()) {
3386 Info.FFDiag(Loc);
3387 return false;
3388 }
3389
3390 if (!Type->isConstantSizeType()) {
3391 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3392 // FIXME: Better diagnostic.
3393 Info.FFDiag(Loc);
3394 return false;
3395 }
3396
3397 if (SOT == SizeOfType::SizeOf)
3398 Size = Info.Ctx.getTypeSizeInChars(Type);
3399 else
3400 Size = Info.Ctx.getTypeInfoDataSizeInChars(Type).Width;
3401 return true;
3402}
3403
3404/// Update a pointer value to model pointer arithmetic.
3405/// \param Info - Information about the ongoing evaluation.
3406/// \param E - The expression being evaluated, for diagnostic purposes.
3407/// \param LVal - The pointer value to be updated.
3408/// \param EltTy - The pointee type represented by LVal.
3409/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3410static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3411 LValue &LVal, QualType EltTy,
3412 APSInt Adjustment) {
3413 CharUnits SizeOfPointee;
3414 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3415 return false;
3416
3417 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3418 return true;
3419}
3420
3421static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3422 LValue &LVal, QualType EltTy,
3423 int64_t Adjustment) {
3424 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3425 APSInt::get(Adjustment));
3426}
3427
3428/// Update an lvalue to refer to a component of a complex number.
3429/// \param Info - Information about the ongoing evaluation.
3430/// \param LVal - The lvalue to be updated.
3431/// \param EltTy - The complex number's component type.
3432/// \param Imag - False for the real component, true for the imaginary.
3433static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3434 LValue &LVal, QualType EltTy,
3435 bool Imag) {
3436 if (Imag) {
3437 CharUnits SizeOfComponent;
3438 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3439 return false;
3440 LVal.Offset += SizeOfComponent;
3441 }
3442 LVal.addComplex(Info, E, EltTy, Imag);
3443 return true;
3444}
3445
3446static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E,
3447 LValue &LVal, QualType EltTy,
3448 uint64_t Size, uint64_t Idx) {
3449 if (Idx) {
3450 CharUnits SizeOfElement;
3451 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfElement))
3452 return false;
3453 LVal.Offset += SizeOfElement * Idx;
3454 }
3455 LVal.addVectorElement(Info, E, EltTy, Size, Idx);
3456 return true;
3457}
3458
3459/// Try to evaluate the initializer for a variable declaration.
3460///
3461/// \param Info Information about the ongoing evaluation.
3462/// \param E An expression to be used when printing diagnostics.
3463/// \param VD The variable whose initializer should be obtained.
3464/// \param Version The version of the variable within the frame.
3465/// \param Frame The frame in which the variable was created. Must be null
3466/// if this variable is not local to the evaluation.
3467/// \param Result Filled in with a pointer to the value of the variable.
3468static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3469 const VarDecl *VD, CallStackFrame *Frame,
3470 unsigned Version, APValue *&Result) {
3471 // C++23 [expr.const]p8 If we have a reference type allow unknown references
3472 // and pointers.
3473 bool AllowConstexprUnknown =
3474 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
3475
3476 APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3477
3478 // If this is a local variable, dig out its value.
3479 if (Frame) {
3480 Result = Frame->getTemporary(VD, Version);
3481 if (Result)
3482 return true;
3483
3484 if (!isa<ParmVarDecl>(VD)) {
3485 // Assume variables referenced within a lambda's call operator that were
3486 // not declared within the call operator are captures and during checking
3487 // of a potential constant expression, assume they are unknown constant
3488 // expressions.
3489 assert(isLambdaCallOperator(Frame->Callee) &&
3490 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3491 "missing value for local variable");
3492 if (Info.checkingPotentialConstantExpression())
3493 return false;
3494 // FIXME: This diagnostic is bogus; we do support captures. Is this code
3495 // still reachable at all?
3496 Info.FFDiag(E->getBeginLoc(),
3497 diag::note_unimplemented_constexpr_lambda_feature_ast)
3498 << "captures not currently allowed";
3499 return false;
3500 }
3501 }
3502
3503 // If we're currently evaluating the initializer of this declaration, use that
3504 // in-flight value.
3505 if (Info.EvaluatingDecl == Base) {
3506 Result = Info.EvaluatingDeclValue;
3507 return true;
3508 }
3509
3510 // P2280R4 struck the restriction that variable of reference type lifetime
3511 // should begin within the evaluation of E
3512 // Used to be C++20 [expr.const]p5.12.2:
3513 // ... its lifetime began within the evaluation of E;
3514 if (isa<ParmVarDecl>(VD) && !AllowConstexprUnknown) {
3515 // Assume parameters of a potential constant expression are usable in
3516 // constant expressions.
3517 if (!Info.checkingPotentialConstantExpression() ||
3518 !Info.CurrentCall->Callee ||
3519 !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3520 if (Info.getLangOpts().CPlusPlus11) {
3521 Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3522 << VD;
3523 NoteLValueLocation(Info, Base);
3524 } else {
3525 Info.FFDiag(E);
3526 }
3527 }
3528 return false;
3529 }
3530
3531 if (E->isValueDependent())
3532 return false;
3533
3534 // Dig out the initializer, and use the declaration which it's attached to.
3535 // FIXME: We should eventually check whether the variable has a reachable
3536 // initializing declaration.
3537 const Expr *Init = VD->getAnyInitializer(VD);
3538 // P2280R4 struck the restriction that variable of reference type should have
3539 // a preceding initialization.
3540 // Used to be C++20 [expr.const]p5.12:
3541 // ... reference has a preceding initialization and either ...
3542 if (!Init && !AllowConstexprUnknown) {
3543 // Don't diagnose during potential constant expression checking; an
3544 // initializer might be added later.
3545 if (!Info.checkingPotentialConstantExpression()) {
3546 Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3547 << VD;
3548 NoteLValueLocation(Info, Base);
3549 }
3550 return false;
3551 }
3552
3553 // P2280R4 struck the initialization requirement for variables of reference
3554 // type so we can no longer assume we have an Init.
3555 // Used to be C++20 [expr.const]p5.12:
3556 // ... reference has a preceding initialization and either ...
3557 if (Init && Init->isValueDependent()) {
3558 // The DeclRefExpr is not value-dependent, but the variable it refers to
3559 // has a value-dependent initializer. This should only happen in
3560 // constant-folding cases, where the variable is not actually of a suitable
3561 // type for use in a constant expression (otherwise the DeclRefExpr would
3562 // have been value-dependent too), so diagnose that.
3563 assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3564 if (!Info.checkingPotentialConstantExpression()) {
3565 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3566 ? diag::note_constexpr_ltor_non_constexpr
3567 : diag::note_constexpr_ltor_non_integral, 1)
3568 << VD << VD->getType();
3569 NoteLValueLocation(Info, Base);
3570 }
3571 return false;
3572 }
3573
3574 // Check that we can fold the initializer. In C++, we will have already done
3575 // this in the cases where it matters for conformance.
3576 // P2280R4 struck the initialization requirement for variables of reference
3577 // type so we can no longer assume we have an Init.
3578 // Used to be C++20 [expr.const]p5.12:
3579 // ... reference has a preceding initialization and either ...
3580 if (Init && !VD->evaluateValue()) {
3581 if (AllowConstexprUnknown) {
3582 Result = &Info.CurrentCall->createConstexprUnknownAPValues(VD, Base);
3583 return true;
3584 }
3585 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3586 NoteLValueLocation(Info, Base);
3587 return false;
3588 }
3589
3590 // Check that the variable is actually usable in constant expressions. For a
3591 // const integral variable or a reference, we might have a non-constant
3592 // initializer that we can nonetheless evaluate the initializer for. Such
3593 // variables are not usable in constant expressions. In C++98, the
3594 // initializer also syntactically needs to be an ICE.
3595 //
3596 // FIXME: We don't diagnose cases that aren't potentially usable in constant
3597 // expressions here; doing so would regress diagnostics for things like
3598 // reading from a volatile constexpr variable.
3599 if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3600 VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3601 ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3602 !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3603 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3604 NoteLValueLocation(Info, Base);
3605 }
3606
3607 // Never use the initializer of a weak variable, not even for constant
3608 // folding. We can't be sure that this is the definition that will be used.
3609 if (VD->isWeak()) {
3610 Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3611 NoteLValueLocation(Info, Base);
3612 return false;
3613 }
3614
3615 Result = VD->getEvaluatedValue();
3616
3617 // C++23 [expr.const]p8
3618 // ... For such an object that is not usable in constant expressions, the
3619 // dynamic type of the object is constexpr-unknown. For such a reference that
3620 // is not usable in constant expressions, the reference is treated as binding
3621 // to an unspecified object of the referenced type whose lifetime and that of
3622 // all subobjects includes the entire constant evaluation and whose dynamic
3623 // type is constexpr-unknown.
3624 if (AllowConstexprUnknown) {
3625 if (!Result)
3626 Result = &Info.CurrentCall->createConstexprUnknownAPValues(VD, Base);
3627 else
3628 Result->setConstexprUnknown();
3629 }
3630 return true;
3631}
3632
3633/// Get the base index of the given base class within an APValue representing
3634/// the given derived class.
3635static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3636 const CXXRecordDecl *Base) {
3637 Base = Base->getCanonicalDecl();
3638 unsigned Index = 0;
3640 E = Derived->bases_end(); I != E; ++I, ++Index) {
3641 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3642 return Index;
3643 }
3644
3645 llvm_unreachable("base class missing from derived class's bases list");
3646}
3647
3648/// Extract the value of a character from a string literal.
3649static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3650 uint64_t Index) {
3651 assert(!isa<SourceLocExpr>(Lit) &&
3652 "SourceLocExpr should have already been converted to a StringLiteral");
3653
3654 // FIXME: Support MakeStringConstant
3655 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3656 std::string Str;
3657 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3658 assert(Index <= Str.size() && "Index too large");
3659 return APSInt::getUnsigned(Str.c_str()[Index]);
3660 }
3661
3662 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3663 Lit = PE->getFunctionName();
3664 const StringLiteral *S = cast<StringLiteral>(Lit);
3665 const ConstantArrayType *CAT =
3666 Info.Ctx.getAsConstantArrayType(S->getType());
3667 assert(CAT && "string literal isn't an array");
3668 QualType CharType = CAT->getElementType();
3669 assert(CharType->isIntegerType() && "unexpected character type");
3670 APSInt Value(Info.Ctx.getTypeSize(CharType),
3671 CharType->isUnsignedIntegerType());
3672 if (Index < S->getLength())
3673 Value = S->getCodeUnit(Index);
3674 return Value;
3675}
3676
3677// Expand a string literal into an array of characters.
3678//
3679// FIXME: This is inefficient; we should probably introduce something similar
3680// to the LLVM ConstantDataArray to make this cheaper.
3681static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3682 APValue &Result,
3683 QualType AllocType = QualType()) {
3684 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3685 AllocType.isNull() ? S->getType() : AllocType);
3686 assert(CAT && "string literal isn't an array");
3687 QualType CharType = CAT->getElementType();
3688 assert(CharType->isIntegerType() && "unexpected character type");
3689
3690 unsigned Elts = CAT->getZExtSize();
3691 Result = APValue(APValue::UninitArray(),
3692 std::min(S->getLength(), Elts), Elts);
3693 APSInt Value(Info.Ctx.getTypeSize(CharType),
3694 CharType->isUnsignedIntegerType());
3695 if (Result.hasArrayFiller())
3696 Result.getArrayFiller() = APValue(Value);
3697 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3698 Value = S->getCodeUnit(I);
3699 Result.getArrayInitializedElt(I) = APValue(Value);
3700 }
3701}
3702
3703// Expand an array so that it has more than Index filled elements.
3704static void expandArray(APValue &Array, unsigned Index) {
3705 unsigned Size = Array.getArraySize();
3706 assert(Index < Size);
3707
3708 // Always at least double the number of elements for which we store a value.
3709 unsigned OldElts = Array.getArrayInitializedElts();
3710 unsigned NewElts = std::max(Index+1, OldElts * 2);
3711 NewElts = std::min(Size, std::max(NewElts, 8u));
3712
3713 // Copy the data across.
3714 APValue NewValue(APValue::UninitArray(), NewElts, Size);
3715 for (unsigned I = 0; I != OldElts; ++I)
3716 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3717 for (unsigned I = OldElts; I != NewElts; ++I)
3718 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3719 if (NewValue.hasArrayFiller())
3720 NewValue.getArrayFiller() = Array.getArrayFiller();
3721 Array.swap(NewValue);
3722}
3723
3724/// Determine whether a type would actually be read by an lvalue-to-rvalue
3725/// conversion. If it's of class type, we may assume that the copy operation
3726/// is trivial. Note that this is never true for a union type with fields
3727/// (because the copy always "reads" the active member) and always true for
3728/// a non-class type.
3729static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3732 return !RD || isReadByLvalueToRvalueConversion(RD);
3733}
3735 // FIXME: A trivial copy of a union copies the object representation, even if
3736 // the union is empty.
3737 if (RD->isUnion())
3738 return !RD->field_empty();
3739 if (RD->isEmpty())
3740 return false;
3741
3742 for (auto *Field : RD->fields())
3743 if (!Field->isUnnamedBitField() &&
3744 isReadByLvalueToRvalueConversion(Field->getType()))
3745 return true;
3746
3747 for (auto &BaseSpec : RD->bases())
3748 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3749 return true;
3750
3751 return false;
3752}
3753
3754/// Diagnose an attempt to read from any unreadable field within the specified
3755/// type, which might be a class type.
3756static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3757 QualType T) {
3759 if (!RD)
3760 return false;
3761
3762 if (!RD->hasMutableFields())
3763 return false;
3764
3765 for (auto *Field : RD->fields()) {
3766 // If we're actually going to read this field in some way, then it can't
3767 // be mutable. If we're in a union, then assigning to a mutable field
3768 // (even an empty one) can change the active member, so that's not OK.
3769 // FIXME: Add core issue number for the union case.
3770 if (Field->isMutable() &&
3771 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3772 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3773 Info.Note(Field->getLocation(), diag::note_declared_at);
3774 return true;
3775 }
3776
3777 if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3778 return true;
3779 }
3780
3781 for (auto &BaseSpec : RD->bases())
3782 if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3783 return true;
3784
3785 // All mutable fields were empty, and thus not actually read.
3786 return false;
3787}
3788
3789static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3791 bool MutableSubobject = false) {
3792 // A temporary or transient heap allocation we created.
3793 if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3794 return true;
3795
3796 switch (Info.IsEvaluatingDecl) {
3797 case EvalInfo::EvaluatingDeclKind::None:
3798 return false;
3799
3800 case EvalInfo::EvaluatingDeclKind::Ctor:
3801 // The variable whose initializer we're evaluating.
3802 if (Info.EvaluatingDecl == Base)
3803 return true;
3804
3805 // A temporary lifetime-extended by the variable whose initializer we're
3806 // evaluating.
3807 if (auto *BaseE = Base.dyn_cast<const Expr *>())
3808 if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3809 return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3810 return false;
3811
3812 case EvalInfo::EvaluatingDeclKind::Dtor:
3813 // C++2a [expr.const]p6:
3814 // [during constant destruction] the lifetime of a and its non-mutable
3815 // subobjects (but not its mutable subobjects) [are] considered to start
3816 // within e.
3817 if (MutableSubobject || Base != Info.EvaluatingDecl)
3818 return false;
3819 // FIXME: We can meaningfully extend this to cover non-const objects, but
3820 // we will need special handling: we should be able to access only
3821 // subobjects of such objects that are themselves declared const.
3822 QualType T = getType(Base);
3823 return T.isConstQualified() || T->isReferenceType();
3824 }
3825
3826 llvm_unreachable("unknown evaluating decl kind");
3827}
3828
3829static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT,
3830 SourceLocation CallLoc = {}) {
3831 return Info.CheckArraySize(
3832 CAT->getSizeExpr() ? CAT->getSizeExpr()->getBeginLoc() : CallLoc,
3833 CAT->getNumAddressingBits(Info.Ctx), CAT->getZExtSize(),
3834 /*Diag=*/true);
3835}
3836
3837namespace {
3838/// A handle to a complete object (an object that is not a subobject of
3839/// another object).
3840struct CompleteObject {
3841 /// The identity of the object.
3843 /// The value of the complete object.
3844 APValue *Value;
3845 /// The type of the complete object.
3846 QualType Type;
3847
3848 CompleteObject() : Value(nullptr) {}
3850 : Base(Base), Value(Value), Type(Type) {}
3851
3852 bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3853 // If this isn't a "real" access (eg, if it's just accessing the type
3854 // info), allow it. We assume the type doesn't change dynamically for
3855 // subobjects of constexpr objects (even though we'd hit UB here if it
3856 // did). FIXME: Is this right?
3857 if (!isAnyAccess(AK))
3858 return true;
3859
3860 // In C++14 onwards, it is permitted to read a mutable member whose
3861 // lifetime began within the evaluation.
3862 // FIXME: Should we also allow this in C++11?
3863 if (!Info.getLangOpts().CPlusPlus14 &&
3864 AK != AccessKinds::AK_IsWithinLifetime)
3865 return false;
3866 return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3867 }
3868
3869 explicit operator bool() const { return !Type.isNull(); }
3870};
3871} // end anonymous namespace
3872
3873static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3874 bool IsMutable = false) {
3875 // C++ [basic.type.qualifier]p1:
3876 // - A const object is an object of type const T or a non-mutable subobject
3877 // of a const object.
3878 if (ObjType.isConstQualified() && !IsMutable)
3879 SubobjType.addConst();
3880 // - A volatile object is an object of type const T or a subobject of a
3881 // volatile object.
3882 if (ObjType.isVolatileQualified())
3883 SubobjType.addVolatile();
3884 return SubobjType;
3885}
3886
3887/// Find the designated sub-object of an rvalue.
3888template <typename SubobjectHandler>
3889static typename SubobjectHandler::result_type
3890findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3891 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3892 if (Sub.Invalid)
3893 // A diagnostic will have already been produced.
3894 return handler.failed();
3895 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3896 if (Info.getLangOpts().CPlusPlus11)
3897 Info.FFDiag(E, Sub.isOnePastTheEnd()
3898 ? diag::note_constexpr_access_past_end
3899 : diag::note_constexpr_access_unsized_array)
3900 << handler.AccessKind;
3901 else
3902 Info.FFDiag(E);
3903 return handler.failed();
3904 }
3905
3906 APValue *O = Obj.Value;
3907 QualType ObjType = Obj.Type;
3908 const FieldDecl *LastField = nullptr;
3909 const FieldDecl *VolatileField = nullptr;
3910
3911 // C++23 [expr.const]p8 If we have an unknown reference or pointers and it
3912 // does not have a value then bail out.
3913 if (O->allowConstexprUnknown() && !O->hasValue())
3914 return false;
3915
3916 // Walk the designator's path to find the subobject.
3917 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3918 // Reading an indeterminate value is undefined, but assigning over one is OK.
3919 if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3920 (O->isIndeterminate() &&
3921 !isValidIndeterminateAccess(handler.AccessKind))) {
3922 // Object has ended lifetime.
3923 // If I is non-zero, some subobject (member or array element) of a
3924 // complete object has ended its lifetime, so this is valid for
3925 // IsWithinLifetime, resulting in false.
3926 if (I != 0 && handler.AccessKind == AK_IsWithinLifetime)
3927 return false;
3928 if (!Info.checkingPotentialConstantExpression())
3929 Info.FFDiag(E, diag::note_constexpr_access_uninit)
3930 << handler.AccessKind << O->isIndeterminate()
3931 << E->getSourceRange();
3932 return handler.failed();
3933 }
3934
3935 // C++ [class.ctor]p5, C++ [class.dtor]p5:
3936 // const and volatile semantics are not applied on an object under
3937 // {con,de}struction.
3938 if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3939 ObjType->isRecordType() &&
3940 Info.isEvaluatingCtorDtor(
3941 Obj.Base,
3942 llvm::ArrayRef(Sub.Entries.begin(), Sub.Entries.begin() + I)) !=
3943 ConstructionPhase::None) {
3944 ObjType = Info.Ctx.getCanonicalType(ObjType);
3945 ObjType.removeLocalConst();
3946 ObjType.removeLocalVolatile();
3947 }
3948
3949 // If this is our last pass, check that the final object type is OK.
3950 if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3951 // Accesses to volatile objects are prohibited.
3952 if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3953 if (Info.getLangOpts().CPlusPlus) {
3954 int DiagKind;
3956 const NamedDecl *Decl = nullptr;
3957 if (VolatileField) {
3958 DiagKind = 2;
3959 Loc = VolatileField->getLocation();
3960 Decl = VolatileField;
3961 } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3962 DiagKind = 1;
3963 Loc = VD->getLocation();
3964 Decl = VD;
3965 } else {
3966 DiagKind = 0;
3967 if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3968 Loc = E->getExprLoc();
3969 }
3970 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3971 << handler.AccessKind << DiagKind << Decl;
3972 Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3973 } else {
3974 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3975 }
3976 return handler.failed();
3977 }
3978
3979 // If we are reading an object of class type, there may still be more
3980 // things we need to check: if there are any mutable subobjects, we
3981 // cannot perform this read. (This only happens when performing a trivial
3982 // copy or assignment.)
3983 if (ObjType->isRecordType() &&
3984 !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3985 diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3986 return handler.failed();
3987 }
3988
3989 if (I == N) {
3990 if (!handler.found(*O, ObjType))
3991 return false;
3992
3993 // If we modified a bit-field, truncate it to the right width.
3994 if (isModification(handler.AccessKind) &&
3995 LastField && LastField->isBitField() &&
3996 !truncateBitfieldValue(Info, E, *O, LastField))
3997 return false;
3998
3999 return true;
4000 }
4001
4002 LastField = nullptr;
4003 if (ObjType->isArrayType()) {
4004 // Next subobject is an array element.
4005 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
4006 assert(CAT && "vla in literal type?");
4007 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4008 if (CAT->getSize().ule(Index)) {
4009 // Note, it should not be possible to form a pointer with a valid
4010 // designator which points more than one past the end of the array.
4011 if (Info.getLangOpts().CPlusPlus11)
4012 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4013 << handler.AccessKind;
4014 else
4015 Info.FFDiag(E);
4016 return handler.failed();
4017 }
4018
4019 ObjType = CAT->getElementType();
4020
4021 if (O->getArrayInitializedElts() > Index)
4022 O = &O->getArrayInitializedElt(Index);
4023 else if (!isRead(handler.AccessKind)) {
4024 if (!CheckArraySize(Info, CAT, E->getExprLoc()))
4025 return handler.failed();
4026
4027 expandArray(*O, Index);
4028 O = &O->getArrayInitializedElt(Index);
4029 } else
4030 O = &O->getArrayFiller();
4031 } else if (ObjType->isAnyComplexType()) {
4032 // Next subobject is a complex number.
4033 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4034 if (Index > 1) {
4035 if (Info.getLangOpts().CPlusPlus11)
4036 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4037 << handler.AccessKind;
4038 else
4039 Info.FFDiag(E);
4040 return handler.failed();
4041 }
4042
4043 ObjType = getSubobjectType(
4044 ObjType, ObjType->castAs<ComplexType>()->getElementType());
4045
4046 assert(I == N - 1 && "extracting subobject of scalar?");
4047 if (O->isComplexInt()) {
4048 return handler.found(Index ? O->getComplexIntImag()
4049 : O->getComplexIntReal(), ObjType);
4050 } else {
4051 assert(O->isComplexFloat());
4052 return handler.found(Index ? O->getComplexFloatImag()
4053 : O->getComplexFloatReal(), ObjType);
4054 }
4055 } else if (const auto *VT = ObjType->getAs<VectorType>()) {
4056 uint64_t Index = Sub.Entries[I].getAsArrayIndex();
4057 unsigned NumElements = VT->getNumElements();
4058 if (Index == NumElements) {
4059 if (Info.getLangOpts().CPlusPlus11)
4060 Info.FFDiag(E, diag::note_constexpr_access_past_end)
4061 << handler.AccessKind;
4062 else
4063 Info.FFDiag(E);
4064 return handler.failed();
4065 }
4066
4067 if (Index > NumElements) {
4068 Info.CCEDiag(E, diag::note_constexpr_array_index)
4069 << Index << /*array*/ 0 << NumElements;
4070 return handler.failed();
4071 }
4072
4073 ObjType = VT->getElementType();
4074 assert(I == N - 1 && "extracting subobject of scalar?");
4075 return handler.found(O->getVectorElt(Index), ObjType);
4076 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
4077 if (Field->isMutable() &&
4078 !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
4079 Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
4080 << handler.AccessKind << Field;
4081 Info.Note(Field->getLocation(), diag::note_declared_at);
4082 return handler.failed();
4083 }
4084
4085 // Next subobject is a class, struct or union field.
4086 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
4087 if (RD->isUnion()) {
4088 const FieldDecl *UnionField = O->getUnionField();
4089 if (!UnionField ||
4090 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
4091 if (I == N - 1 && handler.AccessKind == AK_Construct) {
4092 // Placement new onto an inactive union member makes it active.
4093 O->setUnion(Field, APValue());
4094 } else {
4095 // Pointer to/into inactive union member: Not within lifetime
4096 if (handler.AccessKind == AK_IsWithinLifetime)
4097 return false;
4098 // FIXME: If O->getUnionValue() is absent, report that there's no
4099 // active union member rather than reporting the prior active union
4100 // member. We'll need to fix nullptr_t to not use APValue() as its
4101 // representation first.
4102 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
4103 << handler.AccessKind << Field << !UnionField << UnionField;
4104 return handler.failed();
4105 }
4106 }
4107 O = &O->getUnionValue();
4108 } else
4109 O = &O->getStructField(Field->getFieldIndex());
4110
4111 ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
4112 LastField = Field;
4113 if (Field->getType().isVolatileQualified())
4114 VolatileField = Field;
4115 } else {
4116 // Next subobject is a base class.
4117 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
4118 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
4119 O = &O->getStructBase(getBaseIndex(Derived, Base));
4120
4121 ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
4122 }
4123 }
4124}
4125
4126namespace {
4127struct ExtractSubobjectHandler {
4128 EvalInfo &Info;
4129 const Expr *E;
4130 APValue &Result;
4131 const AccessKinds AccessKind;
4132
4133 typedef bool result_type;
4134 bool failed() { return false; }
4135 bool found(APValue &Subobj, QualType SubobjType) {
4136 Result = Subobj;
4137 if (AccessKind == AK_ReadObjectRepresentation)
4138 return true;
4139 return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
4140 }
4141 bool found(APSInt &Value, QualType SubobjType) {
4142 Result = APValue(Value);
4143 return true;
4144 }
4145 bool found(APFloat &Value, QualType SubobjType) {
4146 Result = APValue(Value);
4147 return true;
4148 }
4149};
4150} // end anonymous namespace
4151
4152/// Extract the designated sub-object of an rvalue.
4153static bool extractSubobject(EvalInfo &Info, const Expr *E,
4154 const CompleteObject &Obj,
4155 const SubobjectDesignator &Sub, APValue &Result,
4156 AccessKinds AK = AK_Read) {
4157 assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
4158 ExtractSubobjectHandler Handler = {Info, E, Result, AK};
4159 return findSubobject(Info, E, Obj, Sub, Handler);
4160}
4161
4162namespace {
4163struct ModifySubobjectHandler {
4164 EvalInfo &Info;
4165 APValue &NewVal;
4166 const Expr *E;
4167
4168 typedef bool result_type;
4169 static const AccessKinds AccessKind = AK_Assign;
4170
4171 bool checkConst(QualType QT) {
4172 // Assigning to a const object has undefined behavior.
4173 if (QT.isConstQualified()) {
4174 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4175 return false;
4176 }
4177 return true;
4178 }
4179
4180 bool failed() { return false; }
4181 bool found(APValue &Subobj, QualType SubobjType) {
4182 if (!checkConst(SubobjType))
4183 return false;
4184 // We've been given ownership of NewVal, so just swap it in.
4185 Subobj.swap(NewVal);
4186 return true;
4187 }
4188 bool found(APSInt &Value, QualType SubobjType) {
4189 if (!checkConst(SubobjType))
4190 return false;
4191 if (!NewVal.isInt()) {
4192 // Maybe trying to write a cast pointer value into a complex?
4193 Info.FFDiag(E);
4194 return false;
4195 }
4196 Value = NewVal.getInt();
4197 return true;
4198 }
4199 bool found(APFloat &Value, QualType SubobjType) {
4200 if (!checkConst(SubobjType))
4201 return false;
4202 Value = NewVal.getFloat();
4203 return true;
4204 }
4205};
4206} // end anonymous namespace
4207
4208const AccessKinds ModifySubobjectHandler::AccessKind;
4209
4210/// Update the designated sub-object of an rvalue to the given value.
4211static bool modifySubobject(EvalInfo &Info, const Expr *E,
4212 const CompleteObject &Obj,
4213 const SubobjectDesignator &Sub,
4214 APValue &NewVal) {
4215 ModifySubobjectHandler Handler = { Info, NewVal, E };
4216 return findSubobject(Info, E, Obj, Sub, Handler);
4217}
4218
4219/// Find the position where two subobject designators diverge, or equivalently
4220/// the length of the common initial subsequence.
4221static unsigned FindDesignatorMismatch(QualType ObjType,
4222 const SubobjectDesignator &A,
4223 const SubobjectDesignator &B,
4224 bool &WasArrayIndex) {
4225 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
4226 for (/**/; I != N; ++I) {
4227 if (!ObjType.isNull() &&
4228 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
4229 // Next subobject is an array element.
4230 if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
4231 WasArrayIndex = true;
4232 return I;
4233 }
4234 if (ObjType->isAnyComplexType())
4235 ObjType = ObjType->castAs<ComplexType>()->getElementType();
4236 else
4237 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
4238 } else {
4239 if (A.Entries[I].getAsBaseOrMember() !=
4240 B.Entries[I].getAsBaseOrMember()) {
4241 WasArrayIndex = false;
4242 return I;
4243 }
4244 if (const FieldDecl *FD = getAsField(A.Entries[I]))
4245 // Next subobject is a field.
4246 ObjType = FD->getType();
4247 else
4248 // Next subobject is a base class.
4249 ObjType = QualType();
4250 }
4251 }
4252 WasArrayIndex = false;
4253 return I;
4254}
4255
4256/// Determine whether the given subobject designators refer to elements of the
4257/// same array object.
4259 const SubobjectDesignator &A,
4260 const SubobjectDesignator &B) {
4261 if (A.Entries.size() != B.Entries.size())
4262 return false;
4263
4264 bool IsArray = A.MostDerivedIsArrayElement;
4265 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
4266 // A is a subobject of the array element.
4267 return false;
4268
4269 // If A (and B) designates an array element, the last entry will be the array
4270 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
4271 // of length 1' case, and the entire path must match.
4272 bool WasArrayIndex;
4273 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
4274 return CommonLength >= A.Entries.size() - IsArray;
4275}
4276
4277/// Find the complete object to which an LValue refers.
4278static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
4279 AccessKinds AK, const LValue &LVal,
4280 QualType LValType) {
4281 if (LVal.InvalidBase) {
4282 Info.FFDiag(E);
4283 return CompleteObject();
4284 }
4285
4286 if (!LVal.Base) {
4287 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
4288 return CompleteObject();
4289 }
4290
4291 CallStackFrame *Frame = nullptr;
4292 unsigned Depth = 0;
4293 if (LVal.getLValueCallIndex()) {
4294 std::tie(Frame, Depth) =
4295 Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
4296 if (!Frame) {
4297 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
4298 << AK << LVal.Base.is<const ValueDecl*>();
4299 NoteLValueLocation(Info, LVal.Base);
4300 return CompleteObject();
4301 }
4302 }
4303
4304 bool IsAccess = isAnyAccess(AK);
4305
4306 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
4307 // is not a constant expression (even if the object is non-volatile). We also
4308 // apply this rule to C++98, in order to conform to the expected 'volatile'
4309 // semantics.
4310 if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
4311 if (Info.getLangOpts().CPlusPlus)
4312 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
4313 << AK << LValType;
4314 else
4315 Info.FFDiag(E);
4316 return CompleteObject();
4317 }
4318
4319 // Compute value storage location and type of base object.
4320 APValue *BaseVal = nullptr;
4321 QualType BaseType = getType(LVal.Base);
4322
4323 if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
4324 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4325 // This is the object whose initializer we're evaluating, so its lifetime
4326 // started in the current evaluation.
4327 BaseVal = Info.EvaluatingDeclValue;
4328 } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
4329 // Allow reading from a GUID declaration.
4330 if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
4331 if (isModification(AK)) {
4332 // All the remaining cases do not permit modification of the object.
4333 Info.FFDiag(E, diag::note_constexpr_modify_global);
4334 return CompleteObject();
4335 }
4336 APValue &V = GD->getAsAPValue();
4337 if (V.isAbsent()) {
4338 Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4339 << GD->getType();
4340 return CompleteObject();
4341 }
4342 return CompleteObject(LVal.Base, &V, GD->getType());
4343 }
4344
4345 // Allow reading the APValue from an UnnamedGlobalConstantDecl.
4346 if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D)) {
4347 if (isModification(AK)) {
4348 Info.FFDiag(E, diag::note_constexpr_modify_global);
4349 return CompleteObject();
4350 }
4351 return CompleteObject(LVal.Base, const_cast<APValue *>(&GCD->getValue()),
4352 GCD->getType());
4353 }
4354
4355 // Allow reading from template parameter objects.
4356 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4357 if (isModification(AK)) {
4358 Info.FFDiag(E, diag::note_constexpr_modify_global);
4359 return CompleteObject();
4360 }
4361 return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4362 TPO->getType());
4363 }
4364
4365 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4366 // In C++11, constexpr, non-volatile variables initialized with constant
4367 // expressions are constant expressions too. Inside constexpr functions,
4368 // parameters are constant expressions even if they're non-const.
4369 // In C++1y, objects local to a constant expression (those with a Frame) are
4370 // both readable and writable inside constant expressions.
4371 // In C, such things can also be folded, although they are not ICEs.
4372 const VarDecl *VD = dyn_cast<VarDecl>(D);
4373 if (VD) {
4374 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4375 VD = VDef;
4376 }
4377 if (!VD || VD->isInvalidDecl()) {
4378 Info.FFDiag(E);
4379 return CompleteObject();
4380 }
4381
4382 bool IsConstant = BaseType.isConstant(Info.Ctx);
4383 bool ConstexprVar = false;
4384 if (const auto *VD = dyn_cast_if_present<VarDecl>(
4385 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
4386 ConstexprVar = VD->isConstexpr();
4387
4388 // Unless we're looking at a local variable or argument in a constexpr call,
4389 // the variable we're reading must be const.
4390 if (!Frame) {
4391 if (IsAccess && isa<ParmVarDecl>(VD)) {
4392 // Access of a parameter that's not associated with a frame isn't going
4393 // to work out, but we can leave it to evaluateVarDeclInit to provide a
4394 // suitable diagnostic.
4395 } else if (Info.getLangOpts().CPlusPlus14 &&
4396 lifetimeStartedInEvaluation(Info, LVal.Base)) {
4397 // OK, we can read and modify an object if we're in the process of
4398 // evaluating its initializer, because its lifetime began in this
4399 // evaluation.
4400 } else if (isModification(AK)) {
4401 // All the remaining cases do not permit modification of the object.
4402 Info.FFDiag(E, diag::note_constexpr_modify_global);
4403 return CompleteObject();
4404 } else if (VD->isConstexpr()) {
4405 // OK, we can read this variable.
4406 } else if (Info.getLangOpts().C23 && ConstexprVar) {
4407 Info.FFDiag(E);
4408 return CompleteObject();
4409 } else if (BaseType->isIntegralOrEnumerationType()) {
4410 if (!IsConstant) {
4411 if (!IsAccess)
4412 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4413 if (Info.getLangOpts().CPlusPlus) {
4414 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4415 Info.Note(VD->getLocation(), diag::note_declared_at);
4416 } else {
4417 Info.FFDiag(E);
4418 }
4419 return CompleteObject();
4420 }
4421 } else if (!IsAccess) {
4422 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4423 } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4424 BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4425 // This variable might end up being constexpr. Don't diagnose it yet.
4426 } else if (IsConstant) {
4427 // Keep evaluating to see what we can do. In particular, we support
4428 // folding of const floating-point types, in order to make static const
4429 // data members of such types (supported as an extension) more useful.
4430 if (Info.getLangOpts().CPlusPlus) {
4431 Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4432 ? diag::note_constexpr_ltor_non_constexpr
4433 : diag::note_constexpr_ltor_non_integral, 1)
4434 << VD << BaseType;
4435 Info.Note(VD->getLocation(), diag::note_declared_at);
4436 } else {
4437 Info.CCEDiag(E);
4438 }
4439 } else {
4440 // Never allow reading a non-const value.
4441 if (Info.getLangOpts().CPlusPlus) {
4442 Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4443 ? diag::note_constexpr_ltor_non_constexpr
4444 : diag::note_constexpr_ltor_non_integral, 1)
4445 << VD << BaseType;
4446 Info.Note(VD->getLocation(), diag::note_declared_at);
4447 } else {
4448 Info.FFDiag(E);
4449 }
4450 return CompleteObject();
4451 }
4452 }
4453
4454 if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4455 return CompleteObject();
4456 } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4457 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
4458 if (!Alloc) {
4459 Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4460 return CompleteObject();
4461 }
4462 return CompleteObject(LVal.Base, &(*Alloc)->Value,
4463 LVal.Base.getDynamicAllocType());
4464 } else {
4465 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4466
4467 if (!Frame) {
4468 if (const MaterializeTemporaryExpr *MTE =
4469 dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4470 assert(MTE->getStorageDuration() == SD_Static &&
4471 "should have a frame for a non-global materialized temporary");
4472
4473 // C++20 [expr.const]p4: [DR2126]
4474 // An object or reference is usable in constant expressions if it is
4475 // - a temporary object of non-volatile const-qualified literal type
4476 // whose lifetime is extended to that of a variable that is usable
4477 // in constant expressions
4478 //
4479 // C++20 [expr.const]p5:
4480 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4481 // - a non-volatile glvalue that refers to an object that is usable
4482 // in constant expressions, or
4483 // - a non-volatile glvalue of literal type that refers to a
4484 // non-volatile object whose lifetime began within the evaluation
4485 // of E;
4486 //
4487 // C++11 misses the 'began within the evaluation of e' check and
4488 // instead allows all temporaries, including things like:
4489 // int &&r = 1;
4490 // int x = ++r;
4491 // constexpr int k = r;
4492 // Therefore we use the C++14-onwards rules in C++11 too.
4493 //
4494 // Note that temporaries whose lifetimes began while evaluating a
4495 // variable's constructor are not usable while evaluating the
4496 // corresponding destructor, not even if they're of const-qualified
4497 // types.
4498 if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4499 !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4500 if (!IsAccess)
4501 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4502 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4503 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4504 return CompleteObject();
4505 }
4506
4507 BaseVal = MTE->getOrCreateValue(false);
4508 assert(BaseVal && "got reference to unevaluated temporary");
4509 } else {
4510 if (!IsAccess)
4511 return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4512 APValue Val;
4513 LVal.moveInto(Val);
4514 Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4515 << AK
4516 << Val.getAsString(Info.Ctx,
4517 Info.Ctx.getLValueReferenceType(LValType));
4518 NoteLValueLocation(Info, LVal.Base);
4519 return CompleteObject();
4520 }
4521 } else {
4522 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4523 assert(BaseVal && "missing value for temporary");
4524 }
4525 }
4526
4527 // In C++14, we can't safely access any mutable state when we might be
4528 // evaluating after an unmodeled side effect. Parameters are modeled as state
4529 // in the caller, but aren't visible once the call returns, so they can be
4530 // modified in a speculatively-evaluated call.
4531 //
4532 // FIXME: Not all local state is mutable. Allow local constant subobjects
4533 // to be read here (but take care with 'mutable' fields).
4534 unsigned VisibleDepth = Depth;
4535 if (llvm::isa_and_nonnull<ParmVarDecl>(
4536 LVal.Base.dyn_cast<const ValueDecl *>()))
4537 ++VisibleDepth;
4538 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4539 Info.EvalStatus.HasSideEffects) ||
4540 (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4541 return CompleteObject();
4542
4543 return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4544}
4545
4546/// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4547/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4548/// glvalue referred to by an entity of reference type.
4549///
4550/// \param Info - Information about the ongoing evaluation.
4551/// \param Conv - The expression for which we are performing the conversion.
4552/// Used for diagnostics.
4553/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4554/// case of a non-class type).
4555/// \param LVal - The glvalue on which we are attempting to perform this action.
4556/// \param RVal - The produced value will be placed here.
4557/// \param WantObjectRepresentation - If true, we're looking for the object
4558/// representation rather than the value, and in particular,
4559/// there is no requirement that the result be fully initialized.
4560static bool
4562 const LValue &LVal, APValue &RVal,
4563 bool WantObjectRepresentation = false) {
4564 if (LVal.Designator.Invalid)
4565 return false;
4566
4567 // Check for special cases where there is no existing APValue to look at.
4568 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4569
4570 AccessKinds AK =
4571 WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4572
4573 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4574 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4575 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4576 // initializer until now for such expressions. Such an expression can't be
4577 // an ICE in C, so this only matters for fold.
4578 if (Type.isVolatileQualified()) {
4579 Info.FFDiag(Conv);
4580 return false;
4581 }
4582
4583 APValue Lit;
4584 if (!Evaluate(Lit, Info, CLE->getInitializer()))
4585 return false;
4586
4587 // According to GCC info page:
4588 //
4589 // 6.28 Compound Literals
4590 //
4591 // As an optimization, G++ sometimes gives array compound literals longer
4592 // lifetimes: when the array either appears outside a function or has a
4593 // const-qualified type. If foo and its initializer had elements of type
4594 // char *const rather than char *, or if foo were a global variable, the
4595 // array would have static storage duration. But it is probably safest
4596 // just to avoid the use of array compound literals in C++ code.
4597 //
4598 // Obey that rule by checking constness for converted array types.
4599
4600 QualType CLETy = CLE->getType();
4601 if (CLETy->isArrayType() && !Type->isArrayType()) {
4602 if (!CLETy.isConstant(Info.Ctx)) {
4603 Info.FFDiag(Conv);
4604 Info.Note(CLE->getExprLoc(), diag::note_declared_at);
4605 return false;
4606 }
4607 }
4608
4609 CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4610 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4611 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4612 // Special-case character extraction so we don't have to construct an
4613 // APValue for the whole string.
4614 assert(LVal.Designator.Entries.size() <= 1 &&
4615 "Can only read characters from string literals");
4616 if (LVal.Designator.Entries.empty()) {
4617 // Fail for now for LValue to RValue conversion of an array.
4618 // (This shouldn't show up in C/C++, but it could be triggered by a
4619 // weird EvaluateAsRValue call from a tool.)
4620 Info.FFDiag(Conv);
4621 return false;
4622 }
4623 if (LVal.Designator.isOnePastTheEnd()) {
4624 if (Info.getLangOpts().CPlusPlus11)
4625 Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4626 else
4627 Info.FFDiag(Conv);
4628 return false;
4629 }
4630 uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4631 RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4632 return true;
4633 }
4634 }
4635
4636 CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4637 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4638}
4639
4640/// Perform an assignment of Val to LVal. Takes ownership of Val.
4641static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4642 QualType LValType, APValue &Val) {
4643 if (LVal.Designator.Invalid)
4644 return false;
4645
4646 if (!Info.getLangOpts().CPlusPlus14) {
4647 Info.FFDiag(E);
4648 return false;
4649 }
4650
4651 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4652 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4653}
4654
4655namespace {
4656struct CompoundAssignSubobjectHandler {
4657 EvalInfo &Info;
4659 QualType PromotedLHSType;
4661 const APValue &RHS;
4662
4663 static const AccessKinds AccessKind = AK_Assign;
4664
4665 typedef bool result_type;
4666
4667 bool checkConst(QualType QT) {
4668 // Assigning to a const object has undefined behavior.
4669 if (QT.isConstQualified()) {
4670 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4671 return false;
4672 }
4673 return true;
4674 }
4675
4676 bool failed() { return false; }
4677 bool found(APValue &Subobj, QualType SubobjType) {
4678 switch (Subobj.getKind()) {
4679 case APValue::Int:
4680 return found(Subobj.getInt(), SubobjType);
4681 case APValue::Float:
4682 return found(Subobj.getFloat(), SubobjType);
4685 // FIXME: Implement complex compound assignment.
4686 Info.FFDiag(E);
4687 return false;
4688 case APValue::LValue:
4689 return foundPointer(Subobj, SubobjType);
4690 case APValue::Vector:
4691 return foundVector(Subobj, SubobjType);
4693 Info.FFDiag(E, diag::note_constexpr_access_uninit)
4694 << /*read of=*/0 << /*uninitialized object=*/1
4695 << E->getLHS()->getSourceRange();
4696 return false;
4697 default:
4698 // FIXME: can this happen?
4699 Info.FFDiag(E);
4700 return false;
4701 }
4702 }
4703
4704 bool foundVector(APValue &Value, QualType SubobjType) {
4705 if (!checkConst(SubobjType))
4706 return false;
4707
4708 if (!SubobjType->isVectorType()) {
4709 Info.FFDiag(E);
4710 return false;
4711 }
4712 return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4713 }
4714
4715 bool found(APSInt &Value, QualType SubobjType) {
4716 if (!checkConst(SubobjType))
4717 return false;
4718
4719 if (!SubobjType->isIntegerType()) {
4720 // We don't support compound assignment on integer-cast-to-pointer
4721 // values.
4722 Info.FFDiag(E);
4723 return false;
4724 }
4725
4726 if (RHS.isInt()) {
4727 APSInt LHS =
4728 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4729 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4730 return false;
4731 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4732 return true;
4733 } else if (RHS.isFloat()) {
4734 const FPOptions FPO = E->getFPFeaturesInEffect(
4735 Info.Ctx.getLangOpts());
4736 APFloat FValue(0.0);
4737 return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4738 PromotedLHSType, FValue) &&
4739 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4740 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4741 Value);
4742 }
4743
4744 Info.FFDiag(E);
4745 return false;
4746 }
4747 bool found(APFloat &Value, QualType SubobjType) {
4748 return checkConst(SubobjType) &&
4749 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4750 Value) &&
4751 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4752 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4753 }
4754 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4755 if (!checkConst(SubobjType))
4756 return false;
4757
4758 QualType PointeeType;
4759 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4760 PointeeType = PT->getPointeeType();
4761
4762 if (PointeeType.isNull() || !RHS.isInt() ||
4763 (Opcode != BO_Add && Opcode != BO_Sub)) {
4764 Info.FFDiag(E);
4765 return false;
4766 }
4767
4768 APSInt Offset = RHS.getInt();
4769 if (Opcode == BO_Sub)
4770 negateAsSigned(Offset);
4771
4772 LValue LVal;
4773 LVal.setFrom(Info.Ctx, Subobj);
4774 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4775 return false;
4776 LVal.moveInto(Subobj);
4777 return true;
4778 }
4779};
4780} // end anonymous namespace
4781
4782const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4783
4784/// Perform a compound assignment of LVal <op>= RVal.
4785static bool handleCompoundAssignment(EvalInfo &Info,
4787 const LValue &LVal, QualType LValType,
4788 QualType PromotedLValType,
4789 BinaryOperatorKind Opcode,
4790 const APValue &RVal) {
4791 if (LVal.Designator.Invalid)
4792 return false;
4793
4794 if (!Info.getLangOpts().CPlusPlus14) {
4795 Info.FFDiag(E);
4796 return false;
4797 }
4798
4799 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4800 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4801 RVal };
4802 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4803}
4804
4805namespace {
4806struct IncDecSubobjectHandler {
4807 EvalInfo &Info;
4808 const UnaryOperator *E;
4809 AccessKinds AccessKind;
4810 APValue *Old;
4811
4812 typedef bool result_type;
4813
4814 bool checkConst(QualType QT) {
4815 // Assigning to a const object has undefined behavior.
4816 if (QT.isConstQualified()) {
4817 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4818 return false;
4819 }
4820 return true;
4821 }
4822
4823 bool failed() { return false; }
4824 bool found(APValue &Subobj, QualType SubobjType) {
4825 // Stash the old value. Also clear Old, so we don't clobber it later
4826 // if we're post-incrementing a complex.
4827 if (Old) {
4828 *Old = Subobj;
4829 Old = nullptr;
4830 }
4831
4832 switch (Subobj.getKind()) {
4833 case APValue::Int:
4834 return found(Subobj.getInt(), SubobjType);
4835 case APValue::Float:
4836 return found(Subobj.getFloat(), SubobjType);
4838 return found(Subobj.getComplexIntReal(),
4839 SubobjType->castAs<ComplexType>()->getElementType()
4840 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4842 return found(Subobj.getComplexFloatReal(),
4843 SubobjType->castAs<ComplexType>()->getElementType()
4844 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4845 case APValue::LValue:
4846 return foundPointer(Subobj, SubobjType);
4847 default:
4848 // FIXME: can this happen?
4849 Info.FFDiag(E);
4850 return false;
4851 }
4852 }
4853 bool found(APSInt &Value, QualType SubobjType) {
4854 if (!checkConst(SubobjType))
4855 return false;
4856
4857 if (!SubobjType->isIntegerType()) {
4858 // We don't support increment / decrement on integer-cast-to-pointer
4859 // values.
4860 Info.FFDiag(E);
4861 return false;
4862 }
4863
4864 if (Old) *Old = APValue(Value);
4865
4866 // bool arithmetic promotes to int, and the conversion back to bool
4867 // doesn't reduce mod 2^n, so special-case it.
4868 if (SubobjType->isBooleanType()) {
4869 if (AccessKind == AK_Increment)
4870 Value = 1;
4871 else
4872 Value = !Value;
4873 return true;
4874 }
4875
4876 bool WasNegative = Value.isNegative();
4877 if (AccessKind == AK_Increment) {
4878 ++Value;
4879
4880 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4881 APSInt ActualValue(Value, /*IsUnsigned*/true);
4882 return HandleOverflow(Info, E, ActualValue, SubobjType);
4883 }
4884 } else {
4885 --Value;
4886
4887 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4888 unsigned BitWidth = Value.getBitWidth();
4889 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4890 ActualValue.setBit(BitWidth);
4891 return HandleOverflow(Info, E, ActualValue, SubobjType);
4892 }
4893 }
4894 return true;
4895 }
4896 bool found(APFloat &Value, QualType SubobjType) {
4897 if (!checkConst(SubobjType))
4898 return false;
4899
4900 if (Old) *Old = APValue(Value);
4901
4902 APFloat One(Value.getSemantics(), 1);
4903 llvm::RoundingMode RM = getActiveRoundingMode(Info, E);
4904 APFloat::opStatus St;
4905 if (AccessKind == AK_Increment)
4906 St = Value.add(One, RM);
4907 else
4908 St = Value.subtract(One, RM);
4909 return checkFloatingPointResult(Info, E, St);
4910 }
4911 bool foundPointer(APValue &Subobj, QualType SubobjType) {
4912 if (!checkConst(SubobjType))
4913 return false;
4914
4915 QualType PointeeType;
4916 if (const PointerType *PT = SubobjType->getAs<PointerType>())
4917 PointeeType = PT->getPointeeType();
4918 else {
4919 Info.FFDiag(E);
4920 return false;
4921 }
4922
4923 LValue LVal;
4924 LVal.setFrom(Info.Ctx, Subobj);
4925 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4926 AccessKind == AK_Increment ? 1 : -1))
4927 return false;
4928 LVal.moveInto(Subobj);
4929 return true;
4930 }
4931};
4932} // end anonymous namespace
4933
4934/// Perform an increment or decrement on LVal.
4935static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4936 QualType LValType, bool IsIncrement, APValue *Old) {
4937 if (LVal.Designator.Invalid)
4938 return false;
4939
4940 if (!Info.getLangOpts().CPlusPlus14) {
4941 Info.FFDiag(E);
4942 return false;
4943 }
4944
4945 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4946 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4947 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4948 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4949}
4950
4951/// Build an lvalue for the object argument of a member function call.
4952static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4953 LValue &This) {
4954 if (Object->getType()->isPointerType() && Object->isPRValue())
4955 return EvaluatePointer(Object, This, Info);
4956
4957 if (Object->isGLValue())
4958 return EvaluateLValue(Object, This, Info);
4959
4960 if (Object->getType()->isLiteralType(Info.Ctx))
4961 return EvaluateTemporary(Object, This, Info);
4962
4963 if (Object->getType()->isRecordType() && Object->isPRValue())
4964 return EvaluateTemporary(Object, This, Info);
4965
4966 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4967 return false;
4968}
4969
4970/// HandleMemberPointerAccess - Evaluate a member access operation and build an
4971/// lvalue referring to the result.
4972///
4973/// \param Info - Information about the ongoing evaluation.
4974/// \param LV - An lvalue referring to the base of the member pointer.
4975/// \param RHS - The member pointer expression.
4976/// \param IncludeMember - Specifies whether the member itself is included in
4977/// the resulting LValue subobject designator. This is not possible when
4978/// creating a bound member function.
4979/// \return The field or method declaration to which the member pointer refers,
4980/// or 0 if evaluation fails.
4981static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4982 QualType LVType,
4983 LValue &LV,
4984 const Expr *RHS,
4985 bool IncludeMember = true) {
4986 MemberPtr MemPtr;
4987 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4988 return nullptr;
4989
4990 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4991 // member value, the behavior is undefined.
4992 if (!MemPtr.getDecl()) {
4993 // FIXME: Specific diagnostic.
4994 Info.FFDiag(RHS);
4995 return nullptr;
4996 }
4997
4998 if (MemPtr.isDerivedMember()) {
4999 // This is a member of some derived class. Truncate LV appropriately.
5000 // The end of the derived-to-base path for the base object must match the
5001 // derived-to-base path for the member pointer.
5002 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
5003 LV.Designator.Entries.size()) {
5004 Info.FFDiag(RHS);
5005 return nullptr;
5006 }
5007 unsigned PathLengthToMember =
5008 LV.Designator.Entries.size() - MemPtr.Path.size();
5009 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
5010 const CXXRecordDecl *LVDecl = getAsBaseClass(
5011 LV.Designator.Entries[PathLengthToMember + I]);
5012 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
5013 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
5014 Info.FFDiag(RHS);
5015 return nullptr;
5016 }
5017 }
5018
5019 // Truncate the lvalue to the appropriate derived class.
5020 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
5021 PathLengthToMember))
5022 return nullptr;
5023 } else if (!MemPtr.Path.empty()) {
5024 // Extend the LValue path with the member pointer's path.
5025 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
5026 MemPtr.Path.size() + IncludeMember);
5027
5028 // Walk down to the appropriate base class.
5029 if (const PointerType *PT = LVType->getAs<PointerType>())
5030 LVType = PT->getPointeeType();
5031 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
5032 assert(RD && "member pointer access on non-class-type expression");
5033 // The first class in the path is that of the lvalue.
5034 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
5035 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
5036 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
5037 return nullptr;
5038 RD = Base;
5039 }
5040 // Finally cast to the class containing the member.
5041 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
5042 MemPtr.getContainingRecord()))
5043 return nullptr;
5044 }
5045
5046 // Add the member. Note that we cannot build bound member functions here.
5047 if (IncludeMember) {
5048 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
5049 if (!HandleLValueMember(Info, RHS, LV, FD))
5050 return nullptr;
5051 } else if (const IndirectFieldDecl *IFD =
5052 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
5053 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
5054 return nullptr;
5055 } else {
5056 llvm_unreachable("can't construct reference to bound member function");
5057 }
5058 }
5059
5060 return MemPtr.getDecl();
5061}
5062
5063static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
5064 const BinaryOperator *BO,
5065 LValue &LV,
5066 bool IncludeMember = true) {
5067 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
5068
5069 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
5070 if (Info.noteFailure()) {
5071 MemberPtr MemPtr;
5072 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
5073 }
5074 return nullptr;
5075 }
5076
5077 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
5078 BO->getRHS(), IncludeMember);
5079}
5080
5081/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
5082/// the provided lvalue, which currently refers to the base object.
5083static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
5084 LValue &Result) {
5085 SubobjectDesignator &D = Result.Designator;
5086 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
5087 return false;
5088
5089 QualType TargetQT = E->getType();
5090 if (const PointerType *PT = TargetQT->getAs<PointerType>())
5091 TargetQT = PT->getPointeeType();
5092
5093 // Check this cast lands within the final derived-to-base subobject path.
5094 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
5095 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5096 << D.MostDerivedType << TargetQT;
5097 return false;
5098 }
5099
5100 // Check the type of the final cast. We don't need to check the path,
5101 // since a cast can only be formed if the path is unique.
5102 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
5103 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
5104 const CXXRecordDecl *FinalType;
5105 if (NewEntriesSize == D.MostDerivedPathLength)
5106 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
5107 else
5108 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
5109 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
5110 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
5111 << D.MostDerivedType << TargetQT;
5112 return false;
5113 }
5114
5115 // Truncate the lvalue to the appropriate derived class.
5116 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
5117}
5118
5119/// Get the value to use for a default-initialized object of type T.
5120/// Return false if it encounters something invalid.
5122 bool Success = true;
5123
5124 // If there is already a value present don't overwrite it.
5125 if (!Result.isAbsent())
5126 return true;
5127
5128 if (auto *RD = T->getAsCXXRecordDecl()) {
5129 if (RD->isInvalidDecl()) {
5130 Result = APValue();
5131 return false;
5132 }
5133 if (RD->isUnion()) {
5134 Result = APValue((const FieldDecl *)nullptr);
5135 return true;
5136 }
5137 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5138 std::distance(RD->field_begin(), RD->field_end()));
5139
5140 unsigned Index = 0;
5141 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5142 End = RD->bases_end();
5143 I != End; ++I, ++Index)
5144 Success &=
5145 handleDefaultInitValue(I->getType(), Result.getStructBase(Index));
5146
5147 for (const auto *I : RD->fields()) {
5148 if (I->isUnnamedBitField())
5149 continue;
5151 I->getType(), Result.getStructField(I->getFieldIndex()));
5152 }
5153 return Success;
5154 }
5155
5156 if (auto *AT =
5157 dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
5158 Result = APValue(APValue::UninitArray(), 0, AT->getZExtSize());
5159 if (Result.hasArrayFiller())
5160 Success &=
5161 handleDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
5162
5163 return Success;
5164 }
5165
5166 Result = APValue::IndeterminateValue();
5167 return true;
5168}
5169
5170namespace {
5171enum EvalStmtResult {
5172 /// Evaluation failed.
5173 ESR_Failed,
5174 /// Hit a 'return' statement.
5175 ESR_Returned,
5176 /// Evaluation succeeded.
5177 ESR_Succeeded,
5178 /// Hit a 'continue' statement.
5179 ESR_Continue,
5180 /// Hit a 'break' statement.
5181 ESR_Break,
5182 /// Still scanning for 'case' or 'default' statement.
5183 ESR_CaseNotFound
5184};
5185}
5186
5187static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
5188 if (VD->isInvalidDecl())
5189 return false;
5190 // We don't need to evaluate the initializer for a static local.
5191 if (!VD->hasLocalStorage())
5192 return true;
5193
5194 LValue Result;
5195 APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
5196 ScopeKind::Block, Result);
5197
5198 const Expr *InitE = VD->getInit();
5199 if (!InitE) {
5200 if (VD->getType()->isDependentType())
5201 return Info.noteSideEffect();
5202 return handleDefaultInitValue(VD->getType(), Val);
5203 }
5204 if (InitE->isValueDependent())
5205 return false;
5206
5207 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
5208 // Wipe out any partially-computed value, to allow tracking that this
5209 // evaluation failed.
5210 Val = APValue();
5211 return false;
5212 }
5213
5214 return true;
5215}
5216
5217static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
5218 bool OK = true;
5219
5220 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5221 OK &= EvaluateVarDecl(Info, VD);
5222
5223 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
5224 for (auto *BD : DD->bindings())
5225 if (auto *VD = BD->getHoldingVar())
5226 OK &= EvaluateDecl(Info, VD);
5227
5228 return OK;
5229}
5230
5231static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
5232 assert(E->isValueDependent());
5233 if (Info.noteSideEffect())
5234 return true;
5235 assert(E->containsErrors() && "valid value-dependent expression should never "
5236 "reach invalid code path.");
5237 return false;
5238}
5239
5240/// Evaluate a condition (either a variable declaration or an expression).
5241static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
5242 const Expr *Cond, bool &Result) {
5243 if (Cond->isValueDependent())
5244 return false;
5245 FullExpressionRAII Scope(Info);
5246 if (CondDecl && !EvaluateDecl(Info, CondDecl))
5247 return false;
5248 if (!EvaluateAsBooleanCondition(Cond, Result, Info))
5249 return false;
5250 return Scope.destroy();
5251}
5252
5253namespace {
5254/// A location where the result (returned value) of evaluating a
5255/// statement should be stored.
5256struct StmtResult {
5257 /// The APValue that should be filled in with the returned value.
5258 APValue &Value;
5259 /// The location containing the result, if any (used to support RVO).
5260 const LValue *Slot;
5261};
5262
5263struct TempVersionRAII {
5264 CallStackFrame &Frame;
5265
5266 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
5267 Frame.pushTempVersion();
5268 }
5269
5270 ~TempVersionRAII() {
5271 Frame.popTempVersion();
5272 }
5273};
5274
5275}
5276
5277static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5278 const Stmt *S,
5279 const SwitchCase *SC = nullptr);
5280
5281/// Evaluate the body of a loop, and translate the result as appropriate.
5282static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
5283 const Stmt *Body,
5284 const SwitchCase *Case = nullptr) {
5285 BlockScopeRAII Scope(Info);
5286
5287 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
5288 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5289 ESR = ESR_Failed;
5290
5291 switch (ESR) {
5292 case ESR_Break:
5293 return ESR_Succeeded;
5294 case ESR_Succeeded:
5295 case ESR_Continue:
5296 return ESR_Continue;
5297 case ESR_Failed:
5298 case ESR_Returned:
5299 case ESR_CaseNotFound:
5300 return ESR;
5301 }
5302 llvm_unreachable("Invalid EvalStmtResult!");
5303}
5304
5305/// Evaluate a switch statement.
5306static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
5307 const SwitchStmt *SS) {
5308 BlockScopeRAII Scope(Info);
5309
5310 // Evaluate the switch condition.
5311 APSInt Value;
5312 {
5313 if (const Stmt *Init = SS->getInit()) {
5314 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5315 if (ESR != ESR_Succeeded) {
5316 if (ESR != ESR_Failed && !Scope.destroy())
5317 ESR = ESR_Failed;
5318 return ESR;
5319 }
5320 }
5321
5322 FullExpressionRAII CondScope(Info);
5323 if (SS->getConditionVariable() &&
5324 !EvaluateDecl(Info, SS->getConditionVariable()))
5325 return ESR_Failed;
5326 if (SS->getCond()->isValueDependent()) {
5327 // We don't know what the value is, and which branch should jump to.
5328 EvaluateDependentExpr(SS->getCond(), Info);
5329 return ESR_Failed;
5330 }
5331 if (!EvaluateInteger(SS->getCond(), Value, Info))
5332 return ESR_Failed;
5333
5334 if (!CondScope.destroy())
5335 return ESR_Failed;
5336 }
5337
5338 // Find the switch case corresponding to the value of the condition.
5339 // FIXME: Cache this lookup.
5340 const SwitchCase *Found = nullptr;
5341 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
5342 SC = SC->getNextSwitchCase()) {
5343 if (isa<DefaultStmt>(SC)) {
5344 Found = SC;
5345 continue;
5346 }
5347
5348 const CaseStmt *CS = cast<CaseStmt>(SC);
5349 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
5350 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
5351 : LHS;
5352 if (LHS <= Value && Value <= RHS) {
5353 Found = SC;
5354 break;
5355 }
5356 }
5357
5358 if (!Found)
5359 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5360
5361 // Search the switch body for the switch case and evaluate it from there.
5362 EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
5363 if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
5364 return ESR_Failed;
5365
5366 switch (ESR) {
5367 case ESR_Break:
5368 return ESR_Succeeded;
5369 case ESR_Succeeded:
5370 case ESR_Continue:
5371 case ESR_Failed:
5372 case ESR_Returned:
5373 return ESR;
5374 case ESR_CaseNotFound:
5375 // This can only happen if the switch case is nested within a statement
5376 // expression. We have no intention of supporting that.
5377 Info.FFDiag(Found->getBeginLoc(),
5378 diag::note_constexpr_stmt_expr_unsupported);
5379 return ESR_Failed;
5380 }
5381 llvm_unreachable("Invalid EvalStmtResult!");
5382}
5383
5384static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD) {
5385 // An expression E is a core constant expression unless the evaluation of E
5386 // would evaluate one of the following: [C++23] - a control flow that passes
5387 // through a declaration of a variable with static or thread storage duration
5388 // unless that variable is usable in constant expressions.
5389 if (VD->isLocalVarDecl() && VD->isStaticLocal() &&
5390 !VD->isUsableInConstantExpressions(Info.Ctx)) {
5391 Info.CCEDiag(VD->getLocation(), diag::note_constexpr_static_local)
5392 << (VD->getTSCSpec() == TSCS_unspecified ? 0 : 1) << VD;
5393 return false;
5394 }
5395 return true;
5396}
5397
5398// Evaluate a statement.
5399static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
5400 const Stmt *S, const SwitchCase *Case) {
5401 if (!Info.nextStep(S))
5402 return ESR_Failed;
5403
5404 // If we're hunting down a 'case' or 'default' label, recurse through
5405 // substatements until we hit the label.
5406 if (Case) {
5407 switch (S->getStmtClass()) {
5408 case Stmt::CompoundStmtClass:
5409 // FIXME: Precompute which substatement of a compound statement we
5410 // would jump to, and go straight there rather than performing a
5411 // linear scan each time.
5412 case Stmt::LabelStmtClass:
5413 case Stmt::AttributedStmtClass:
5414 case Stmt::DoStmtClass:
5415 break;
5416
5417 case Stmt::CaseStmtClass:
5418 case Stmt::DefaultStmtClass:
5419 if (Case == S)
5420 Case = nullptr;
5421 break;
5422
5423 case Stmt::IfStmtClass: {
5424 // FIXME: Precompute which side of an 'if' we would jump to, and go
5425 // straight there rather than scanning both sides.
5426 const IfStmt *IS = cast<IfStmt>(S);
5427
5428 // Wrap the evaluation in a block scope, in case it's a DeclStmt
5429 // preceded by our switch label.
5430 BlockScopeRAII Scope(Info);
5431
5432 // Step into the init statement in case it brings an (uninitialized)
5433 // variable into scope.
5434 if (const Stmt *Init = IS->getInit()) {
5435 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5436 if (ESR != ESR_CaseNotFound) {
5437 assert(ESR != ESR_Succeeded);
5438 return ESR;
5439 }
5440 }
5441
5442 // Condition variable must be initialized if it exists.
5443 // FIXME: We can skip evaluating the body if there's a condition
5444 // variable, as there can't be any case labels within it.
5445 // (The same is true for 'for' statements.)
5446
5447 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5448 if (ESR == ESR_Failed)
5449 return ESR;
5450 if (ESR != ESR_CaseNotFound)
5451 return Scope.destroy() ? ESR : ESR_Failed;
5452 if (!IS->getElse())
5453 return ESR_CaseNotFound;
5454
5455 ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5456 if (ESR == ESR_Failed)
5457 return ESR;
5458 if (ESR != ESR_CaseNotFound)
5459 return Scope.destroy() ? ESR : ESR_Failed;
5460 return ESR_CaseNotFound;
5461 }
5462
5463 case Stmt::WhileStmtClass: {
5464 EvalStmtResult ESR =
5465 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5466 if (ESR != ESR_Continue)
5467 return ESR;
5468 break;
5469 }
5470
5471 case Stmt::ForStmtClass: {
5472 const ForStmt *FS = cast<ForStmt>(S);
5473 BlockScopeRAII Scope(Info);
5474
5475 // Step into the init statement in case it brings an (uninitialized)
5476 // variable into scope.
5477 if (const Stmt *Init = FS->getInit()) {
5478 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5479 if (ESR != ESR_CaseNotFound) {
5480 assert(ESR != ESR_Succeeded);
5481 return ESR;
5482 }
5483 }
5484
5485 EvalStmtResult ESR =
5486 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5487 if (ESR != ESR_Continue)
5488 return ESR;
5489 if (const auto *Inc = FS->getInc()) {
5490 if (Inc->isValueDependent()) {
5491 if (!EvaluateDependentExpr(Inc, Info))
5492 return ESR_Failed;
5493 } else {
5494 FullExpressionRAII IncScope(Info);
5495 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5496 return ESR_Failed;
5497 }
5498 }
5499 break;
5500 }
5501
5502 case Stmt::DeclStmtClass: {
5503 // Start the lifetime of any uninitialized variables we encounter. They
5504 // might be used by the selected branch of the switch.
5505 const DeclStmt *DS = cast<DeclStmt>(S);
5506 for (const auto *D : DS->decls()) {
5507 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5508 if (!CheckLocalVariableDeclaration(Info, VD))
5509 return ESR_Failed;
5510 if (VD->hasLocalStorage() && !VD->getInit())
5511 if (!EvaluateVarDecl(Info, VD))
5512 return ESR_Failed;
5513 // FIXME: If the variable has initialization that can't be jumped
5514 // over, bail out of any immediately-surrounding compound-statement
5515 // too. There can't be any case labels here.
5516 }
5517 }
5518 return ESR_CaseNotFound;
5519 }
5520
5521 default:
5522 return ESR_CaseNotFound;
5523 }
5524 }
5525
5526 switch (S->getStmtClass()) {
5527 default:
5528 if (const Expr *E = dyn_cast<Expr>(S)) {
5529 if (E->isValueDependent()) {
5530 if (!EvaluateDependentExpr(E, Info))
5531 return ESR_Failed;
5532 } else {
5533 // Don't bother evaluating beyond an expression-statement which couldn't
5534 // be evaluated.
5535 // FIXME: Do we need the FullExpressionRAII object here?
5536 // VisitExprWithCleanups should create one when necessary.
5537 FullExpressionRAII Scope(Info);
5538 if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5539 return ESR_Failed;
5540 }
5541 return ESR_Succeeded;
5542 }
5543
5544 Info.FFDiag(S->getBeginLoc()) << S->getSourceRange();
5545 return ESR_Failed;
5546
5547 case Stmt::NullStmtClass:
5548 return ESR_Succeeded;
5549
5550 case Stmt::DeclStmtClass: {
5551 const DeclStmt *DS = cast<DeclStmt>(S);
5552 for (const auto *D : DS->decls()) {
5553 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D);
5554 if (VD && !CheckLocalVariableDeclaration(Info, VD))
5555 return ESR_Failed;
5556 // Each declaration initialization is its own full-expression.
5557 FullExpressionRAII Scope(Info);
5558 if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5559 return ESR_Failed;
5560 if (!Scope.destroy())
5561 return ESR_Failed;
5562 }
5563 return ESR_Succeeded;
5564 }
5565
5566 case Stmt::ReturnStmtClass: {
5567 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5568 FullExpressionRAII Scope(Info);
5569 if (RetExpr && RetExpr->isValueDependent()) {
5570 EvaluateDependentExpr(RetExpr, Info);
5571 // We know we returned, but we don't know what the value is.
5572 return ESR_Failed;
5573 }
5574 if (RetExpr &&
5575 !(Result.Slot
5576 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5577 : Evaluate(Result.Value, Info, RetExpr)))
5578 return ESR_Failed;
5579 return Scope.destroy() ? ESR_Returned : ESR_Failed;
5580 }
5581
5582 case Stmt::CompoundStmtClass: {
5583 BlockScopeRAII Scope(Info);
5584
5585 const CompoundStmt *CS = cast<CompoundStmt>(S);
5586 for (const auto *BI : CS->body()) {
5587 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5588 if (ESR == ESR_Succeeded)
5589 Case = nullptr;
5590 else if (ESR != ESR_CaseNotFound) {
5591 if (ESR != ESR_Failed && !Scope.destroy())
5592 return ESR_Failed;
5593 return ESR;
5594 }
5595 }
5596 if (Case)
5597 return ESR_CaseNotFound;
5598 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5599 }
5600
5601 case Stmt::IfStmtClass: {
5602 const IfStmt *IS = cast<IfStmt>(S);
5603
5604 // Evaluate the condition, as either a var decl or as an expression.
5605 BlockScopeRAII Scope(Info);
5606 if (const Stmt *Init = IS->getInit()) {
5607 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5608 if (ESR != ESR_Succeeded) {
5609 if (ESR != ESR_Failed && !Scope.destroy())
5610 return ESR_Failed;
5611 return ESR;
5612 }
5613 }
5614 bool Cond;
5615 if (IS->isConsteval()) {
5616 Cond = IS->isNonNegatedConsteval();
5617 // If we are not in a constant context, if consteval should not evaluate
5618 // to true.
5619 if (!Info.InConstantContext)
5620 Cond = !Cond;
5621 } else if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(),
5622 Cond))
5623 return ESR_Failed;
5624
5625 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5626 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5627 if (ESR != ESR_Succeeded) {
5628 if (ESR != ESR_Failed && !Scope.destroy())
5629 return ESR_Failed;
5630 return ESR;
5631 }
5632 }
5633 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5634 }
5635
5636 case Stmt::WhileStmtClass: {
5637 const WhileStmt *WS = cast<WhileStmt>(S);
5638 while (true) {
5639 BlockScopeRAII Scope(Info);
5640 bool Continue;
5641 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5642 Continue))
5643 return ESR_Failed;
5644 if (!Continue)
5645 break;
5646
5647 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5648 if (ESR != ESR_Continue) {
5649 if (ESR != ESR_Failed && !Scope.destroy())
5650 return ESR_Failed;
5651 return ESR;
5652 }
5653 if (!Scope.destroy())
5654 return ESR_Failed;
5655 }
5656 return ESR_Succeeded;
5657 }
5658
5659 case Stmt::DoStmtClass: {
5660 const DoStmt *DS = cast<DoStmt>(S);
5661 bool Continue;
5662 do {
5663 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5664 if (ESR != ESR_Continue)
5665 return ESR;
5666 Case = nullptr;
5667
5668 if (DS->getCond()->isValueDependent()) {
5669 EvaluateDependentExpr(DS->getCond(), Info);
5670 // Bailout as we don't know whether to keep going or terminate the loop.
5671 return ESR_Failed;
5672 }
5673 FullExpressionRAII CondScope(Info);
5674 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5675 !CondScope.destroy())
5676 return ESR_Failed;
5677 } while (Continue);
5678 return ESR_Succeeded;
5679 }
5680
5681 case Stmt::ForStmtClass: {
5682 const ForStmt *FS = cast<ForStmt>(S);
5683 BlockScopeRAII ForScope(Info);
5684 if (FS->getInit()) {
5685 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5686 if (ESR != ESR_Succeeded) {
5687 if (ESR != ESR_Failed && !ForScope.destroy())
5688 return ESR_Failed;
5689 return ESR;
5690 }
5691 }
5692 while (true) {
5693 BlockScopeRAII IterScope(Info);
5694 bool Continue = true;
5695 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5696 FS->getCond(), Continue))
5697 return ESR_Failed;
5698 if (!Continue)
5699 break;
5700
5701 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5702 if (ESR != ESR_Continue) {
5703 if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5704 return ESR_Failed;
5705 return ESR;
5706 }
5707
5708 if (const auto *Inc = FS->getInc()) {
5709 if (Inc->isValueDependent()) {
5710 if (!EvaluateDependentExpr(Inc, Info))
5711 return ESR_Failed;
5712 } else {
5713 FullExpressionRAII IncScope(Info);
5714 if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5715 return ESR_Failed;
5716 }
5717 }
5718
5719 if (!IterScope.destroy())
5720 return ESR_Failed;
5721 }
5722 return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5723 }
5724
5725 case Stmt::CXXForRangeStmtClass: {
5726 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5727 BlockScopeRAII Scope(Info);
5728
5729 // Evaluate the init-statement if present.
5730 if (FS->getInit()) {
5731 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5732 if (ESR != ESR_Succeeded) {
5733 if (ESR != ESR_Failed && !Scope.destroy())
5734 return ESR_Failed;
5735 return ESR;
5736 }
5737 }
5738
5739 // Initialize the __range variable.
5740 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5741 if (ESR != ESR_Succeeded) {
5742 if (ESR != ESR_Failed && !Scope.destroy())
5743 return ESR_Failed;
5744 return ESR;
5745 }
5746
5747 // In error-recovery cases it's possible to get here even if we failed to
5748 // synthesize the __begin and __end variables.
5749 if (!FS->getBeginStmt() || !FS->getEndStmt() || !FS->getCond())
5750 return ESR_Failed;
5751
5752 // Create the __begin and __end iterators.
5753 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5754 if (ESR != ESR_Succeeded) {
5755 if (ESR != ESR_Failed && !Scope.destroy())
5756 return ESR_Failed;
5757 return ESR;
5758 }
5759 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5760 if (ESR != ESR_Succeeded) {
5761 if (ESR != ESR_Failed && !Scope.destroy())
5762 return ESR_Failed;
5763 return ESR;
5764 }
5765
5766 while (true) {
5767 // Condition: __begin != __end.
5768 {
5769 if (FS->getCond()->isValueDependent()) {
5770 EvaluateDependentExpr(FS->getCond(), Info);
5771 // We don't know whether to keep going or terminate the loop.
5772 return ESR_Failed;
5773 }
5774 bool Continue = true;
5775 FullExpressionRAII CondExpr(Info);
5776 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5777 return ESR_Failed;
5778 if (!Continue)
5779 break;
5780 }
5781
5782 // User's variable declaration, initialized by *__begin.
5783 BlockScopeRAII InnerScope(Info);
5784 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5785 if (ESR != ESR_Succeeded) {
5786 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5787 return ESR_Failed;
5788 return ESR;
5789 }
5790
5791 // Loop body.
5792 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5793 if (ESR != ESR_Continue) {
5794 if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5795 return ESR_Failed;
5796 return ESR;
5797 }
5798 if (FS->getInc()->isValueDependent()) {
5799 if (!EvaluateDependentExpr(FS->getInc(), Info))
5800 return ESR_Failed;
5801 } else {
5802 // Increment: ++__begin
5803 if (!EvaluateIgnoredValue(Info, FS->getInc()))
5804 return ESR_Failed;
5805 }
5806
5807 if (!InnerScope.destroy())
5808 return ESR_Failed;
5809 }
5810
5811 return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5812 }
5813
5814 case Stmt::SwitchStmtClass:
5815 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5816
5817 case Stmt::ContinueStmtClass:
5818 return ESR_Continue;
5819
5820 case Stmt::BreakStmtClass:
5821 return ESR_Break;
5822
5823 case Stmt::LabelStmtClass:
5824 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5825
5826 case Stmt::AttributedStmtClass: {
5827 const auto *AS = cast<AttributedStmt>(S);
5828 const auto *SS = AS->getSubStmt();
5829 MSConstexprContextRAII ConstexprContext(
5830 *Info.CurrentCall, hasSpecificAttr<MSConstexprAttr>(AS->getAttrs()) &&
5831 isa<ReturnStmt>(SS));
5832
5833 auto LO = Info.getASTContext().getLangOpts();
5834 if (LO.CXXAssumptions && !LO.MSVCCompat) {
5835 for (auto *Attr : AS->getAttrs()) {
5836 auto *AA = dyn_cast<CXXAssumeAttr>(Attr);
5837 if (!AA)
5838 continue;
5839
5840 auto *Assumption = AA->getAssumption();
5841 if (Assumption->isValueDependent())
5842 return ESR_Failed;
5843
5844 if (Assumption->HasSideEffects(Info.getASTContext()))
5845 continue;
5846
5847 bool Value;
5848 if (!EvaluateAsBooleanCondition(Assumption, Value, Info))
5849 return ESR_Failed;
5850 if (!Value) {
5851 Info.CCEDiag(Assumption->getExprLoc(),
5852 diag::note_constexpr_assumption_failed);
5853 return ESR_Failed;
5854 }
5855 }
5856 }
5857
5858 return EvaluateStmt(Result, Info, SS, Case);
5859 }
5860
5861 case Stmt::CaseStmtClass:
5862 case Stmt::DefaultStmtClass:
5863 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5864 case Stmt::CXXTryStmtClass:
5865 // Evaluate try blocks by evaluating all sub statements.
5866 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5867 }
5868}
5869
5870/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5871/// default constructor. If so, we'll fold it whether or not it's marked as
5872/// constexpr. If it is marked as constexpr, we will never implicitly define it,
5873/// so we need special handling.
5875 const CXXConstructorDecl *CD,
5876 bool IsValueInitialization) {
5877 if (!CD->isTrivial() || !CD->isDefaultConstructor())
5878 return false;
5879
5880 // Value-initialization does not call a trivial default constructor, so such a
5881 // call is a core constant expression whether or not the constructor is
5882 // constexpr.
5883 if (!CD->isConstexpr() && !IsValueInitialization) {
5884 if (Info.getLangOpts().CPlusPlus11) {
5885 // FIXME: If DiagDecl is an implicitly-declared special member function,
5886 // we should be much more explicit about why it's not constexpr.
5887 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5888 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5889 Info.Note(CD->getLocation(), diag::note_declared_at);
5890 } else {
5891 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5892 }
5893 }
5894 return true;
5895}
5896
5897/// CheckConstexprFunction - Check that a function can be called in a constant
5898/// expression.
5899static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5901 const FunctionDecl *Definition,
5902 const Stmt *Body) {
5903 // Potential constant expressions can contain calls to declared, but not yet
5904 // defined, constexpr functions.
5905 if (Info.checkingPotentialConstantExpression() && !Definition &&
5906 Declaration->isConstexpr())
5907 return false;
5908
5909 // Bail out if the function declaration itself is invalid. We will
5910 // have produced a relevant diagnostic while parsing it, so just
5911 // note the problematic sub-expression.
5912 if (Declaration->isInvalidDecl()) {
5913 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5914 return false;
5915 }
5916
5917 // DR1872: An instantiated virtual constexpr function can't be called in a
5918 // constant expression (prior to C++20). We can still constant-fold such a
5919 // call.
5920 if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5921 cast<CXXMethodDecl>(Declaration)->isVirtual())
5922 Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5923
5924 if (Definition && Definition->isInvalidDecl()) {
5925 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5926 return false;
5927 }
5928
5929 // Can we evaluate this function call?
5930 if (Definition && Body &&
5931 (Definition->isConstexpr() || (Info.CurrentCall->CanEvalMSConstexpr &&
5932 Definition->hasAttr<MSConstexprAttr>())))
5933 return true;
5934
5935 if (Info.getLangOpts().CPlusPlus11) {
5936 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5937
5938 // If this function is not constexpr because it is an inherited
5939 // non-constexpr constructor, diagnose that directly.
5940 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5941 if (CD && CD->isInheritingConstructor()) {
5942 auto *Inherited = CD->getInheritedConstructor().getConstructor();
5943 if (!Inherited->isConstexpr())
5944 DiagDecl = CD = Inherited;
5945 }
5946
5947 // FIXME: If DiagDecl is an implicitly-declared special member function
5948 // or an inheriting constructor, we should be much more explicit about why
5949 // it's not constexpr.
5950 if (CD && CD->isInheritingConstructor())
5951 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5952 << CD->getInheritedConstructor().getConstructor()->getParent();
5953 else
5954 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5955 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5956 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5957 } else {
5958 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5959 }
5960 return false;
5961}
5962
5963namespace {
5964struct CheckDynamicTypeHandler {
5965 AccessKinds AccessKind;
5966 typedef bool result_type;
5967 bool failed() { return false; }
5968 bool found(APValue &Subobj, QualType SubobjType) { return true; }
5969 bool found(APSInt &Value, QualType SubobjType) { return true; }
5970 bool found(APFloat &Value, QualType SubobjType) { return true; }
5971};
5972} // end anonymous namespace
5973
5974/// Check that we can access the notional vptr of an object / determine its
5975/// dynamic type.
5976static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5977 AccessKinds AK, bool Polymorphic) {
5978 // We are not allowed to invoke a virtual function whose dynamic type
5979 // is constexpr-unknown, so stop early and let this fail later on if we
5980 // attempt to do so.
5981 // C++23 [expr.const]p5.6
5982 // an invocation of a virtual function ([class.virtual]) for an object whose
5983 // dynamic type is constexpr-unknown;
5984 if (This.allowConstexprUnknown())
5985 return true;
5986
5987 if (This.Designator.Invalid)
5988 return false;
5989
5990 CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5991
5992 if (!Obj)
5993 return false;
5994
5995 if (!Obj.Value) {
5996 // The object is not usable in constant expressions, so we can't inspect
5997 // its value to see if it's in-lifetime or what the active union members
5998 // are. We can still check for a one-past-the-end lvalue.
5999 if (This.Designator.isOnePastTheEnd() ||
6000 This.Designator.isMostDerivedAnUnsizedArray()) {
6001 Info.FFDiag(E, This.Designator.isOnePastTheEnd()
6002 ? diag::note_constexpr_access_past_end
6003 : diag::note_constexpr_access_unsized_array)
6004 << AK;
6005 return false;
6006 } else if (Polymorphic) {
6007 // Conservatively refuse to perform a polymorphic operation if we would
6008 // not be able to read a notional 'vptr' value.
6009 APValue Val;
6010 This.moveInto(Val);
6011 QualType StarThisType =
6012 Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
6013 Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
6014 << AK << Val.getAsString(Info.Ctx, StarThisType);
6015 return false;
6016 }
6017 return true;
6018 }
6019
6020 CheckDynamicTypeHandler Handler{AK};
6021 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6022}
6023
6024/// Check that the pointee of the 'this' pointer in a member function call is
6025/// either within its lifetime or in its period of construction or destruction.
6026static bool
6028 const LValue &This,
6029 const CXXMethodDecl *NamedMember) {
6030 return checkDynamicType(
6031 Info, E, This,
6032 isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
6033}
6034
6036 /// The dynamic class type of the object.
6038 /// The corresponding path length in the lvalue.
6039 unsigned PathLength;
6040};
6041
6042static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
6043 unsigned PathLength) {
6044 assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
6045 Designator.Entries.size() && "invalid path length");
6046 return (PathLength == Designator.MostDerivedPathLength)
6047 ? Designator.MostDerivedType->getAsCXXRecordDecl()
6048 : getAsBaseClass(Designator.Entries[PathLength - 1]);
6049}
6050
6051/// Determine the dynamic type of an object.
6052static std::optional<DynamicType> ComputeDynamicType(EvalInfo &Info,
6053 const Expr *E,
6054 LValue &This,
6055 AccessKinds AK) {
6056 // If we don't have an lvalue denoting an object of class type, there is no
6057 // meaningful dynamic type. (We consider objects of non-class type to have no
6058 // dynamic type.)
6059 if (!checkDynamicType(Info, E, This, AK,
6060 (AK == AK_TypeId
6061 ? (E->getType()->isReferenceType() ? true : false)
6062 : true)))
6063 return std::nullopt;
6064
6065 if (This.Designator.Invalid)
6066 return std::nullopt;
6067
6068 // Refuse to compute a dynamic type in the presence of virtual bases. This
6069 // shouldn't happen other than in constant-folding situations, since literal
6070 // types can't have virtual bases.
6071 //
6072 // Note that consumers of DynamicType assume that the type has no virtual
6073 // bases, and will need modifications if this restriction is relaxed.
6074 const CXXRecordDecl *Class =
6075 This.Designator.MostDerivedType->getAsCXXRecordDecl();
6076 if (!Class || Class->getNumVBases()) {
6077 Info.FFDiag(E);
6078 return std::nullopt;
6079 }
6080
6081 // FIXME: For very deep class hierarchies, it might be beneficial to use a
6082 // binary search here instead. But the overwhelmingly common case is that
6083 // we're not in the middle of a constructor, so it probably doesn't matter
6084 // in practice.
6085 ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
6086 for (unsigned PathLength = This.Designator.MostDerivedPathLength;
6087 PathLength <= Path.size(); ++PathLength) {
6088 switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
6089 Path.slice(0, PathLength))) {
6090 case ConstructionPhase::Bases:
6091 case ConstructionPhase::DestroyingBases:
6092 // We're constructing or destroying a base class. This is not the dynamic
6093 // type.
6094 break;
6095
6096 case ConstructionPhase::None:
6097 case ConstructionPhase::AfterBases:
6098 case ConstructionPhase::AfterFields:
6099 case ConstructionPhase::Destroying:
6100 // We've finished constructing the base classes and not yet started
6101 // destroying them again, so this is the dynamic type.
6102 return DynamicType{getBaseClassType(This.Designator, PathLength),
6103 PathLength};
6104 }
6105 }
6106
6107 // CWG issue 1517: we're constructing a base class of the object described by
6108 // 'This', so that object has not yet begun its period of construction and
6109 // any polymorphic operation on it results in undefined behavior.
6110 Info.FFDiag(E);
6111 return std::nullopt;
6112}
6113
6114/// Perform virtual dispatch.
6116 EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
6117 llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
6118 std::optional<DynamicType> DynType = ComputeDynamicType(
6119 Info, E, This,
6120 isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
6121 if (!DynType)
6122 return nullptr;
6123
6124 // Find the final overrider. It must be declared in one of the classes on the
6125 // path from the dynamic type to the static type.
6126 // FIXME: If we ever allow literal types to have virtual base classes, that
6127 // won't be true.
6128 const CXXMethodDecl *Callee = Found;
6129 unsigned PathLength = DynType->PathLength;
6130 for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
6131 const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
6132 const CXXMethodDecl *Overrider =
6133 Found->getCorrespondingMethodDeclaredInClass(Class, false);
6134 if (Overrider) {
6135 Callee = Overrider;
6136 break;
6137 }
6138 }
6139
6140 // C++2a [class.abstract]p6:
6141 // the effect of making a virtual call to a pure virtual function [...] is
6142 // undefined
6143 if (Callee->isPureVirtual()) {
6144 Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
6145 Info.Note(Callee->getLocation(), diag::note_declared_at);
6146 return nullptr;
6147 }
6148
6149 // If necessary, walk the rest of the path to determine the sequence of
6150 // covariant adjustment steps to apply.
6151 if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
6152 Found->getReturnType())) {
6153 CovariantAdjustmentPath.push_back(Callee->getReturnType());
6154 for (unsigned CovariantPathLength = PathLength + 1;
6155 CovariantPathLength != This.Designator.Entries.size();
6156 ++CovariantPathLength) {
6157 const CXXRecordDecl *NextClass =
6158 getBaseClassType(This.Designator, CovariantPathLength);
6159 const CXXMethodDecl *Next =
6160 Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
6161 if (Next && !Info.Ctx.hasSameUnqualifiedType(
6162 Next->getReturnType(), CovariantAdjustmentPath.back()))
6163 CovariantAdjustmentPath.push_back(Next->getReturnType());
6164 }
6165 if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
6166 CovariantAdjustmentPath.back()))
6167 CovariantAdjustmentPath.push_back(Found->getReturnType());
6168 }
6169
6170 // Perform 'this' adjustment.
6171 if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
6172 return nullptr;
6173
6174 return Callee;
6175}
6176
6177/// Perform the adjustment from a value returned by a virtual function to
6178/// a value of the statically expected type, which may be a pointer or
6179/// reference to a base class of the returned type.
6180static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
6181 APValue &Result,
6183 assert(Result.isLValue() &&
6184 "unexpected kind of APValue for covariant return");
6185 if (Result.isNullPointer())
6186 return true;
6187
6188 LValue LVal;
6189 LVal.setFrom(Info.Ctx, Result);
6190
6191 const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
6192 for (unsigned I = 1; I != Path.size(); ++I) {
6193 const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
6194 assert(OldClass && NewClass && "unexpected kind of covariant return");
6195 if (OldClass != NewClass &&
6196 !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
6197 return false;
6198 OldClass = NewClass;
6199 }
6200
6201 LVal.moveInto(Result);
6202 return true;
6203}
6204
6205/// Determine whether \p Base, which is known to be a direct base class of
6206/// \p Derived, is a public base class.
6207static bool isBaseClassPublic(const CXXRecordDecl *Derived,
6208 const CXXRecordDecl *Base) {
6209 for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
6210 auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
6211 if (BaseClass && declaresSameEntity(BaseClass, Base))
6212 return BaseSpec.getAccessSpecifier() == AS_public;
6213 }
6214 llvm_unreachable("Base is not a direct base of Derived");
6215}
6216
6217/// Apply the given dynamic cast operation on the provided lvalue.
6218///
6219/// This implements the hard case of dynamic_cast, requiring a "runtime check"
6220/// to find a suitable target subobject.
6221static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
6222 LValue &Ptr) {
6223 // We can't do anything with a non-symbolic pointer value.
6224 SubobjectDesignator &D = Ptr.Designator;
6225 if (D.Invalid)
6226 return false;
6227
6228 // C++ [expr.dynamic.cast]p6:
6229 // If v is a null pointer value, the result is a null pointer value.
6230 if (Ptr.isNullPointer() && !E->isGLValue())
6231 return true;
6232
6233 // For all the other cases, we need the pointer to point to an object within
6234 // its lifetime / period of construction / destruction, and we need to know
6235 // its dynamic type.
6236 std::optional<DynamicType> DynType =
6237 ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
6238 if (!DynType)
6239 return false;
6240
6241 // C++ [expr.dynamic.cast]p7:
6242 // If T is "pointer to cv void", then the result is a pointer to the most
6243 // derived object
6244 if (E->getType()->isVoidPointerType())
6245 return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
6246
6247 const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
6248 assert(C && "dynamic_cast target is not void pointer nor class");
6249 CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
6250
6251 auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
6252 // C++ [expr.dynamic.cast]p9:
6253 if (!E->isGLValue()) {
6254 // The value of a failed cast to pointer type is the null pointer value
6255 // of the required result type.
6256 Ptr.setNull(Info.Ctx, E->getType());
6257 return true;
6258 }
6259
6260 // A failed cast to reference type throws [...] std::bad_cast.
6261 unsigned DiagKind;
6262 if (!Paths && (declaresSameEntity(DynType->Type, C) ||
6263 DynType->Type->isDerivedFrom(C)))
6264 DiagKind = 0;
6265 else if (!Paths || Paths->begin() == Paths->end())
6266 DiagKind = 1;
6267 else if (Paths->isAmbiguous(CQT))
6268 DiagKind = 2;
6269 else {
6270 assert(Paths->front().Access != AS_public && "why did the cast fail?");
6271 DiagKind = 3;
6272 }
6273 Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
6274 << DiagKind << Ptr.Designator.getType(Info.Ctx)
6275 << Info.Ctx.getRecordType(DynType->Type)
6277 return false;
6278 };
6279
6280 // Runtime check, phase 1:
6281 // Walk from the base subobject towards the derived object looking for the
6282 // target type.
6283 for (int PathLength = Ptr.Designator.Entries.size();
6284 PathLength >= (int)DynType->PathLength; --PathLength) {
6285 const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
6287 return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
6288 // We can only walk across public inheritance edges.
6289 if (PathLength > (int)DynType->PathLength &&
6290 !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
6291 Class))
6292 return RuntimeCheckFailed(nullptr);
6293 }
6294
6295 // Runtime check, phase 2:
6296 // Search the dynamic type for an unambiguous public base of type C.
6297 CXXBasePaths Paths(/*FindAmbiguities=*/true,
6298 /*RecordPaths=*/true, /*DetectVirtual=*/false);
6299 if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
6300 Paths.front().Access == AS_public) {
6301 // Downcast to the dynamic type...
6302 if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
6303 return false;
6304 // ... then upcast to the chosen base class subobject.
6305 for (CXXBasePathElement &Elem : Paths.front())
6306 if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
6307 return false;
6308 return true;
6309 }
6310
6311 // Otherwise, the runtime check fails.
6312 return RuntimeCheckFailed(&Paths);
6313}
6314
6315namespace {
6316struct StartLifetimeOfUnionMemberHandler {
6317 EvalInfo &Info;
6318 const Expr *LHSExpr;
6319 const FieldDecl *Field;
6320 bool DuringInit;
6321 bool Failed = false;
6322 static const AccessKinds AccessKind = AK_Assign;
6323
6324 typedef bool result_type;
6325 bool failed() { return Failed; }
6326 bool found(APValue &Subobj, QualType SubobjType) {
6327 // We are supposed to perform no initialization but begin the lifetime of
6328 // the object. We interpret that as meaning to do what default
6329 // initialization of the object would do if all constructors involved were
6330 // trivial:
6331 // * All base, non-variant member, and array element subobjects' lifetimes
6332 // begin
6333 // * No variant members' lifetimes begin
6334 // * All scalar subobjects whose lifetimes begin have indeterminate values
6335 assert(SubobjType->isUnionType());
6336 if (declaresSameEntity(Subobj.getUnionField(), Field)) {
6337 // This union member is already active. If it's also in-lifetime, there's
6338 // nothing to do.
6339 if (Subobj.getUnionValue().hasValue())
6340 return true;
6341 } else if (DuringInit) {
6342 // We're currently in the process of initializing a different union
6343 // member. If we carried on, that initialization would attempt to
6344 // store to an inactive union member, resulting in undefined behavior.
6345 Info.FFDiag(LHSExpr,
6346 diag::note_constexpr_union_member_change_during_init);
6347 return false;
6348 }
6349 APValue Result;
6350 Failed = !handleDefaultInitValue(Field->getType(), Result);
6351 Subobj.setUnion(Field, Result);
6352 return true;
6353 }
6354 bool found(APSInt &Value, QualType SubobjType) {
6355 llvm_unreachable("wrong value kind for union object");
6356 }
6357 bool found(APFloat &Value, QualType SubobjType) {
6358 llvm_unreachable("wrong value kind for union object");
6359 }
6360};
6361} // end anonymous namespace
6362
6363const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
6364
6365/// Handle a builtin simple-assignment or a call to a trivial assignment
6366/// operator whose left-hand side might involve a union member access. If it
6367/// does, implicitly start the lifetime of any accessed union elements per
6368/// C++20 [class.union]5.
6369static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info,
6370 const Expr *LHSExpr,
6371 const LValue &LHS) {
6372 if (LHS.InvalidBase || LHS.Designator.Invalid)
6373 return false;
6374
6376 // C++ [class.union]p5:
6377 // define the set S(E) of subexpressions of E as follows:
6378 unsigned PathLength = LHS.Designator.Entries.size();
6379 for (const Expr *E = LHSExpr; E != nullptr;) {
6380 // -- If E is of the form A.B, S(E) contains the elements of S(A)...
6381 if (auto *ME = dyn_cast<MemberExpr>(E)) {
6382 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6383 // Note that we can't implicitly start the lifetime of a reference,
6384 // so we don't need to proceed any further if we reach one.
6385 if (!FD || FD->getType()->isReferenceType())
6386 break;
6387
6388 // ... and also contains A.B if B names a union member ...
6389 if (FD->getParent()->isUnion()) {
6390 // ... of a non-class, non-array type, or of a class type with a
6391 // trivial default constructor that is not deleted, or an array of
6392 // such types.
6393 auto *RD =
6394 FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6395 if (!RD || RD->hasTrivialDefaultConstructor())
6396 UnionPathLengths.push_back({PathLength - 1, FD});
6397 }
6398
6399 E = ME->getBase();
6400 --PathLength;
6401 assert(declaresSameEntity(FD,
6402 LHS.Designator.Entries[PathLength]
6403 .getAsBaseOrMember().getPointer()));
6404
6405 // -- If E is of the form A[B] and is interpreted as a built-in array
6406 // subscripting operator, S(E) is [S(the array operand, if any)].
6407 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6408 // Step over an ArrayToPointerDecay implicit cast.
6409 auto *Base = ASE->getBase()->IgnoreImplicit();
6410 if (!Base->getType()->isArrayType())
6411 break;
6412
6413 E = Base;
6414 --PathLength;
6415
6416 } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6417 // Step over a derived-to-base conversion.
6418 E = ICE->getSubExpr();
6419 if (ICE->getCastKind() == CK_NoOp)
6420 continue;
6421 if (ICE->getCastKind() != CK_DerivedToBase &&
6422 ICE->getCastKind() != CK_UncheckedDerivedToBase)
6423 break;
6424 // Walk path backwards as we walk up from the base to the derived class.
6425 for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
6426 if (Elt->isVirtual()) {
6427 // A class with virtual base classes never has a trivial default
6428 // constructor, so S(E) is empty in this case.
6429 E = nullptr;
6430 break;
6431 }
6432
6433 --PathLength;
6434 assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
6435 LHS.Designator.Entries[PathLength]
6436 .getAsBaseOrMember().getPointer()));
6437 }
6438
6439 // -- Otherwise, S(E) is empty.
6440 } else {
6441 break;
6442 }
6443 }
6444
6445 // Common case: no unions' lifetimes are started.
6446 if (UnionPathLengths.empty())
6447 return true;
6448
6449 // if modification of X [would access an inactive union member], an object
6450 // of the type of X is implicitly created
6451 CompleteObject Obj =
6452 findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
6453 if (!Obj)
6454 return false;
6455 for (std::pair<unsigned, const FieldDecl *> LengthAndField :
6456 llvm::reverse(UnionPathLengths)) {
6457 // Form a designator for the union object.
6458 SubobjectDesignator D = LHS.Designator;
6459 D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
6460
6461 bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
6462 ConstructionPhase::AfterBases;
6463 StartLifetimeOfUnionMemberHandler StartLifetime{
6464 Info, LHSExpr, LengthAndField.second, DuringInit};
6465 if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
6466 return false;
6467 }
6468
6469 return true;
6470}
6471
6472static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
6473 CallRef Call, EvalInfo &Info,
6474 bool NonNull = false) {
6475 LValue LV;
6476 // Create the parameter slot and register its destruction. For a vararg
6477 // argument, create a temporary.
6478 // FIXME: For calling conventions that destroy parameters in the callee,
6479 // should we consider performing destruction when the function returns
6480 // instead?
6481 APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
6482 : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
6483 ScopeKind::Call, LV);
6484 if (!EvaluateInPlace(V, Info, LV, Arg))
6485 return false;
6486
6487 // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6488 // undefined behavior, so is non-constant.
6489 if (NonNull && V.isLValue() && V.isNullPointer()) {
6490 Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6491 return false;
6492 }
6493
6494 return true;
6495}
6496
6497/// Evaluate the arguments to a function call.
6498static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6499 EvalInfo &Info, const FunctionDecl *Callee,
6500 bool RightToLeft = false) {
6501 bool Success = true;
6502 llvm::SmallBitVector ForbiddenNullArgs;
6503 if (Callee->hasAttr<NonNullAttr>()) {
6504 ForbiddenNullArgs.resize(Args.size());
6505 for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6506 if (!Attr->args_size()) {
6507 ForbiddenNullArgs.set();
6508 break;
6509 } else
6510 for (auto Idx : Attr->args()) {
6511 unsigned ASTIdx = Idx.getASTIndex();
6512 if (ASTIdx >= Args.size())
6513 continue;
6514 ForbiddenNullArgs[ASTIdx] = true;
6515 }
6516 }
6517 }
6518 for (unsigned I = 0; I < Args.size(); I++) {
6519 unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6520 const ParmVarDecl *PVD =
6521 Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6522 bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6523 if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6524 // If we're checking for a potential constant expression, evaluate all
6525 // initializers even if some of them fail.
6526 if (!Info.noteFailure())
6527 return false;
6528 Success = false;
6529 }
6530 }
6531 return Success;
6532}
6533
6534/// Perform a trivial copy from Param, which is the parameter of a copy or move
6535/// constructor or assignment operator.
6536static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6537 const Expr *E, APValue &Result,
6538 bool CopyObjectRepresentation) {
6539 // Find the reference argument.
6540 CallStackFrame *Frame = Info.CurrentCall;
6541 APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6542 if (!RefValue) {
6543 Info.FFDiag(E);
6544 return false;
6545 }
6546
6547 // Copy out the contents of the RHS object.
6548 LValue RefLValue;
6549 RefLValue.setFrom(Info.Ctx, *RefValue);
6551 Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6552 CopyObjectRepresentation);
6553}
6554
6555/// Evaluate a function call.
6557 const FunctionDecl *Callee, const LValue *This,
6558 const Expr *E, ArrayRef<const Expr *> Args,
6559 CallRef Call, const Stmt *Body, EvalInfo &Info,
6560 APValue &Result, const LValue *ResultSlot) {
6561 if (!Info.CheckCallLimit(CallLoc))
6562 return false;
6563
6564 CallStackFrame Frame(Info, E->getSourceRange(), Callee, This, E, Call);
6565
6566 // For a trivial copy or move assignment, perform an APValue copy. This is
6567 // essential for unions, where the operations performed by the assignment
6568 // operator cannot be represented as statements.
6569 //
6570 // Skip this for non-union classes with no fields; in that case, the defaulted
6571 // copy/move does not actually read the object.
6572 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6573 if (MD && MD->isDefaulted() &&
6574 (MD->getParent()->isUnion() ||
6575 (MD->isTrivial() &&
6577 assert(This &&
6579 APValue RHSValue;
6580 if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6581 MD->getParent()->isUnion()))
6582 return false;
6583 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6584 RHSValue))
6585 return false;
6586 This->moveInto(Result);
6587 return true;
6588 } else if (MD && isLambdaCallOperator(MD)) {
6589 // We're in a lambda; determine the lambda capture field maps unless we're
6590 // just constexpr checking a lambda's call operator. constexpr checking is
6591 // done before the captures have been added to the closure object (unless
6592 // we're inferring constexpr-ness), so we don't have access to them in this
6593 // case. But since we don't need the captures to constexpr check, we can
6594 // just ignore them.
6595 if (!Info.checkingPotentialConstantExpression())
6596 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6597 Frame.LambdaThisCaptureField);
6598 }
6599
6600 StmtResult Ret = {Result, ResultSlot};
6601 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6602 if (ESR == ESR_Succeeded) {
6603 if (Callee->getReturnType()->isVoidType())
6604 return true;
6605 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6606 }
6607 return ESR == ESR_Returned;
6608}
6609
6610/// Evaluate a constructor call.
6611static bool HandleConstructorCall(const Expr *E, const LValue &This,
6612 CallRef Call,
6614 EvalInfo &Info, APValue &Result) {
6615 SourceLocation CallLoc = E->getExprLoc();
6616 if (!Info.CheckCallLimit(CallLoc))
6617 return false;
6618
6619 const CXXRecordDecl *RD = Definition->getParent();
6620 if (RD->getNumVBases()) {
6621 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6622 return false;
6623 }
6624
6625 EvalInfo::EvaluatingConstructorRAII EvalObj(
6626 Info,
6627 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6628 RD->getNumBases());
6629 CallStackFrame Frame(Info, E->getSourceRange(), Definition, &This, E, Call);
6630
6631 // FIXME: Creating an APValue just to hold a nonexistent return value is
6632 // wasteful.
6633 APValue RetVal;
6634 StmtResult Ret = {RetVal, nullptr};
6635
6636 // If it's a delegating constructor, delegate.
6637 if (Definition->isDelegatingConstructor()) {
6639 if ((*I)->getInit()->isValueDependent()) {
6640 if (!EvaluateDependentExpr((*I)->getInit(), Info))
6641 return false;
6642 } else {
6643 FullExpressionRAII InitScope(Info);
6644 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6645 !InitScope.destroy())
6646 return false;
6647 }
6648 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6649 }
6650
6651 // For a trivial copy or move constructor, perform an APValue copy. This is
6652 // essential for unions (or classes with anonymous union members), where the
6653 // operations performed by the constructor cannot be represented by
6654 // ctor-initializers.
6655 //
6656 // Skip this for empty non-union classes; we should not perform an
6657 // lvalue-to-rvalue conversion on them because their copy constructor does not
6658 // actually read them.
6659 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6660 (Definition->getParent()->isUnion() ||
6661 (Definition->isTrivial() &&
6663 return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6664 Definition->getParent()->isUnion());
6665 }
6666
6667 // Reserve space for the struct members.
6668 if (!Result.hasValue()) {
6669 if (!RD->isUnion())
6670 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6671 std::distance(RD->field_begin(), RD->field_end()));
6672 else
6673 // A union starts with no active member.
6674 Result = APValue((const FieldDecl*)nullptr);
6675 }
6676
6677 if (RD->isInvalidDecl()) return false;
6678 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6679
6680 // A scope for temporaries lifetime-extended by reference members.
6681 BlockScopeRAII LifetimeExtendedScope(Info);
6682
6683 bool Success = true;
6684 unsigned BasesSeen = 0;
6685#ifndef NDEBUG
6687#endif
6689 auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6690 // We might be initializing the same field again if this is an indirect
6691 // field initialization.
6692 if (FieldIt == RD->field_end() ||
6693 FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6694 assert(Indirect && "fields out of order?");
6695 return;
6696 }
6697
6698 // Default-initialize any fields with no explicit initializer.
6699 for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6700 assert(FieldIt != RD->field_end() && "missing field?");
6701 if (!FieldIt->isUnnamedBitField())
6703 FieldIt->getType(),
6704 Result.getStructField(FieldIt->getFieldIndex()));
6705 }
6706 ++FieldIt;
6707 };
6708 for (const auto *I : Definition->inits()) {
6709 LValue Subobject = This;
6710 LValue SubobjectParent = This;
6711 APValue *Value = &Result;
6712
6713 // Determine the subobject to initialize.
6714 FieldDecl *FD = nullptr;
6715 if (I->isBaseInitializer()) {
6716 QualType BaseType(I->getBaseClass(), 0);
6717#ifndef NDEBUG
6718 // Non-virtual base classes are initialized in the order in the class
6719 // definition. We have already checked for virtual base classes.
6720 assert(!BaseIt->isVirtual() && "virtual base for literal type");
6721 assert(Info.Ctx.hasSameUnqualifiedType(BaseIt->getType(), BaseType) &&
6722 "base class initializers not in expected order");
6723 ++BaseIt;
6724#endif
6725 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6726 BaseType->getAsCXXRecordDecl(), &Layout))
6727 return false;
6728 Value = &Result.getStructBase(BasesSeen++);
6729 } else if ((FD = I->getMember())) {
6730 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6731 return false;
6732 if (RD->isUnion()) {
6733 Result = APValue(FD);
6734 Value = &Result.getUnionValue();
6735 } else {
6736 SkipToField(FD, false);
6737 Value = &Result.getStructField(FD->getFieldIndex());
6738 }
6739 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6740 // Walk the indirect field decl's chain to find the object to initialize,
6741 // and make sure we've initialized every step along it.
6742 auto IndirectFieldChain = IFD->chain();
6743 for (auto *C : IndirectFieldChain) {
6744 FD = cast<FieldDecl>(C);
6745 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6746 // Switch the union field if it differs. This happens if we had
6747 // preceding zero-initialization, and we're now initializing a union
6748 // subobject other than the first.
6749 // FIXME: In this case, the values of the other subobjects are
6750 // specified, since zero-initialization sets all padding bits to zero.
6751 if (!Value->hasValue() ||
6752 (Value->isUnion() && Value->getUnionField() != FD)) {
6753 if (CD->isUnion())
6754 *Value = APValue(FD);
6755 else
6756 // FIXME: This immediately starts the lifetime of all members of
6757 // an anonymous struct. It would be preferable to strictly start
6758 // member lifetime in initialization order.
6759 Success &=
6760 handleDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6761 }
6762 // Store Subobject as its parent before updating it for the last element
6763 // in the chain.
6764 if (C == IndirectFieldChain.back())
6765 SubobjectParent = Subobject;
6766 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6767 return false;
6768 if (CD->isUnion())
6769 Value = &Value->getUnionValue();
6770 else {
6771 if (C == IndirectFieldChain.front() && !RD->isUnion())
6772 SkipToField(FD, true);
6773 Value = &Value->getStructField(FD->getFieldIndex());
6774 }
6775 }
6776 } else {
6777 llvm_unreachable("unknown base initializer kind");
6778 }
6779
6780 // Need to override This for implicit field initializers as in this case
6781 // This refers to innermost anonymous struct/union containing initializer,
6782 // not to currently constructed class.
6783 const Expr *Init = I->getInit();
6784 if (Init->isValueDependent()) {
6785 if (!EvaluateDependentExpr(Init, Info))
6786 return false;
6787 } else {
6788 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6789 isa<CXXDefaultInitExpr>(Init));
6790 FullExpressionRAII InitScope(Info);
6791 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6792 (FD && FD->isBitField() &&
6793 !truncateBitfieldValue(Info, Init, *Value, FD))) {
6794 // If we're checking for a potential constant expression, evaluate all
6795 // initializers even if some of them fail.
6796 if (!Info.noteFailure())
6797 return false;
6798 Success = false;
6799 }
6800 }
6801
6802 // This is the point at which the dynamic type of the object becomes this
6803 // class type.
6804 if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6805 EvalObj.finishedConstructingBases();
6806 }
6807
6808 // Default-initialize any remaining fields.
6809 if (!RD->isUnion()) {
6810 for (; FieldIt != RD->field_end(); ++FieldIt) {
6811 if (!FieldIt->isUnnamedBitField())
6813 FieldIt->getType(),
6814 Result.getStructField(FieldIt->getFieldIndex()));
6815 }
6816 }
6817
6818 EvalObj.finishedConstructingFields();
6819
6820 return Success &&
6821 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6822 LifetimeExtendedScope.destroy();
6823}
6824
6825static bool HandleConstructorCall(const Expr *E, const LValue &This,
6828 EvalInfo &Info, APValue &Result) {
6829 CallScopeRAII CallScope(Info);
6830 CallRef Call = Info.CurrentCall->createCall(Definition);
6831 if (!EvaluateArgs(Args, Call, Info, Definition))
6832 return false;
6833
6834 return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6835 CallScope.destroy();
6836}
6837
6838static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange,
6839 const LValue &This, APValue &Value,
6840 QualType T) {
6841 // Objects can only be destroyed while they're within their lifetimes.
6842 // FIXME: We have no representation for whether an object of type nullptr_t
6843 // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6844 // as indeterminate instead?
6845 if (Value.isAbsent() && !T->isNullPtrType()) {
6846 APValue Printable;
6847 This.moveInto(Printable);
6848 Info.FFDiag(CallRange.getBegin(),
6849 diag::note_constexpr_destroy_out_of_lifetime)
6850 << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6851 return false;
6852 }
6853
6854 // Invent an expression for location purposes.
6855 // FIXME: We shouldn't need to do this.
6856 OpaqueValueExpr LocE(CallRange.getBegin(), Info.Ctx.IntTy, VK_PRValue);
6857
6858 // For arrays, destroy elements right-to-left.
6859 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6860 uint64_t Size = CAT->getZExtSize();
6861 QualType ElemT = CAT->getElementType();
6862
6863 if (!CheckArraySize(Info, CAT, CallRange.getBegin()))
6864 return false;
6865
6866 LValue ElemLV = This;
6867 ElemLV.addArray(Info, &LocE, CAT);
6868 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6869 return false;
6870
6871 // Ensure that we have actual array elements available to destroy; the
6872 // destructors might mutate the value, so we can't run them on the array
6873 // filler.
6874 if (Size && Size > Value.getArrayInitializedElts())
6875 expandArray(Value, Value.getArraySize() - 1);
6876
6877 // The size of the array might have been reduced by
6878 // a placement new.
6879 for (Size = Value.getArraySize(); Size != 0; --Size) {
6880 APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6881 if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6882 !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
6883 return false;
6884 }
6885
6886 // End the lifetime of this array now.
6887 Value = APValue();
6888 return true;
6889 }
6890
6891 const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6892 if (!RD) {
6893 if (T.isDestructedType()) {
6894 Info.FFDiag(CallRange.getBegin(),
6895 diag::note_constexpr_unsupported_destruction)
6896 << T;
6897 return false;
6898 }
6899
6900 Value = APValue();
6901 return true;
6902 }
6903
6904 if (RD->getNumVBases()) {
6905 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_virtual_base) << RD;
6906 return false;
6907 }
6908
6909 const CXXDestructorDecl *DD = RD->getDestructor();
6910 if (!DD && !RD->hasTrivialDestructor()) {
6911 Info.FFDiag(CallRange.getBegin());
6912 return false;
6913 }
6914
6915 if (!DD || DD->isTrivial() ||
6916 (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6917 // A trivial destructor just ends the lifetime of the object. Check for
6918 // this case before checking for a body, because we might not bother
6919 // building a body for a trivial destructor. Note that it doesn't matter
6920 // whether the destructor is constexpr in this case; all trivial
6921 // destructors are constexpr.
6922 //
6923 // If an anonymous union would be destroyed, some enclosing destructor must
6924 // have been explicitly defined, and the anonymous union destruction should
6925 // have no effect.
6926 Value = APValue();
6927 return true;
6928 }
6929
6930 if (!Info.CheckCallLimit(CallRange.getBegin()))
6931 return false;
6932
6933 const FunctionDecl *Definition = nullptr;
6934 const Stmt *Body = DD->getBody(Definition);
6935
6936 if (!CheckConstexprFunction(Info, CallRange.getBegin(), DD, Definition, Body))
6937 return false;
6938
6939 CallStackFrame Frame(Info, CallRange, Definition, &This, /*CallExpr=*/nullptr,
6940 CallRef());
6941
6942 // We're now in the period of destruction of this object.
6943 unsigned BasesLeft = RD->getNumBases();
6944 EvalInfo::EvaluatingDestructorRAII EvalObj(
6945 Info,
6946 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6947 if (!EvalObj.DidInsert) {
6948 // C++2a [class.dtor]p19:
6949 // the behavior is undefined if the destructor is invoked for an object
6950 // whose lifetime has ended
6951 // (Note that formally the lifetime ends when the period of destruction
6952 // begins, even though certain uses of the object remain valid until the
6953 // period of destruction ends.)
6954 Info.FFDiag(CallRange.getBegin(), diag::note_constexpr_double_destroy);
6955 return false;
6956 }
6957
6958 // FIXME: Creating an APValue just to hold a nonexistent return value is
6959 // wasteful.
6960 APValue RetVal;
6961 StmtResult Ret = {RetVal, nullptr};
6962 if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6963 return false;
6964
6965 // A union destructor does not implicitly destroy its members.
6966 if (RD->isUnion())
6967 return true;
6968
6969 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6970
6971 // We don't have a good way to iterate fields in reverse, so collect all the
6972 // fields first and then walk them backwards.
6973 SmallVector<FieldDecl*, 16> Fields(RD->fields());
6974 for (const FieldDecl *FD : llvm::reverse(Fields)) {
6975 if (FD->isUnnamedBitField())
6976 continue;
6977
6978 LValue Subobject = This;
6979 if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6980 return false;
6981
6982 APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6983 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
6984 FD->getType()))
6985 return false;
6986 }
6987
6988 if (BasesLeft != 0)
6989 EvalObj.startedDestroyingBases();
6990
6991 // Destroy base classes in reverse order.
6992 for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6993 --BasesLeft;
6994
6995 QualType BaseType = Base.getType();
6996 LValue Subobject = This;
6997 if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6998 BaseType->getAsCXXRecordDecl(), &Layout))
6999 return false;
7000
7001 APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
7002 if (!HandleDestructionImpl(Info, CallRange, Subobject, *SubobjectValue,
7003 BaseType))
7004 return false;
7005 }
7006 assert(BasesLeft == 0 && "NumBases was wrong?");
7007
7008 // The period of destruction ends now. The object is gone.
7009 Value = APValue();
7010 return true;
7011}
7012
7013namespace {
7014struct DestroyObjectHandler {
7015 EvalInfo &Info;
7016 const Expr *E;
7017 const LValue &This;
7018 const AccessKinds AccessKind;
7019
7020 typedef bool result_type;
7021 bool failed() { return false; }
7022 bool found(APValue &Subobj, QualType SubobjType) {
7023 return HandleDestructionImpl(Info, E->getSourceRange(), This, Subobj,
7024 SubobjType);
7025 }
7026 bool found(APSInt &Value, QualType SubobjType) {
7027 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7028 return false;
7029 }
7030 bool found(APFloat &Value, QualType SubobjType) {
7031 Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
7032 return false;
7033 }
7034};
7035}
7036
7037/// Perform a destructor or pseudo-destructor call on the given object, which
7038/// might in general not be a complete object.
7039static bool HandleDestruction(EvalInfo &Info, const Expr *E,
7040 const LValue &This, QualType ThisType) {
7041 CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
7042 DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
7043 return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
7044}
7045
7046/// Destroy and end the lifetime of the given complete object.
7047static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
7049 QualType T) {
7050 // If we've had an unmodeled side-effect, we can't rely on mutable state
7051 // (such as the object we're about to destroy) being correct.
7052 if (Info.EvalStatus.HasSideEffects)
7053 return false;
7054
7055 LValue LV;
7056 LV.set({LVBase});
7057 return HandleDestructionImpl(Info, Loc, LV, Value, T);
7058}
7059
7060/// Perform a call to 'operator new' or to `__builtin_operator_new'.
7061static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
7062 LValue &Result) {
7063 if (Info.checkingPotentialConstantExpression() ||
7064 Info.SpeculativeEvaluationDepth)
7065 return false;
7066
7067 // This is permitted only within a call to std::allocator<T>::allocate.
7068 auto Caller = Info.getStdAllocatorCaller("allocate");
7069 if (!Caller) {
7070 Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
7071 ? diag::note_constexpr_new_untyped
7072 : diag::note_constexpr_new);
7073 return false;
7074 }
7075
7076 QualType ElemType = Caller.ElemType;
7077 if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
7078 Info.FFDiag(E->getExprLoc(),
7079 diag::note_constexpr_new_not_complete_object_type)
7080 << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
7081 return false;
7082 }
7083
7084 APSInt ByteSize;
7085 if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
7086 return false;
7087 bool IsNothrow = false;
7088 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
7089 EvaluateIgnoredValue(Info, E->getArg(I));
7090 IsNothrow |= E->getType()->isNothrowT();
7091 }
7092
7093 CharUnits ElemSize;
7094 if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
7095 return false;
7096 APInt Size, Remainder;
7097 APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
7098 APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
7099 if (Remainder != 0) {
7100 // This likely indicates a bug in the implementation of 'std::allocator'.
7101 Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
7102 << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
7103 return false;
7104 }
7105
7106 if (!Info.CheckArraySize(E->getBeginLoc(), ByteSize.getActiveBits(),
7107 Size.getZExtValue(), /*Diag=*/!IsNothrow)) {
7108 if (IsNothrow) {
7109 Result.setNull(Info.Ctx, E->getType());
7110 return true;
7111 }
7112 return false;
7113 }
7114
7115 QualType AllocType = Info.Ctx.getConstantArrayType(
7116 ElemType, Size, nullptr, ArraySizeModifier::Normal, 0);
7117 APValue *Val = Info.createHeapAlloc(Caller.Call, AllocType, Result);
7118 *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
7119 Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
7120 return true;
7121}
7122
7124 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7125 if (CXXDestructorDecl *DD = RD->getDestructor())
7126 return DD->isVirtual();
7127 return false;
7128}
7129
7131 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
7132 if (CXXDestructorDecl *DD = RD->getDestructor())
7133 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
7134 return nullptr;
7135}
7136
7137/// Check that the given object is a suitable pointer to a heap allocation that
7138/// still exists and is of the right kind for the purpose of a deletion.
7139///
7140/// On success, returns the heap allocation to deallocate. On failure, produces
7141/// a diagnostic and returns std::nullopt.
7142static std::optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
7143 const LValue &Pointer,
7144 DynAlloc::Kind DeallocKind) {
7145 auto PointerAsString = [&] {
7146 return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
7147 };
7148
7149 DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
7150 if (!DA) {
7151 Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
7152 << PointerAsString();
7153 if (Pointer.Base)
7154 NoteLValueLocation(Info, Pointer.Base);
7155 return std::nullopt;
7156 }
7157
7158 std::optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
7159 if (!Alloc) {
7160 Info.FFDiag(E, diag::note_constexpr_double_delete);
7161 return std::nullopt;
7162 }
7163
7164 if (DeallocKind != (*Alloc)->getKind()) {
7165 QualType AllocType = Pointer.Base.getDynamicAllocType();
7166 Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
7167 << DeallocKind << (*Alloc)->getKind() << AllocType;
7168 NoteLValueLocation(Info, Pointer.Base);
7169 return std::nullopt;
7170 }
7171
7172 bool Subobject = false;
7173 if (DeallocKind == DynAlloc::New) {
7174 Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
7175 Pointer.Designator.isOnePastTheEnd();
7176 } else {
7177 Subobject = Pointer.Designator.Entries.size() != 1 ||
7178 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
7179 }
7180 if (Subobject) {
7181 Info.FFDiag(E, diag::note_constexpr_delete_subobject)
7182 << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
7183 return std::nullopt;
7184 }
7185
7186 return Alloc;
7187}
7188
7189// Perform a call to 'operator delete' or '__builtin_operator_delete'.
7190static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
7191 if (Info.checkingPotentialConstantExpression() ||
7192 Info.SpeculativeEvaluationDepth)
7193 return false;
7194
7195 // This is permitted only within a call to std::allocator<T>::deallocate.
7196 if (!Info.getStdAllocatorCaller("deallocate")) {
7197 Info.FFDiag(E->getExprLoc());
7198 return true;
7199 }
7200
7201 LValue Pointer;
7202 if (!EvaluatePointer(E->getArg(0), Pointer, Info))
7203 return false;
7204 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
7205 EvaluateIgnoredValue(Info, E->getArg(I));
7206
7207 if (Pointer.Designator.Invalid)
7208 return false;
7209
7210 // Deleting a null pointer would have no effect, but it's not permitted by
7211 // std::allocator<T>::deallocate's contract.
7212 if (Pointer.isNullPointer()) {
7213 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
7214 return true;
7215 }
7216
7217 if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
7218 return false;
7219
7220 Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
7221 return true;
7222}
7223
7224//===----------------------------------------------------------------------===//
7225// Generic Evaluation
7226//===----------------------------------------------------------------------===//
7227namespace {
7228
7229class BitCastBuffer {
7230 // FIXME: We're going to need bit-level granularity when we support
7231 // bit-fields.
7232 // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
7233 // we don't support a host or target where that is the case. Still, we should
7234 // use a more generic type in case we ever do.
7236
7237 static_assert(std::numeric_limits<unsigned char>::digits >= 8,
7238 "Need at least 8 bit unsigned char");
7239
7240 bool TargetIsLittleEndian;
7241
7242public:
7243 BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
7244 : Bytes(Width.getQuantity()),
7245 TargetIsLittleEndian(TargetIsLittleEndian) {}
7246
7247 [[nodiscard]] bool readObject(CharUnits Offset, CharUnits Width,
7248 SmallVectorImpl<unsigned char> &Output) const {
7249 for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
7250 // If a byte of an integer is uninitialized, then the whole integer is
7251 // uninitialized.
7252 if (!Bytes[I.getQuantity()])
7253 return false;
7254 Output.push_back(*Bytes[I.getQuantity()]);
7255 }
7256 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7257 std::reverse(Output.begin(), Output.end());
7258 return true;
7259 }
7260
7261 void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
7262 if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
7263 std::reverse(Input.begin(), Input.end());
7264
7265 size_t Index = 0;
7266 for (unsigned char Byte : Input) {
7267 assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
7268 Bytes[Offset.getQuantity() + Index] = Byte;
7269 ++Index;
7270 }
7271 }
7272
7273 size_t size() { return Bytes.size(); }
7274};
7275
7276/// Traverse an APValue to produce an BitCastBuffer, emulating how the current
7277/// target would represent the value at runtime.
7278class APValueToBufferConverter {
7279 EvalInfo &Info;
7280 BitCastBuffer Buffer;
7281 const CastExpr *BCE;
7282
7283 APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
7284 const CastExpr *BCE)
7285 : Info(Info),
7286 Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
7287 BCE(BCE) {}
7288
7289 bool visit(const APValue &Val, QualType Ty) {
7290 return visit(Val, Ty, CharUnits::fromQuantity(0));
7291 }
7292
7293 // Write out Val with type Ty into Buffer starting at Offset.
7294 bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
7295 assert((size_t)Offset.getQuantity() <= Buffer.size());
7296
7297 // As a special case, nullptr_t has an indeterminate value.
7298 if (Ty->isNullPtrType())
7299 return true;
7300
7301 // Dig through Src to find the byte at SrcOffset.
7302 switch (Val.getKind()) {
7304 case APValue::None:
7305 return true;
7306
7307 case APValue::Int:
7308 return visitInt(Val.getInt(), Ty, Offset);
7309 case APValue::Float:
7310 return visitFloat(Val.getFloat(), Ty, Offset);
7311 case APValue::Array:
7312 return visitArray(Val, Ty, Offset);
7313 case APValue::Struct:
7314 return visitRecord(Val, Ty, Offset);
7315 case APValue::Vector:
7316 return visitVector(Val, Ty, Offset);
7317
7320 return visitComplex(Val, Ty, Offset);
7322 // FIXME: We should support these.
7323
7324 case APValue::Union:
7327 Info.FFDiag(BCE->getBeginLoc(),
7328 diag::note_constexpr_bit_cast_unsupported_type)
7329 << Ty;
7330 return false;
7331 }
7332
7333 case APValue::LValue:
7334 llvm_unreachable("LValue subobject in bit_cast?");
7335 }
7336 llvm_unreachable("Unhandled APValue::ValueKind");
7337 }
7338
7339 bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
7340 const RecordDecl *RD = Ty->getAsRecordDecl();
7341 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7342
7343 // Visit the base classes.
7344 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7345 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7346 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7347 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7348
7349 if (!visitRecord(Val.getStructBase(I), BS.getType(),
7350 Layout.getBaseClassOffset(BaseDecl) + Offset))
7351 return false;
7352 }
7353 }
7354
7355 // Visit the fields.
7356 unsigned FieldIdx = 0;
7357 for (FieldDecl *FD : RD->fields()) {
7358 if (FD->isBitField()) {
7359 Info.FFDiag(BCE->getBeginLoc(),
7360 diag::note_constexpr_bit_cast_unsupported_bitfield);
7361 return false;
7362 }
7363
7364 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7365
7366 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
7367 "only bit-fields can have sub-char alignment");
7368 CharUnits FieldOffset =
7369 Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
7370 QualType FieldTy = FD->getType();
7371 if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
7372 return false;
7373 ++FieldIdx;
7374 }
7375
7376 return true;
7377 }
7378
7379 bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
7380 const auto *CAT =
7381 dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
7382 if (!CAT)
7383 return false;
7384
7385 CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
7386 unsigned NumInitializedElts = Val.getArrayInitializedElts();
7387 unsigned ArraySize = Val.getArraySize();
7388 // First, initialize the initialized elements.
7389 for (unsigned I = 0; I != NumInitializedElts; ++I) {
7390 const APValue &SubObj = Val.getArrayInitializedElt(I);
7391 if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
7392 return false;
7393 }
7394
7395 // Next, initialize the rest of the array using the filler.
7396 if (Val.hasArrayFiller()) {
7397 const APValue &Filler = Val.getArrayFiller();
7398 for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
7399 if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
7400 return false;
7401 }
7402 }
7403
7404 return true;
7405 }
7406
7407 bool visitComplex(const APValue &Val, QualType Ty, CharUnits Offset) {
7408 const ComplexType *ComplexTy = Ty->castAs<ComplexType>();
7409 QualType EltTy = ComplexTy->getElementType();
7410 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7411 bool IsInt = Val.isComplexInt();
7412
7413 if (IsInt) {
7414 if (!visitInt(Val.getComplexIntReal(), EltTy,
7415 Offset + (0 * EltSizeChars)))
7416 return false;
7417 if (!visitInt(Val.getComplexIntImag(), EltTy,
7418 Offset + (1 * EltSizeChars)))
7419 return false;
7420 } else {
7421 if (!visitFloat(Val.getComplexFloatReal(), EltTy,
7422 Offset + (0 * EltSizeChars)))
7423 return false;
7424 if (!visitFloat(Val.getComplexFloatImag(), EltTy,
7425 Offset + (1 * EltSizeChars)))
7426 return false;
7427 }
7428
7429 return true;
7430 }
7431
7432 bool visitVector(const APValue &Val, QualType Ty, CharUnits Offset) {
7433 const VectorType *VTy = Ty->castAs<VectorType>();
7434 QualType EltTy = VTy->getElementType();
7435 unsigned NElts = VTy->getNumElements();
7436
7437 if (VTy->isExtVectorBoolType()) {
7438 // Special handling for OpenCL bool vectors:
7439 // Since these vectors are stored as packed bits, but we can't write
7440 // individual bits to the BitCastBuffer, we'll buffer all of the elements
7441 // together into an appropriately sized APInt and write them all out at
7442 // once. Because we don't accept vectors where NElts * EltSize isn't a
7443 // multiple of the char size, there will be no padding space, so we don't
7444 // have to worry about writing data which should have been left
7445 // uninitialized.
7446 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7447
7448 llvm::APInt Res = llvm::APInt::getZero(NElts);
7449 for (unsigned I = 0; I < NElts; ++I) {
7450 const llvm::APSInt &EltAsInt = Val.getVectorElt(I).getInt();
7451 assert(EltAsInt.isUnsigned() && EltAsInt.getBitWidth() == 1 &&
7452 "bool vector element must be 1-bit unsigned integer!");
7453
7454 Res.insertBits(EltAsInt, BigEndian ? (NElts - I - 1) : I);
7455 }
7456
7457 SmallVector<uint8_t, 8> Bytes(NElts / 8);
7458 llvm::StoreIntToMemory(Res, &*Bytes.begin(), NElts / 8);
7459 Buffer.writeObject(Offset, Bytes);
7460 } else {
7461 // Iterate over each of the elements and write them out to the buffer at
7462 // the appropriate offset.
7463 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7464 for (unsigned I = 0; I < NElts; ++I) {
7465 if (!visit(Val.getVectorElt(I), EltTy, Offset + I * EltSizeChars))
7466 return false;
7467 }
7468 }
7469
7470 return true;
7471 }
7472
7473 bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
7474 APSInt AdjustedVal = Val;
7475 unsigned Width = AdjustedVal.getBitWidth();
7476 if (Ty->isBooleanType()) {
7477 Width = Info.Ctx.getTypeSize(Ty);
7478 AdjustedVal = AdjustedVal.extend(Width);
7479 }
7480
7481 SmallVector<uint8_t, 8> Bytes(Width / 8);
7482 llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
7483 Buffer.writeObject(Offset, Bytes);
7484 return true;
7485 }
7486
7487 bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
7488 APSInt AsInt(Val.bitcastToAPInt());
7489 return visitInt(AsInt, Ty, Offset);
7490 }
7491
7492public:
7493 static std::optional<BitCastBuffer>
7494 convert(EvalInfo &Info, const APValue &Src, const CastExpr *BCE) {
7495 CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
7496 APValueToBufferConverter Converter(Info, DstSize, BCE);
7497 if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
7498 return std::nullopt;
7499 return Converter.Buffer;
7500 }
7501};
7502
7503/// Write an BitCastBuffer into an APValue.
7504class BufferToAPValueConverter {
7505 EvalInfo &Info;
7506 const BitCastBuffer &Buffer;
7507 const CastExpr *BCE;
7508
7509 BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
7510 const CastExpr *BCE)
7511 : Info(Info), Buffer(Buffer), BCE(BCE) {}
7512
7513 // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
7514 // with an invalid type, so anything left is a deficiency on our part (FIXME).
7515 // Ideally this will be unreachable.
7516 std::nullopt_t unsupportedType(QualType Ty) {
7517 Info.FFDiag(BCE->getBeginLoc(),
7518 diag::note_constexpr_bit_cast_unsupported_type)
7519 << Ty;
7520 return std::nullopt;
7521 }
7522
7523 std::nullopt_t unrepresentableValue(QualType Ty, const APSInt &Val) {
7524 Info.FFDiag(BCE->getBeginLoc(),
7525 diag::note_constexpr_bit_cast_unrepresentable_value)
7526 << Ty << toString(Val, /*Radix=*/10);
7527 return std::nullopt;
7528 }
7529
7530 std::optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
7531 const EnumType *EnumSugar = nullptr) {
7532 if (T->isNullPtrType()) {
7533 uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
7534 return APValue((Expr *)nullptr,
7535 /*Offset=*/CharUnits::fromQuantity(NullValue),
7536 APValue::NoLValuePath{}, /*IsNullPtr=*/true);
7537 }
7538
7539 CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
7540
7541 // Work around floating point types that contain unused padding bytes. This
7542 // is really just `long double` on x86, which is the only fundamental type
7543 // with padding bytes.
7544 if (T->isRealFloatingType()) {
7545 const llvm::fltSemantics &Semantics =
7546 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7547 unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
7548 assert(NumBits % 8 == 0);
7549 CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
7550 if (NumBytes != SizeOf)
7551 SizeOf = NumBytes;
7552 }
7553
7555 if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
7556 // If this is std::byte or unsigned char, then its okay to store an
7557 // indeterminate value.
7558 bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7559 bool IsUChar =
7560 !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7561 T->isSpecificBuiltinType(BuiltinType::Char_U));
7562 if (!IsStdByte && !IsUChar) {
7563 QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7564 Info.FFDiag(BCE->getExprLoc(),
7565 diag::note_constexpr_bit_cast_indet_dest)
7566 << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7567 return std::nullopt;
7568 }
7569
7571 }
7572
7573 APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7574 llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7575
7577 Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7578
7579 unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7580 if (IntWidth != Val.getBitWidth()) {
7581 APSInt Truncated = Val.trunc(IntWidth);
7582 if (Truncated.extend(Val.getBitWidth()) != Val)
7583 return unrepresentableValue(QualType(T, 0), Val);
7584 Val = Truncated;
7585 }
7586
7587 return APValue(Val);
7588 }
7589
7590 if (T->isRealFloatingType()) {
7591 const llvm::fltSemantics &Semantics =
7592 Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7593 return APValue(APFloat(Semantics, Val));
7594 }
7595
7596 return unsupportedType(QualType(T, 0));
7597 }
7598
7599 std::optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7600 const RecordDecl *RD = RTy->getAsRecordDecl();
7601 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7602
7603 unsigned NumBases = 0;
7604 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7605 NumBases = CXXRD->getNumBases();
7606
7607 APValue ResultVal(APValue::UninitStruct(), NumBases,
7608 std::distance(RD->field_begin(), RD->field_end()));
7609
7610 // Visit the base classes.
7611 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7612 for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7613 const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7614 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7615
7616 std::optional<APValue> SubObj = visitType(
7617 BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7618 if (!SubObj)
7619 return std::nullopt;
7620 ResultVal.getStructBase(I) = *SubObj;
7621 }
7622 }
7623
7624 // Visit the fields.
7625 unsigned FieldIdx = 0;
7626 for (FieldDecl *FD : RD->fields()) {
7627 // FIXME: We don't currently support bit-fields. A lot of the logic for
7628 // this is in CodeGen, so we need to factor it around.
7629 if (FD->isBitField()) {
7630 Info.FFDiag(BCE->getBeginLoc(),
7631 diag::note_constexpr_bit_cast_unsupported_bitfield);
7632 return std::nullopt;
7633 }
7634
7635 uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7636 assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7637
7638 CharUnits FieldOffset =
7639 CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7640 Offset;
7641 QualType FieldTy = FD->getType();
7642 std::optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7643 if (!SubObj)
7644 return std::nullopt;
7645 ResultVal.getStructField(FieldIdx) = *SubObj;
7646 ++FieldIdx;
7647 }
7648
7649 return ResultVal;
7650 }
7651
7652 std::optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7653 QualType RepresentationType = Ty->getDecl()->getIntegerType();
7654 assert(!RepresentationType.isNull() &&
7655 "enum forward decl should be caught by Sema");
7656 const auto *AsBuiltin =
7657 RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7658 // Recurse into the underlying type. Treat std::byte transparently as
7659 // unsigned char.
7660 return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7661 }
7662
7663 std::optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7664 size_t Size = Ty->getLimitedSize();
7665 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7666
7667 APValue ArrayValue(APValue::UninitArray(), Size, Size);
7668 for (size_t I = 0; I != Size; ++I) {
7669 std::optional<APValue> ElementValue =
7670 visitType(Ty->getElementType(), Offset + I * ElementWidth);
7671 if (!ElementValue)
7672 return std::nullopt;
7673 ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7674 }
7675
7676 return ArrayValue;
7677 }
7678
7679 std::optional<APValue> visit(const ComplexType *Ty, CharUnits Offset) {
7680 QualType ElementType = Ty->getElementType();
7681 CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(ElementType);
7682 bool IsInt = ElementType->isIntegerType();
7683
7684 std::optional<APValue> Values[2];
7685 for (unsigned I = 0; I != 2; ++I) {
7686 Values[I] = visitType(Ty->getElementType(), Offset + I * ElementWidth);
7687 if (!Values[I])
7688 return std::nullopt;
7689 }
7690
7691 if (IsInt)
7692 return APValue(Values[0]->getInt(), Values[1]->getInt());
7693 return APValue(Values[0]->getFloat(), Values[1]->getFloat());
7694 }
7695
7696 std::optional<APValue> visit(const VectorType *VTy, CharUnits Offset) {
7697 QualType EltTy = VTy->getElementType();
7698 unsigned NElts = VTy->getNumElements();
7699 unsigned EltSize =
7700 VTy->isExtVectorBoolType() ? 1 : Info.Ctx.getTypeSize(EltTy);
7701
7703 Elts.reserve(NElts);
7704 if (VTy->isExtVectorBoolType()) {
7705 // Special handling for OpenCL bool vectors:
7706 // Since these vectors are stored as packed bits, but we can't read
7707 // individual bits from the BitCastBuffer, we'll buffer all of the
7708 // elements together into an appropriately sized APInt and write them all
7709 // out at once. Because we don't accept vectors where NElts * EltSize
7710 // isn't a multiple of the char size, there will be no padding space, so
7711 // we don't have to worry about reading any padding data which didn't
7712 // actually need to be accessed.
7713 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7714
7716 Bytes.reserve(NElts / 8);
7717 if (!Buffer.readObject(Offset, CharUnits::fromQuantity(NElts / 8), Bytes))
7718 return std::nullopt;
7719
7720 APSInt SValInt(NElts, true);
7721 llvm::LoadIntFromMemory(SValInt, &*Bytes.begin(), Bytes.size());
7722
7723 for (unsigned I = 0; I < NElts; ++I) {
7724 llvm::APInt Elt =
7725 SValInt.extractBits(1, (BigEndian ? NElts - I - 1 : I) * EltSize);
7726 Elts.emplace_back(
7727 APSInt(std::move(Elt), !EltTy->isSignedIntegerType()));
7728 }
7729 } else {
7730 // Iterate over each of the elements and read them from the buffer at
7731 // the appropriate offset.
7732 CharUnits EltSizeChars = Info.Ctx.getTypeSizeInChars(EltTy);
7733 for (unsigned I = 0; I < NElts; ++I) {
7734 std::optional<APValue> EltValue =
7735 visitType(EltTy, Offset + I * EltSizeChars);
7736 if (!EltValue)
7737 return std::nullopt;
7738 Elts.push_back(std::move(*EltValue));
7739 }
7740 }
7741
7742 return APValue(Elts.data(), Elts.size());
7743 }
7744
7745 std::optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7746 return unsupportedType(QualType(Ty, 0));
7747 }
7748
7749 std::optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7750 QualType Can = Ty.getCanonicalType();
7751
7752 switch (Can->getTypeClass()) {
7753#define TYPE(Class, Base) \
7754 case Type::Class: \
7755 return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7756#define ABSTRACT_TYPE(Class, Base)
7757#define NON_CANONICAL_TYPE(Class, Base) \
7758 case Type::Class: \
7759 llvm_unreachable("non-canonical type should be impossible!");
7760#define DEPENDENT_TYPE(Class, Base) \
7761 case Type::Class: \
7762 llvm_unreachable( \
7763 "dependent types aren't supported in the constant evaluator!");
7764#define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base) \
7765 case Type::Class: \
7766 llvm_unreachable("either dependent or not canonical!");
7767#include "clang/AST/TypeNodes.inc"
7768 }
7769 llvm_unreachable("Unhandled Type::TypeClass");
7770 }
7771
7772public:
7773 // Pull out a full value of type DstType.
7774 static std::optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7775 const CastExpr *BCE) {
7776 BufferToAPValueConverter Converter(Info, Buffer, BCE);
7777 return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7778 }
7779};
7780
7781static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7782 QualType Ty, EvalInfo *Info,
7783 const ASTContext &Ctx,
7784 bool CheckingDest) {
7785 Ty = Ty.getCanonicalType();
7786
7787 auto diag = [&](int Reason) {
7788 if (Info)
7789 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7790 << CheckingDest << (Reason == 4) << Reason;
7791 return false;
7792 };
7793 auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7794 if (Info)
7795 Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7796 << NoteTy << Construct << Ty;
7797 return false;
7798 };
7799
7800 if (Ty->isUnionType())
7801 return diag(0);
7802 if (Ty->isPointerType())
7803 return diag(1);
7804 if (Ty->isMemberPointerType())
7805 return diag(2);
7806 if (Ty.isVolatileQualified())
7807 return diag(3);
7808
7809 if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7810 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7811 for (CXXBaseSpecifier &BS : CXXRD->bases())
7812 if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7813 CheckingDest))
7814 return note(1, BS.getType(), BS.getBeginLoc());
7815 }
7816 for (FieldDecl *FD : Record->fields()) {
7817 if (FD->getType()->isReferenceType())
7818 return diag(4);
7819 if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7820 CheckingDest))
7821 return note(0, FD->getType(), FD->getBeginLoc());
7822 }
7823 }
7824
7825 if (Ty->isArrayType() &&
7826 !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7827 Info, Ctx, CheckingDest))
7828 return false;
7829
7830 if (const auto *VTy = Ty->getAs<VectorType>()) {
7831 QualType EltTy = VTy->getElementType();
7832 unsigned NElts = VTy->getNumElements();
7833 unsigned EltSize = VTy->isExtVectorBoolType() ? 1 : Ctx.getTypeSize(EltTy);
7834
7835 if ((NElts * EltSize) % Ctx.getCharWidth() != 0) {
7836 // The vector's size in bits is not a multiple of the target's byte size,
7837 // so its layout is unspecified. For now, we'll simply treat these cases
7838 // as unsupported (this should only be possible with OpenCL bool vectors
7839 // whose element count isn't a multiple of the byte size).
7840 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_vector)
7841 << QualType(VTy, 0) << EltSize << NElts << Ctx.getCharWidth();
7842 return false;
7843 }
7844
7845 if (EltTy->isRealFloatingType() &&
7846 &Ctx.getFloatTypeSemantics(EltTy) == &APFloat::x87DoubleExtended()) {
7847 // The layout for x86_fp80 vectors seems to be handled very inconsistently
7848 // by both clang and LLVM, so for now we won't allow bit_casts involving
7849 // it in a constexpr context.
7850 Info->FFDiag(Loc, diag::note_constexpr_bit_cast_unsupported_type)
7851 << EltTy;
7852 return false;
7853 }
7854 }
7855
7856 return true;
7857}
7858
7859static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7860 const ASTContext &Ctx,
7861 const CastExpr *BCE) {
7862 bool DestOK = checkBitCastConstexprEligibilityType(
7863 BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7864 bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7865 BCE->getBeginLoc(),
7866 BCE->getSubExpr()->getType(), Info, Ctx, false);
7867 return SourceOK;
7868}
7869
7870static bool handleRValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7871 const APValue &SourceRValue,
7872 const CastExpr *BCE) {
7873 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7874 "no host or target supports non 8-bit chars");
7875
7876 if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7877 return false;
7878
7879 // Read out SourceValue into a char buffer.
7880 std::optional<BitCastBuffer> Buffer =
7881 APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7882 if (!Buffer)
7883 return false;
7884
7885 // Write out the buffer into a new APValue.
7886 std::optional<APValue> MaybeDestValue =
7887 BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7888 if (!MaybeDestValue)
7889 return false;
7890
7891 DestValue = std::move(*MaybeDestValue);
7892 return true;
7893}
7894
7895static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7896 APValue &SourceValue,
7897 const CastExpr *BCE) {
7898 assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7899 "no host or target supports non 8-bit chars");
7900 assert(SourceValue.isLValue() &&
7901 "LValueToRValueBitcast requires an lvalue operand!");
7902
7903 LValue SourceLValue;
7904 APValue SourceRValue;
7905 SourceLValue.setFrom(Info.Ctx, SourceValue);
7907 Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7908 SourceRValue, /*WantObjectRepresentation=*/true))
7909 return false;
7910
7911 return handleRValueToRValueBitCast(Info, DestValue, SourceRValue, BCE);
7912}
7913
7914template <class Derived>
7915class ExprEvaluatorBase
7916 : public ConstStmtVisitor<Derived, bool> {
7917private:
7918 Derived &getDerived() { return static_cast<Derived&>(*this); }
7919 bool DerivedSuccess(const APValue &V, const Expr *E) {
7920 return getDerived().Success(V, E);
7921 }
7922 bool DerivedZeroInitialization(const Expr *E) {
7923 return getDerived().ZeroInitialization(E);
7924 }
7925
7926 // Check whether a conditional operator with a non-constant condition is a
7927 // potential constant expression. If neither arm is a potential constant
7928 // expression, then the conditional operator is not either.
7929 template<typename ConditionalOperator>
7930 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7931 assert(Info.checkingPotentialConstantExpression());
7932
7933 // Speculatively evaluate both arms.
7935 {
7936 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7937 StmtVisitorTy::Visit(E->getFalseExpr());
7938 if (Diag.empty())
7939 return;
7940 }
7941
7942 {
7943 SpeculativeEvaluationRAII Speculate(Info, &Diag);
7944 Diag.clear();
7945 StmtVisitorTy::Visit(E->getTrueExpr());
7946 if (Diag.empty())
7947 return;
7948 }
7949
7950 Error(E, diag::note_constexpr_conditional_never_const);
7951 }
7952
7953
7954 template<typename ConditionalOperator>
7955 bool HandleConditionalOperator(const ConditionalOperator *E) {
7956 bool BoolResult;
7957 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7958 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7959 CheckPotentialConstantConditional(E);
7960 return false;
7961 }
7962 if (Info.noteFailure()) {
7963 StmtVisitorTy::Visit(E->getTrueExpr());
7964 StmtVisitorTy::Visit(E->getFalseExpr());
7965 }
7966 return false;
7967 }
7968
7969 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7970 return StmtVisitorTy::Visit(EvalExpr);
7971 }
7972
7973protected:
7974 EvalInfo &Info;
7975 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7976 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7977
7978 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7979 return Info.CCEDiag(E, D);
7980 }
7981
7982 bool ZeroInitialization(const Expr *E) { return Error(E); }
7983
7984 bool IsConstantEvaluatedBuiltinCall(const CallExpr *E) {
7985 unsigned BuiltinOp = E->getBuiltinCallee();
7986 return BuiltinOp != 0 &&
7987 Info.Ctx.BuiltinInfo.isConstantEvaluated(BuiltinOp);
7988 }
7989
7990public:
7991 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7992
7993 EvalInfo &getEvalInfo() { return Info; }
7994
7995 /// Report an evaluation error. This should only be called when an error is
7996 /// first discovered. When propagating an error, just return false.
7997 bool Error(const Expr *E, diag::kind D) {
7998 Info.FFDiag(E, D) << E->getSourceRange();
7999 return false;
8000 }
8001 bool Error(const Expr *E) {
8002 return Error(E, diag::note_invalid_subexpr_in_const_expr);
8003 }
8004
8005 bool VisitStmt(const Stmt *) {
8006 llvm_unreachable("Expression evaluator should not be called on stmts");
8007 }
8008 bool VisitExpr(const Expr *E) {
8009 return Error(E);
8010 }
8011
8012 bool VisitEmbedExpr(const EmbedExpr *E) {
8013 const auto It = E->begin();
8014 return StmtVisitorTy::Visit(*It);
8015 }
8016
8017 bool VisitPredefinedExpr(const PredefinedExpr *E) {
8018 return StmtVisitorTy::Visit(E->getFunctionName());
8019 }
8020 bool VisitConstantExpr(const ConstantExpr *E) {
8021 if (E->hasAPValueResult())
8022 return DerivedSuccess(E->getAPValueResult(), E);
8023
8024 return StmtVisitorTy::Visit(E->getSubExpr());
8025 }
8026
8027 bool VisitParenExpr(const ParenExpr *E)
8028 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8029 bool VisitUnaryExtension(const UnaryOperator *E)
8030 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8031 bool VisitUnaryPlus(const UnaryOperator *E)
8032 { return StmtVisitorTy::Visit(E->getSubExpr()); }
8033 bool VisitChooseExpr(const ChooseExpr *E)
8034 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
8035 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
8036 { return StmtVisitorTy::Visit(E->getResultExpr()); }
8037 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
8038 { return StmtVisitorTy::Visit(E->getReplacement()); }
8039 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
8040 TempVersionRAII RAII(*Info.CurrentCall);
8041 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8042 return StmtVisitorTy::Visit(E->getExpr());
8043 }
8044 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
8045 TempVersionRAII RAII(*Info.CurrentCall);
8046 // The initializer may not have been parsed yet, or might be erroneous.
8047 if (!E->getExpr())
8048 return Error(E);
8049 SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
8050 return StmtVisitorTy::Visit(E->getExpr());
8051 }
8052
8053 bool VisitExprWithCleanups(const ExprWithCleanups *E) {
8054 FullExpressionRAII Scope(Info);
8055 return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
8056 }
8057
8058 // Temporaries are registered when created, so we don't care about
8059 // CXXBindTemporaryExpr.
8060 bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
8061 return StmtVisitorTy::Visit(E->getSubExpr());
8062 }
8063
8064 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
8065 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
8066 return static_cast<Derived*>(this)->VisitCastExpr(E);
8067 }
8068 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
8069 if (!Info.Ctx.getLangOpts().CPlusPlus20)
8070 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
8071 return static_cast<Derived*>(this)->VisitCastExpr(E);
8072 }
8073 bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
8074 return static_cast<Derived*>(this)->VisitCastExpr(E);
8075 }
8076
8077 bool VisitBinaryOperator(const BinaryOperator *E) {
8078 switch (E->getOpcode()) {
8079 default:
8080 return Error(E);
8081
8082 case BO_Comma:
8083 VisitIgnoredValue(E->getLHS());
8084 return StmtVisitorTy::Visit(E->getRHS());
8085
8086 case BO_PtrMemD:
8087 case BO_PtrMemI: {
8088 LValue Obj;
8089 if (!HandleMemberPointerAccess(Info, E, Obj))
8090 return false;
8091 APValue Result;
8092 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
8093 return false;
8094 return DerivedSuccess(Result, E);
8095 }
8096 }
8097 }
8098
8099 bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
8100 return StmtVisitorTy::Visit(E->getSemanticForm());
8101 }
8102
8103 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
8104 // Evaluate and cache the common expression. We treat it as a temporary,
8105 // even though it's not quite the same thing.
8106 LValue CommonLV;
8107 if (!Evaluate(Info.CurrentCall->createTemporary(
8108 E->getOpaqueValue(),
8109 getStorageType(Info.Ctx, E->getOpaqueValue()),
8110 ScopeKind::FullExpression, CommonLV),
8111 Info, E->getCommon()))
8112 return false;
8113
8114 return HandleConditionalOperator(E);
8115 }
8116
8117 bool VisitConditionalOperator(const ConditionalOperator *E) {
8118 bool IsBcpCall = false;
8119 // If the condition (ignoring parens) is a __builtin_constant_p call,
8120 // the result is a constant expression if it can be folded without
8121 // side-effects. This is an important GNU extension. See GCC PR38377
8122 // for discussion.
8123 if (const CallExpr *CallCE =
8124 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
8125 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
8126 IsBcpCall = true;
8127
8128 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
8129 // constant expression; we can't check whether it's potentially foldable.
8130 // FIXME: We should instead treat __builtin_constant_p as non-constant if
8131 // it would return 'false' in this mode.
8132 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
8133 return false;
8134
8135 FoldConstant Fold(Info, IsBcpCall);
8136 if (!HandleConditionalOperator(E)) {
8137 Fold.keepDiagnostics();
8138 return false;
8139 }
8140
8141 return true;
8142 }
8143
8144 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
8145 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E);
8146 Value && !Value->isAbsent())
8147 return DerivedSuccess(*Value, E);
8148
8149 const Expr *Source = E->getSourceExpr();
8150 if (!Source)
8151 return Error(E);
8152 if (Source == E) {
8153 assert(0 && "OpaqueValueExpr recursively refers to itself");
8154 return Error(E);
8155 }
8156 return StmtVisitorTy::Visit(Source);
8157 }
8158
8159 bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
8160 for (const Expr *SemE : E->semantics()) {
8161 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
8162 // FIXME: We can't handle the case where an OpaqueValueExpr is also the
8163 // result expression: there could be two different LValues that would
8164 // refer to the same object in that case, and we can't model that.
8165 if (SemE == E->getResultExpr())
8166 return Error(E);
8167
8168 // Unique OVEs get evaluated if and when we encounter them when
8169 // emitting the rest of the semantic form, rather than eagerly.
8170 if (OVE->isUnique())
8171 continue;
8172
8173 LValue LV;
8174 if (!Evaluate(Info.CurrentCall->createTemporary(
8175 OVE, getStorageType(Info.Ctx, OVE),
8176 ScopeKind::FullExpression, LV),
8177 Info, OVE->getSourceExpr()))
8178 return false;
8179 } else if (SemE == E->getResultExpr()) {
8180 if (!StmtVisitorTy::Visit(SemE))
8181 return false;
8182 } else {
8183 if (!EvaluateIgnoredValue(Info, SemE))
8184 return false;
8185 }
8186 }
8187 return true;
8188 }
8189
8190 bool VisitCallExpr(const CallExpr *E) {
8191 APValue Result;
8192 if (!handleCallExpr(E, Result, nullptr))
8193 return false;
8194 return DerivedSuccess(Result, E);
8195 }
8196
8197 bool handleCallExpr(const CallExpr *E, APValue &Result,
8198 const LValue *ResultSlot) {
8199 CallScopeRAII CallScope(Info);
8200
8201 const Expr *Callee = E->getCallee()->IgnoreParens();
8202 QualType CalleeType = Callee->getType();
8203
8204 const FunctionDecl *FD = nullptr;
8205 LValue *This = nullptr, ThisVal;
8206 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
8207 bool HasQualifier = false;
8208
8209 CallRef Call;
8210
8211 // Extract function decl and 'this' pointer from the callee.
8212 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
8213 const CXXMethodDecl *Member = nullptr;
8214 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
8215 // Explicit bound member calls, such as x.f() or p->g();
8216 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
8217 return false;
8218 Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
8219 if (!Member)
8220 return Error(Callee);
8221 This = &ThisVal;
8222 HasQualifier = ME->hasQualifier();
8223 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
8224 // Indirect bound member calls ('.*' or '->*').
8225 const ValueDecl *D =
8226 HandleMemberPointerAccess(Info, BE, ThisVal, false);
8227 if (!D)
8228 return false;
8229 Member = dyn_cast<CXXMethodDecl>(D);
8230 if (!Member)
8231 return Error(Callee);
8232 This = &ThisVal;
8233 } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
8234 if (!Info.getLangOpts().CPlusPlus20)
8235 Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
8236 return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
8237 HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
8238 } else
8239 return Error(Callee);
8240 FD = Member;
8241 } else if (CalleeType->isFunctionPointerType()) {
8242 LValue CalleeLV;
8243 if (!EvaluatePointer(Callee, CalleeLV, Info))
8244 return false;
8245
8246 if (!CalleeLV.getLValueOffset().isZero())
8247 return Error(Callee);
8248 if (CalleeLV.isNullPointer()) {
8249 Info.FFDiag(Callee, diag::note_constexpr_null_callee)
8250 << const_cast<Expr *>(Callee);
8251 return false;
8252 }
8253 FD = dyn_cast_or_null<FunctionDecl>(
8254 CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
8255 if (!FD)
8256 return Error(Callee);
8257 // Don't call function pointers which have been cast to some other type.
8258 // Per DR (no number yet), the caller and callee can differ in noexcept.
8259 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
8260 CalleeType->getPointeeType(), FD->getType())) {
8261 return Error(E);
8262 }
8263
8264 // For an (overloaded) assignment expression, evaluate the RHS before the
8265 // LHS.
8266 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
8267 if (OCE && OCE->isAssignmentOp()) {
8268 assert(Args.size() == 2 && "wrong number of arguments in assignment");
8269 Call = Info.CurrentCall->createCall(FD);
8270 bool HasThis = false;
8271 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
8272 HasThis = MD->isImplicitObjectMemberFunction();
8273 if (!EvaluateArgs(HasThis ? Args.slice(1) : Args, Call, Info, FD,
8274 /*RightToLeft=*/true))
8275 return false;
8276 }
8277
8278 // Overloaded operator calls to member functions are represented as normal
8279 // calls with '*this' as the first argument.
8280 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8281 if (MD &&
8282 (MD->isImplicitObjectMemberFunction() || (OCE && MD->isStatic()))) {
8283 // FIXME: When selecting an implicit conversion for an overloaded
8284 // operator delete, we sometimes try to evaluate calls to conversion
8285 // operators without a 'this' parameter!
8286 if (Args.empty())
8287 return Error(E);
8288
8289 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
8290 return false;
8291
8292 // If we are calling a static operator, the 'this' argument needs to be
8293 // ignored after being evaluated.
8294 if (MD->isInstance())
8295 This = &ThisVal;
8296
8297 // If this is syntactically a simple assignment using a trivial
8298 // assignment operator, start the lifetimes of union members as needed,
8299 // per C++20 [class.union]5.
8300 if (Info.getLangOpts().CPlusPlus20 && OCE &&
8301 OCE->getOperator() == OO_Equal && MD->isTrivial() &&
8302 !MaybeHandleUnionActiveMemberChange(Info, Args[0], ThisVal))
8303 return false;
8304
8305 Args = Args.slice(1);
8306 } else if (MD && MD->isLambdaStaticInvoker()) {
8307 // Map the static invoker for the lambda back to the call operator.
8308 // Conveniently, we don't have to slice out the 'this' argument (as is
8309 // being done for the non-static case), since a static member function
8310 // doesn't have an implicit argument passed in.
8311 const CXXRecordDecl *ClosureClass = MD->getParent();
8312 assert(
8313 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
8314 "Number of captures must be zero for conversion to function-ptr");
8315
8316 const CXXMethodDecl *LambdaCallOp =
8317 ClosureClass->getLambdaCallOperator();
8318
8319 // Set 'FD', the function that will be called below, to the call
8320 // operator. If the closure object represents a generic lambda, find
8321 // the corresponding specialization of the call operator.
8322
8323 if (ClosureClass->isGenericLambda()) {
8324 assert(MD->isFunctionTemplateSpecialization() &&
8325 "A generic lambda's static-invoker function must be a "
8326 "template specialization");
8328 FunctionTemplateDecl *CallOpTemplate =
8329 LambdaCallOp->getDescribedFunctionTemplate();
8330 void *InsertPos = nullptr;
8331 FunctionDecl *CorrespondingCallOpSpecialization =
8332 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
8333 assert(CorrespondingCallOpSpecialization &&
8334 "We must always have a function call operator specialization "
8335 "that corresponds to our static invoker specialization");
8336 assert(isa<CXXMethodDecl>(CorrespondingCallOpSpecialization));
8337 FD = CorrespondingCallOpSpecialization;
8338 } else
8339 FD = LambdaCallOp;
8340 } else if (FD->isReplaceableGlobalAllocationFunction()) {
8341 if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
8342 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
8343 LValue Ptr;
8344 if (!HandleOperatorNewCall(Info, E, Ptr))
8345 return false;
8346 Ptr.moveInto(Result);
8347 return CallScope.destroy();
8348 } else {
8349 return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
8350 }
8351 }
8352 } else
8353 return Error(E);
8354
8355 // Evaluate the arguments now if we've not already done so.
8356 if (!Call) {
8357 Call = Info.CurrentCall->createCall(FD);
8358 if (!EvaluateArgs(Args, Call, Info, FD))
8359 return false;
8360 }
8361
8362 SmallVector<QualType, 4> CovariantAdjustmentPath;
8363 if (This) {
8364 auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
8365 if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
8366 // Perform virtual dispatch, if necessary.
8367 FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
8368 CovariantAdjustmentPath);
8369 if (!FD)
8370 return false;
8371 } else if (NamedMember && NamedMember->isImplicitObjectMemberFunction()) {
8372 // Check that the 'this' pointer points to an object of the right type.
8373 // FIXME: If this is an assignment operator call, we may need to change
8374 // the active union member before we check this.
8375 if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
8376 return false;
8377 }
8378 }
8379
8380 // Destructor calls are different enough that they have their own codepath.
8381 if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
8382 assert(This && "no 'this' pointer for destructor call");
8383 return HandleDestruction(Info, E, *This,
8384 Info.Ctx.getRecordType(DD->getParent())) &&
8385 CallScope.destroy();
8386 }
8387
8388 const FunctionDecl *Definition = nullptr;
8389 Stmt *Body = FD->getBody(Definition);
8390
8391 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
8392 !HandleFunctionCall(E->getExprLoc(), Definition, This, E, Args, Call,
8393 Body, Info, Result, ResultSlot))
8394 return false;
8395
8396 if (!CovariantAdjustmentPath.empty() &&
8397 !HandleCovariantReturnAdjustment(Info, E, Result,
8398 CovariantAdjustmentPath))
8399 return false;
8400
8401 return CallScope.destroy();
8402 }
8403
8404 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8405 return StmtVisitorTy::Visit(E->getInitializer());
8406 }
8407 bool VisitInitListExpr(const InitListExpr *E) {
8408 if (E->getNumInits() == 0)
8409 return DerivedZeroInitialization(E);
8410 if (E->getNumInits() == 1)
8411 return StmtVisitorTy::Visit(E->getInit(0));
8412 return Error(E);
8413 }
8414 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
8415 return DerivedZeroInitialization(E);
8416 }
8417 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
8418 return DerivedZeroInitialization(E);
8419 }
8420 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
8421 return DerivedZeroInitialization(E);
8422 }
8423
8424 /// A member expression where the object is a prvalue is itself a prvalue.
8425 bool VisitMemberExpr(const MemberExpr *E) {
8426 assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
8427 "missing temporary materialization conversion");
8428 assert(!E->isArrow() && "missing call to bound member function?");
8429
8430 APValue Val;
8431 if (!Evaluate(Val, Info, E->getBase()))
8432 return false;
8433
8434 QualType BaseTy = E->getBase()->getType();
8435
8436 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
8437 if (!FD) return Error(E);
8438 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
8439 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8440 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8441
8442 // Note: there is no lvalue base here. But this case should only ever
8443 // happen in C or in C++98, where we cannot be evaluating a constexpr
8444 // constructor, which is the only case the base matters.
8445 CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
8446 SubobjectDesignator Designator(BaseTy);
8447 Designator.addDeclUnchecked(FD);
8448
8449 APValue Result;
8450 return extractSubobject(Info, E, Obj, Designator, Result) &&
8451 DerivedSuccess(Result, E);
8452 }
8453
8454 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
8455 APValue Val;
8456 if (!Evaluate(Val, Info, E->getBase()))
8457 return false;
8458
8459 if (Val.isVector()) {
8461 E->getEncodedElementAccess(Indices);
8462 if (Indices.size() == 1) {
8463 // Return scalar.
8464 return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
8465 } else {
8466 // Construct new APValue vector.
8468 for (unsigned I = 0; I < Indices.size(); ++I) {
8469 Elts.push_back(Val.getVectorElt(Indices[I]));
8470 }
8471 APValue VecResult(Elts.data(), Indices.size());
8472 return DerivedSuccess(VecResult, E);
8473 }
8474 }
8475
8476 return false;
8477 }
8478
8479 bool VisitCastExpr(const CastExpr *E) {
8480 switch (E->getCastKind()) {
8481 default:
8482 break;
8483
8484 case CK_AtomicToNonAtomic: {
8485 APValue AtomicVal;
8486 // This does not need to be done in place even for class/array types:
8487 // atomic-to-non-atomic conversion implies copying the object
8488 // representation.
8489 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
8490 return false;
8491 return DerivedSuccess(AtomicVal, E);
8492 }
8493
8494 case CK_NoOp:
8495 case CK_UserDefinedConversion:
8496 return StmtVisitorTy::Visit(E->getSubExpr());
8497
8498 case CK_LValueToRValue: {
8499 LValue LVal;
8500 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
8501 return false;
8502 APValue RVal;
8503 // Note, we use the subexpression's type in order to retain cv-qualifiers.
8504 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8505 LVal, RVal))
8506 return false;
8507 return DerivedSuccess(RVal, E);
8508 }
8509 case CK_LValueToRValueBitCast: {
8510 APValue DestValue, SourceValue;
8511 if (!Evaluate(SourceValue, Info, E->getSubExpr()))
8512 return false;
8513 if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
8514 return false;
8515 return DerivedSuccess(DestValue, E);
8516 }
8517
8518 case CK_AddressSpaceConversion: {
8519 APValue Value;
8520 if (!Evaluate(Value, Info, E->getSubExpr()))
8521 return false;
8522 return DerivedSuccess(Value, E);
8523 }
8524 }
8525
8526 return Error(E);
8527 }
8528
8529 bool VisitUnaryPostInc(const UnaryOperator *UO) {
8530 return VisitUnaryPostIncDec(UO);
8531 }
8532 bool VisitUnaryPostDec(const UnaryOperator *UO) {
8533 return VisitUnaryPostIncDec(UO);
8534 }
8535 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
8536 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8537 return Error(UO);
8538
8539 LValue LVal;
8540 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
8541 return false;
8542 APValue RVal;
8543 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
8544 UO->isIncrementOp(), &RVal))
8545 return false;
8546 return DerivedSuccess(RVal, UO);
8547 }
8548
8549 bool VisitStmtExpr(const StmtExpr *E) {
8550 // We will have checked the full-expressions inside the statement expression
8551 // when they were completed, and don't need to check them again now.
8552 llvm::SaveAndRestore NotCheckingForUB(Info.CheckingForUndefinedBehavior,
8553 false);
8554
8555 const CompoundStmt *CS = E->getSubStmt();
8556 if (CS->body_empty())
8557 return true;
8558
8559 BlockScopeRAII Scope(Info);
8561 BE = CS->body_end();
8562 /**/; ++BI) {
8563 if (BI + 1 == BE) {
8564 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
8565 if (!FinalExpr) {
8566 Info.FFDiag((*BI)->getBeginLoc(),
8567 diag::note_constexpr_stmt_expr_unsupported);
8568 return false;
8569 }
8570 return this->Visit(FinalExpr) && Scope.destroy();
8571 }
8572
8574 StmtResult Result = { ReturnValue, nullptr };
8575 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
8576 if (ESR != ESR_Succeeded) {
8577 // FIXME: If the statement-expression terminated due to 'return',
8578 // 'break', or 'continue', it would be nice to propagate that to
8579 // the outer statement evaluation rather than bailing out.
8580 if (ESR != ESR_Failed)
8581 Info.FFDiag((*BI)->getBeginLoc(),
8582 diag::note_constexpr_stmt_expr_unsupported);
8583 return false;
8584 }
8585 }
8586
8587 llvm_unreachable("Return from function from the loop above.");
8588 }
8589
8590 bool VisitPackIndexingExpr(const PackIndexingExpr *E) {
8591 return StmtVisitorTy::Visit(E->getSelectedExpr());
8592 }
8593
8594 /// Visit a value which is evaluated, but whose value is ignored.
8595 void VisitIgnoredValue(const Expr *E) {
8596 EvaluateIgnoredValue(Info, E);
8597 }
8598
8599 /// Potentially visit a MemberExpr's base expression.
8600 void VisitIgnoredBaseExpression(const Expr *E) {
8601 // While MSVC doesn't evaluate the base expression, it does diagnose the
8602 // presence of side-effecting behavior.
8603 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
8604 return;
8605 VisitIgnoredValue(E);
8606 }
8607};
8608
8609} // namespace
8610
8611//===----------------------------------------------------------------------===//
8612// Common base class for lvalue and temporary evaluation.
8613//===----------------------------------------------------------------------===//
8614namespace {
8615template<class Derived>
8616class LValueExprEvaluatorBase
8617 : public ExprEvaluatorBase<Derived> {
8618protected:
8619 LValue &Result;
8620 bool InvalidBaseOK;
8621 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
8622 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
8623
8625 Result.set(B);
8626 return true;
8627 }
8628
8629 bool evaluatePointer(const Expr *E, LValue &Result) {
8630 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
8631 }
8632
8633public:
8634 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
8635 : ExprEvaluatorBaseTy(Info), Result(Result),
8636 InvalidBaseOK(InvalidBaseOK) {}
8637
8638 bool Success(const APValue &V, const Expr *E) {
8639 Result.setFrom(this->Info.Ctx, V);
8640 return true;
8641 }
8642
8643 bool VisitMemberExpr(const MemberExpr *E) {
8644 // Handle non-static data members.
8645 QualType BaseTy;
8646 bool EvalOK;
8647 if (E->isArrow()) {
8648 EvalOK = evaluatePointer(E->getBase(), Result);
8649 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
8650 } else if (E->getBase()->isPRValue()) {
8651 assert(E->getBase()->getType()->isRecordType());
8652 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
8653 BaseTy = E->getBase()->getType();
8654 } else {
8655 EvalOK = this->Visit(E->getBase());
8656 BaseTy = E->getBase()->getType();
8657 }
8658 if (!EvalOK) {
8659 if (!InvalidBaseOK)
8660 return false;
8661 Result.setInvalid(E);
8662 return true;
8663 }
8664
8665 const ValueDecl *MD = E->getMemberDecl();
8666 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
8667 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
8668 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
8669 (void)BaseTy;
8670 if (!HandleLValueMember(this->Info, E, Result, FD))
8671 return false;
8672 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
8673 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
8674 return false;
8675 } else
8676 return this->Error(E);
8677
8678 if (MD->getType()->isReferenceType()) {
8679 APValue RefValue;
8680 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
8681 RefValue))
8682 return false;
8683 return Success(RefValue, E);
8684 }
8685 return true;
8686 }
8687
8688 bool VisitBinaryOperator(const BinaryOperator *E) {
8689 switch (E->getOpcode()) {
8690 default:
8691 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8692
8693 case BO_PtrMemD:
8694 case BO_PtrMemI:
8695 return HandleMemberPointerAccess(this->Info, E, Result);
8696 }
8697 }
8698
8699 bool VisitCastExpr(const CastExpr *E) {
8700 switch (E->getCastKind()) {
8701 default:
8702 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8703
8704 case CK_DerivedToBase:
8705 case CK_UncheckedDerivedToBase:
8706 if (!this->Visit(E->getSubExpr()))
8707 return false;
8708
8709 // Now figure out the necessary offset to add to the base LV to get from
8710 // the derived class to the base class.
8711 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8712 Result);
8713 }
8714 }
8715};
8716}
8717
8718//===----------------------------------------------------------------------===//
8719// LValue Evaluation
8720//
8721// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8722// function designators (in C), decl references to void objects (in C), and
8723// temporaries (if building with -Wno-address-of-temporary).
8724//
8725// LValue evaluation produces values comprising a base expression of one of the
8726// following types:
8727// - Declarations
8728// * VarDecl
8729// * FunctionDecl
8730// - Literals
8731// * CompoundLiteralExpr in C (and in global scope in C++)
8732// * StringLiteral
8733// * PredefinedExpr
8734// * ObjCStringLiteralExpr
8735// * ObjCEncodeExpr
8736// * AddrLabelExpr
8737// * BlockExpr
8738// * CallExpr for a MakeStringConstant builtin
8739// - typeid(T) expressions, as TypeInfoLValues
8740// - Locals and temporaries
8741// * MaterializeTemporaryExpr
8742// * Any Expr, with a CallIndex indicating the function in which the temporary
8743// was evaluated, for cases where the MaterializeTemporaryExpr is missing
8744// from the AST (FIXME).
8745// * A MaterializeTemporaryExpr that has static storage duration, with no
8746// CallIndex, for a lifetime-extended temporary.
8747// * The ConstantExpr that is currently being evaluated during evaluation of an
8748// immediate invocation.
8749// plus an offset in bytes.
8750//===----------------------------------------------------------------------===//
8751namespace {
8752class LValueExprEvaluator
8753 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8754public:
8755 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8756 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8757
8758 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8759 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8760
8761 bool VisitCallExpr(const CallExpr *E);
8762 bool VisitDeclRefExpr(const DeclRefExpr *E);
8763 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8764 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8765 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8766 bool VisitMemberExpr(const MemberExpr *E);
8767 bool VisitStringLiteral(const StringLiteral *E) {
8769 E, 0, Info.getASTContext().getNextStringLiteralVersion()));
8770 }
8771 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8772 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8773 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8774 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8775 bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
8776 bool VisitUnaryDeref(const UnaryOperator *E);
8777 bool VisitUnaryReal(const UnaryOperator *E);
8778 bool VisitUnaryImag(const UnaryOperator *E);
8779 bool VisitUnaryPreInc(const UnaryOperator *UO) {
8780 return VisitUnaryPreIncDec(UO);
8781 }
8782 bool VisitUnaryPreDec(const UnaryOperator *UO) {
8783 return VisitUnaryPreIncDec(UO);
8784 }
8785 bool VisitBinAssign(const BinaryOperator *BO);
8786 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8787
8788 bool VisitCastExpr(const CastExpr *E) {
8789 switch (E->getCastKind()) {
8790 default:
8791 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8792
8793 case CK_LValueBitCast:
8794 this->CCEDiag(E, diag::note_constexpr_invalid_cast)
8795 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
8796 if (!Visit(E->getSubExpr()))
8797 return false;
8798 Result.Designator.setInvalid();
8799 return true;
8800
8801 case CK_BaseToDerived:
8802 if (!Visit(E->getSubExpr()))
8803 return false;
8804 return HandleBaseToDerivedCast(Info, E, Result);
8805
8806 case CK_Dynamic:
8807 if (!Visit(E->getSubExpr()))
8808 return false;
8809 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8810 }
8811 }
8812};
8813} // end anonymous namespace
8814
8815/// Get an lvalue to a field of a lambda's closure type.
8816static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result,
8817 const CXXMethodDecl *MD, const FieldDecl *FD,
8818 bool LValueToRValueConversion) {
8819 // Static lambda function call operators can't have captures. We already
8820 // diagnosed this, so bail out here.
8821 if (MD->isStatic()) {
8822 assert(Info.CurrentCall->This == nullptr &&
8823 "This should not be set for a static call operator");
8824 return false;
8825 }
8826
8827 // Start with 'Result' referring to the complete closure object...
8829 // Self may be passed by reference or by value.
8830 const ParmVarDecl *Self = MD->getParamDecl(0);
8831 if (Self->getType()->isReferenceType()) {
8832 APValue *RefValue = Info.getParamSlot(Info.CurrentCall->Arguments, Self);
8833 if (!RefValue->allowConstexprUnknown() || RefValue->hasValue())
8834 Result.setFrom(Info.Ctx, *RefValue);
8835 } else {
8836 const ParmVarDecl *VD = Info.CurrentCall->Arguments.getOrigParam(Self);
8837 CallStackFrame *Frame =
8838 Info.getCallFrameAndDepth(Info.CurrentCall->Arguments.CallIndex)
8839 .first;
8840 unsigned Version = Info.CurrentCall->Arguments.Version;
8841 Result.set({VD, Frame->Index, Version});
8842 }
8843 } else
8844 Result = *Info.CurrentCall->This;
8845
8846 // ... then update it to refer to the field of the closure object
8847 // that represents the capture.
8848 if (!HandleLValueMember(Info, E, Result, FD))
8849 return false;
8850
8851 // And if the field is of reference type (or if we captured '*this' by
8852 // reference), update 'Result' to refer to what
8853 // the field refers to.
8854 if (LValueToRValueConversion) {
8855 APValue RVal;
8856 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result, RVal))
8857 return false;
8858 Result.setFrom(Info.Ctx, RVal);
8859 }
8860 return true;
8861}
8862
8863/// Evaluate an expression as an lvalue. This can be legitimately called on
8864/// expressions which are not glvalues, in three cases:
8865/// * function designators in C, and
8866/// * "extern void" objects
8867/// * @selector() expressions in Objective-C
8868static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8869 bool InvalidBaseOK) {
8870 assert(!E->isValueDependent());
8871 assert(E->isGLValue() || E->getType()->isFunctionType() ||
8872 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E->IgnoreParens()));
8873 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8874}
8875
8876bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8877 const NamedDecl *D = E->getDecl();
8880 return Success(cast<ValueDecl>(D));
8881 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8882 return VisitVarDecl(E, VD);
8883 if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8884 return Visit(BD->getBinding());
8885 return Error(E);
8886}
8887
8888
8889bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8890 // C++23 [expr.const]p8 If we have a reference type allow unknown references
8891 // and pointers.
8892 bool AllowConstexprUnknown =
8893 Info.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType();
8894 // If we are within a lambda's call operator, check whether the 'VD' referred
8895 // to within 'E' actually represents a lambda-capture that maps to a
8896 // data-member/field within the closure object, and if so, evaluate to the
8897 // field or what the field refers to.
8898 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8899 isa<DeclRefExpr>(E) &&
8900 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8901 // We don't always have a complete capture-map when checking or inferring if
8902 // the function call operator meets the requirements of a constexpr function
8903 // - but we don't need to evaluate the captures to determine constexprness
8904 // (dcl.constexpr C++17).
8905 if (Info.checkingPotentialConstantExpression())
8906 return false;
8907
8908 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8909 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
8910 return HandleLambdaCapture(Info, E, Result, MD, FD,
8911 FD->getType()->isReferenceType());
8912 }
8913 }
8914
8915 CallStackFrame *Frame = nullptr;
8916 unsigned Version = 0;
8917 if (VD->hasLocalStorage()) {
8918 // Only if a local variable was declared in the function currently being
8919 // evaluated, do we expect to be able to find its value in the current
8920 // frame. (Otherwise it was likely declared in an enclosing context and
8921 // could either have a valid evaluatable value (for e.g. a constexpr
8922 // variable) or be ill-formed (and trigger an appropriate evaluation
8923 // diagnostic)).
8924 CallStackFrame *CurrFrame = Info.CurrentCall;
8925 if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8926 // Function parameters are stored in some caller's frame. (Usually the
8927 // immediate caller, but for an inherited constructor they may be more
8928 // distant.)
8929 if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8930 if (CurrFrame->Arguments) {
8931 VD = CurrFrame->Arguments.getOrigParam(PVD);
8932 Frame =
8933 Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8934 Version = CurrFrame->Arguments.Version;
8935 }
8936 } else {
8937 Frame = CurrFrame;
8938 Version = CurrFrame->getCurrentTemporaryVersion(VD);
8939 }
8940 }
8941 }
8942
8943 if (!VD->getType()->isReferenceType()) {
8944 if (Frame) {
8945 Result.set({VD, Frame->Index, Version});
8946 return true;
8947 }
8948 return Success(VD);
8949 }
8950
8951 if (!Info.getLangOpts().CPlusPlus11) {
8952 Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8953 << VD << VD->getType();
8954 Info.Note(VD->getLocation(), diag::note_declared_at);
8955 }
8956
8957 APValue *V;
8958 if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8959 return false;
8960 if (!V->hasValue()) {
8961 // FIXME: Is it possible for V to be indeterminate here? If so, we should
8962 // adjust the diagnostic to say that.
8963 // C++23 [expr.const]p8 If we have a variable that is unknown reference
8964 // or pointer it may not have a value but still be usable later on so do not
8965 // diagnose.
8966 if (!Info.checkingPotentialConstantExpression() && !AllowConstexprUnknown)
8967 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8968
8969 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
8970 // pointer try to recover it from the frame and set the result accordingly.
8971 if (VD->getType()->isReferenceType() && AllowConstexprUnknown) {
8972 if (Frame) {
8973 Result.set({VD, Frame->Index, Version});
8974 return true;
8975 }
8976 return Success(VD);
8977 }
8978 return false;
8979 }
8980
8981 return Success(*V, E);
8982}
8983
8984bool LValueExprEvaluator::VisitCallExpr(const CallExpr *E) {
8985 if (!IsConstantEvaluatedBuiltinCall(E))
8986 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8987
8988 switch (E->getBuiltinCallee()) {
8989 default:
8990 return false;
8991 case Builtin::BIas_const:
8992 case Builtin::BIforward:
8993 case Builtin::BIforward_like:
8994 case Builtin::BImove:
8995 case Builtin::BImove_if_noexcept:
8996 if (cast<FunctionDecl>(E->getCalleeDecl())->isConstexpr())
8997 return Visit(E->getArg(0));
8998 break;
8999 }
9000
9001 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9002}
9003
9004bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
9005 const MaterializeTemporaryExpr *E) {
9006 // Walk through the expression to find the materialized temporary itself.
9009 const Expr *Inner =
9010 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
9011
9012 // If we passed any comma operators, evaluate their LHSs.
9013 for (const Expr *E : CommaLHSs)
9014 if (!EvaluateIgnoredValue(Info, E))
9015 return false;
9016
9017 // A materialized temporary with static storage duration can appear within the
9018 // result of a constant expression evaluation, so we need to preserve its
9019 // value for use outside this evaluation.
9020 APValue *Value;
9021 if (E->getStorageDuration() == SD_Static) {
9022 if (Info.EvalMode == EvalInfo::EM_ConstantFold)
9023 return false;
9024 // FIXME: What about SD_Thread?
9025 Value = E->getOrCreateValue(true);
9026 *Value = APValue();
9027 Result.set(E);
9028 } else {
9029 Value = &Info.CurrentCall->createTemporary(
9030 E, Inner->getType(),
9031 E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
9032 : ScopeKind::Block,
9033 Result);
9034 }
9035
9036 QualType Type = Inner->getType();
9037
9038 // Materialize the temporary itself.
9039 if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
9040 *Value = APValue();
9041 return false;
9042 }
9043
9044 // Adjust our lvalue to refer to the desired subobject.
9045 for (unsigned I = Adjustments.size(); I != 0; /**/) {
9046 --I;
9047 switch (Adjustments[I].Kind) {
9049 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
9050 Type, Result))
9051 return false;
9052 Type = Adjustments[I].DerivedToBase.BasePath->getType();
9053 break;
9054
9056 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
9057 return false;
9058 Type = Adjustments[I].Field->getType();
9059 break;
9060
9062 if (!HandleMemberPointerAccess(this->Info, Type, Result,
9063 Adjustments[I].Ptr.RHS))
9064 return false;
9065 Type = Adjustments[I].Ptr.MPT->getPointeeType();
9066 break;
9067 }
9068 }
9069
9070 return true;
9071}
9072
9073bool
9074LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
9075 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
9076 "lvalue compound literal in c++?");
9077 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
9078 // only see this when folding in C, so there's no standard to follow here.
9079 return Success(E);
9080}
9081
9082bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
9084
9085 if (!E->isPotentiallyEvaluated()) {
9086 if (E->isTypeOperand())
9087 TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
9088 else
9089 TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
9090 } else {
9091 if (!Info.Ctx.getLangOpts().CPlusPlus20) {
9092 Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
9093 << E->getExprOperand()->getType()
9094 << E->getExprOperand()->getSourceRange();
9095 }
9096
9097 if (!Visit(E->getExprOperand()))
9098 return false;
9099
9100 std::optional<DynamicType> DynType =
9101 ComputeDynamicType(Info, E, Result, AK_TypeId);
9102 if (!DynType)
9103 return false;
9104
9105 TypeInfo =
9106 TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
9107 }
9108
9110}
9111
9112bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
9113 return Success(E->getGuidDecl());
9114}
9115
9116bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
9117 // Handle static data members.
9118 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
9119 VisitIgnoredBaseExpression(E->getBase());
9120 return VisitVarDecl(E, VD);
9121 }
9122
9123 // Handle static member functions.
9124 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
9125 if (MD->isStatic()) {
9126 VisitIgnoredBaseExpression(E->getBase());
9127 return Success(MD);
9128 }
9129 }
9130
9131 // Handle non-static data members.
9132 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
9133}
9134
9135bool LValueExprEvaluator::VisitExtVectorElementExpr(
9136 const ExtVectorElementExpr *E) {
9137 bool Success = true;
9138
9139 APValue Val;
9140 if (!Evaluate(Val, Info, E->getBase())) {
9141 if (!Info.noteFailure())
9142 return false;
9143 Success = false;
9144 }
9145
9147 E->getEncodedElementAccess(Indices);
9148 // FIXME: support accessing more than one element
9149 if (Indices.size() > 1)
9150 return false;
9151
9152 if (Success) {
9153 Result.setFrom(Info.Ctx, Val);
9154 const auto *VT = E->getBase()->getType()->castAs<VectorType>();
9155 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9156 VT->getNumElements(), Indices[0]);
9157 }
9158
9159 return Success;
9160}
9161
9162bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
9163 if (E->getBase()->getType()->isSveVLSBuiltinType())
9164 return Error(E);
9165
9166 APSInt Index;
9167 bool Success = true;
9168
9169 if (const auto *VT = E->getBase()->getType()->getAs<VectorType>()) {
9170 APValue Val;
9171 if (!Evaluate(Val, Info, E->getBase())) {
9172 if (!Info.noteFailure())
9173 return false;
9174 Success = false;
9175 }
9176
9177 if (!EvaluateInteger(E->getIdx(), Index, Info)) {
9178 if (!Info.noteFailure())
9179 return false;
9180 Success = false;
9181 }
9182
9183 if (Success) {
9184 Result.setFrom(Info.Ctx, Val);
9185 HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
9186 VT->getNumElements(), Index.getExtValue());
9187 }
9188
9189 return Success;
9190 }
9191
9192 // C++17's rules require us to evaluate the LHS first, regardless of which
9193 // side is the base.
9194 for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
9195 if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
9196 : !EvaluateInteger(SubExpr, Index, Info)) {
9197 if (!Info.noteFailure())
9198 return false;
9199 Success = false;
9200 }
9201 }
9202
9203 return Success &&
9204 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
9205}
9206
9207bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
9208 return evaluatePointer(E->getSubExpr(), Result);
9209}
9210
9211bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9212 if (!Visit(E->getSubExpr()))
9213 return false;
9214 // __real is a no-op on scalar lvalues.
9215 if (E->getSubExpr()->getType()->isAnyComplexType())
9216 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
9217 return true;
9218}
9219
9220bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9221 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
9222 "lvalue __imag__ on scalar?");
9223 if (!Visit(E->getSubExpr()))
9224 return false;
9225 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
9226 return true;
9227}
9228
9229bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
9230 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9231 return Error(UO);
9232
9233 if (!this->Visit(UO->getSubExpr()))
9234 return false;
9235
9236 return handleIncDec(
9237 this->Info, UO, Result, UO->getSubExpr()->getType(),
9238 UO->isIncrementOp(), nullptr);
9239}
9240
9241bool LValueExprEvaluator::VisitCompoundAssignOperator(
9242 const CompoundAssignOperator *CAO) {
9243 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9244 return Error(CAO);
9245
9246 bool Success = true;
9247
9248 // C++17 onwards require that we evaluate the RHS first.
9249 APValue RHS;
9250 if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
9251 if (!Info.noteFailure())
9252 return false;
9253 Success = false;
9254 }
9255
9256 // The overall lvalue result is the result of evaluating the LHS.
9257 if (!this->Visit(CAO->getLHS()) || !Success)
9258 return false;
9259
9261 this->Info, CAO,
9262 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
9263 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
9264}
9265
9266bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
9267 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
9268 return Error(E);
9269
9270 bool Success = true;
9271
9272 // C++17 onwards require that we evaluate the RHS first.
9273 APValue NewVal;
9274 if (!Evaluate(NewVal, this->Info, E->getRHS())) {
9275 if (!Info.noteFailure())
9276 return false;
9277 Success = false;
9278 }
9279
9280 if (!this->Visit(E->getLHS()) || !Success)
9281 return false;
9282
9283 if (Info.getLangOpts().CPlusPlus20 &&
9284 !MaybeHandleUnionActiveMemberChange(Info, E->getLHS(), Result))
9285 return false;
9286
9287 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
9288 NewVal);
9289}
9290
9291//===----------------------------------------------------------------------===//
9292// Pointer Evaluation
9293//===----------------------------------------------------------------------===//
9294
9295/// Attempts to compute the number of bytes available at the pointer
9296/// returned by a function with the alloc_size attribute. Returns true if we
9297/// were successful. Places an unsigned number into `Result`.
9298///
9299/// This expects the given CallExpr to be a call to a function with an
9300/// alloc_size attribute.
9302 const CallExpr *Call,
9303 llvm::APInt &Result) {
9304 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
9305
9306 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
9307 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
9308 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
9309 if (Call->getNumArgs() <= SizeArgNo)
9310 return false;
9311
9312 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
9315 return false;
9316 Into = ExprResult.Val.getInt();
9317 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
9318 return false;
9319 Into = Into.zext(BitsInSizeT);
9320 return true;
9321 };
9322
9323 APSInt SizeOfElem;
9324 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
9325 return false;
9326
9327 if (!AllocSize->getNumElemsParam().isValid()) {
9328 Result = std::move(SizeOfElem);
9329 return true;
9330 }
9331
9332 APSInt NumberOfElems;
9333 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
9334 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
9335 return false;
9336
9337 bool Overflow;
9338 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
9339 if (Overflow)
9340 return false;
9341
9342 Result = std::move(BytesAvailable);
9343 return true;
9344}
9345
9346/// Convenience function. LVal's base must be a call to an alloc_size
9347/// function.
9349 const LValue &LVal,
9350 llvm::APInt &Result) {
9351 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9352 "Can't get the size of a non alloc_size function");
9353 const auto *Base = LVal.getLValueBase().get<const Expr *>();
9354 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
9355 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
9356}
9357
9358/// Attempts to evaluate the given LValueBase as the result of a call to
9359/// a function with the alloc_size attribute. If it was possible to do so, this
9360/// function will return true, make Result's Base point to said function call,
9361/// and mark Result's Base as invalid.
9363 LValue &Result) {
9364 if (Base.isNull())
9365 return false;
9366
9367 // Because we do no form of static analysis, we only support const variables.
9368 //
9369 // Additionally, we can't support parameters, nor can we support static
9370 // variables (in the latter case, use-before-assign isn't UB; in the former,
9371 // we have no clue what they'll be assigned to).
9372 const auto *VD =
9373 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
9374 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
9375 return false;
9376
9377 const Expr *Init = VD->getAnyInitializer();
9378 if (!Init || Init->getType().isNull())
9379 return false;
9380
9381 const Expr *E = Init->IgnoreParens();
9382 if (!tryUnwrapAllocSizeCall(E))
9383 return false;
9384
9385 // Store E instead of E unwrapped so that the type of the LValue's base is
9386 // what the user wanted.
9387 Result.setInvalid(E);
9388
9389 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
9390 Result.addUnsizedArray(Info, E, Pointee);
9391 return true;
9392}
9393
9394namespace {
9395class PointerExprEvaluator
9396 : public ExprEvaluatorBase<PointerExprEvaluator> {
9397 LValue &Result;
9398 bool InvalidBaseOK;
9399
9400 bool Success(const Expr *E) {
9401 Result.set(E);
9402 return true;
9403 }
9404
9405 bool evaluateLValue(const Expr *E, LValue &Result) {
9406 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
9407 }
9408
9409 bool evaluatePointer(const Expr *E, LValue &Result) {
9410 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
9411 }
9412
9413 bool visitNonBuiltinCallExpr(const CallExpr *E);
9414public:
9415
9416 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
9417 : ExprEvaluatorBaseTy(info), Result(Result),
9418 InvalidBaseOK(InvalidBaseOK) {}
9419
9420 bool Success(const APValue &V, const Expr *E) {
9421 Result.setFrom(Info.Ctx, V);
9422 return true;
9423 }
9424 bool ZeroInitialization(const Expr *E) {
9425 Result.setNull(Info.Ctx, E->getType());
9426 return true;
9427 }
9428
9429 bool VisitBinaryOperator(const BinaryOperator *E);
9430 bool VisitCastExpr(const CastExpr* E);
9431 bool VisitUnaryAddrOf(const UnaryOperator *E);
9432 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
9433 { return Success(E); }
9434 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
9435 if (E->isExpressibleAsConstantInitializer())
9436 return Success(E);
9437 if (Info.noteFailure())
9438 EvaluateIgnoredValue(Info, E->getSubExpr());
9439 return Error(E);
9440 }
9441 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
9442 { return Success(E); }
9443 bool VisitCallExpr(const CallExpr *E);
9444 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9445 bool VisitBlockExpr(const BlockExpr *E) {
9446 if (!E->getBlockDecl()->hasCaptures())
9447 return Success(E);
9448 return Error(E);
9449 }
9450 bool VisitCXXThisExpr(const CXXThisExpr *E) {
9451 auto DiagnoseInvalidUseOfThis = [&] {
9452 if (Info.getLangOpts().CPlusPlus11)
9453 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
9454 else
9455 Info.FFDiag(E);
9456 };
9457
9458 // Can't look at 'this' when checking a potential constant expression.
9459 if (Info.checkingPotentialConstantExpression())
9460 return false;
9461
9462 bool IsExplicitLambda =
9463 isLambdaCallWithExplicitObjectParameter(Info.CurrentCall->Callee);
9464 if (!IsExplicitLambda) {
9465 if (!Info.CurrentCall->This) {
9466 DiagnoseInvalidUseOfThis();
9467 return false;
9468 }
9469
9470 Result = *Info.CurrentCall->This;
9471 }
9472
9473 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
9474 // Ensure we actually have captured 'this'. If something was wrong with
9475 // 'this' capture, the error would have been previously reported.
9476 // Otherwise we can be inside of a default initialization of an object
9477 // declared by lambda's body, so no need to return false.
9478 if (!Info.CurrentCall->LambdaThisCaptureField) {
9479 if (IsExplicitLambda && !Info.CurrentCall->This) {
9480 DiagnoseInvalidUseOfThis();
9481 return false;
9482 }
9483
9484 return true;
9485 }
9486
9487 const auto *MD = cast<CXXMethodDecl>(Info.CurrentCall->Callee);
9488 return HandleLambdaCapture(
9489 Info, E, Result, MD, Info.CurrentCall->LambdaThisCaptureField,
9490 Info.CurrentCall->LambdaThisCaptureField->getType()->isPointerType());
9491 }
9492 return true;
9493 }
9494
9495 bool VisitCXXNewExpr(const CXXNewExpr *E);
9496
9497 bool VisitSourceLocExpr(const SourceLocExpr *E) {
9498 assert(!E->isIntType() && "SourceLocExpr isn't a pointer type?");
9499 APValue LValResult = E->EvaluateInContext(
9500 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
9501 Result.setFrom(Info.Ctx, LValResult);
9502 return true;
9503 }
9504
9505 bool VisitEmbedExpr(const EmbedExpr *E) {
9506 llvm::report_fatal_error("Not yet implemented for ExprConstant.cpp");
9507 return true;
9508 }
9509
9510 bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
9511 std::string ResultStr = E->ComputeName(Info.Ctx);
9512
9513 QualType CharTy = Info.Ctx.CharTy.withConst();
9514 APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
9515 ResultStr.size() + 1);
9516 QualType ArrayTy = Info.Ctx.getConstantArrayType(
9517 CharTy, Size, nullptr, ArraySizeModifier::Normal, 0);
9518
9519 StringLiteral *SL =
9520 StringLiteral::Create(Info.Ctx, ResultStr, StringLiteralKind::Ordinary,
9521 /*Pascal*/ false, ArrayTy, E->getLocation());
9522
9523 evaluateLValue(SL, Result);
9524 Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
9525 return true;
9526 }
9527
9528 // FIXME: Missing: @protocol, @selector
9529};
9530} // end anonymous namespace
9531
9532static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
9533 bool InvalidBaseOK) {
9534 assert(!E->isValueDependent());
9535 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
9536 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
9537}
9538
9539bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9540 if (E->getOpcode() != BO_Add &&
9541 E->getOpcode() != BO_Sub)
9542 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9543
9544 const Expr *PExp = E->getLHS();
9545 const Expr *IExp = E->getRHS();
9546 if (IExp->getType()->isPointerType())
9547 std::swap(PExp, IExp);
9548
9549 bool EvalPtrOK = evaluatePointer(PExp, Result);
9550 if (!EvalPtrOK && !Info.noteFailure())
9551 return false;
9552
9553 llvm::APSInt Offset;
9554 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
9555 return false;
9556
9557 if (E->getOpcode() == BO_Sub)
9558 negateAsSigned(Offset);
9559
9560 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
9561 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
9562}
9563
9564bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9565 return evaluateLValue(E->getSubExpr(), Result);
9566}
9567
9568// Is the provided decl 'std::source_location::current'?
9570 if (!FD)
9571 return false;
9572 const IdentifierInfo *FnII = FD->getIdentifier();
9573 if (!FnII || !FnII->isStr("current"))
9574 return false;
9575
9576 const auto *RD = dyn_cast<RecordDecl>(FD->getParent());
9577 if (!RD)
9578 return false;
9579
9580 const IdentifierInfo *ClassII = RD->getIdentifier();
9581 return RD->isInStdNamespace() && ClassII && ClassII->isStr("source_location");
9582}
9583
9584bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9585 const Expr *SubExpr = E->getSubExpr();
9586
9587 switch (E->getCastKind()) {
9588 default:
9589 break;
9590 case CK_BitCast:
9591 case CK_CPointerToObjCPointerCast:
9592 case CK_BlockPointerToObjCPointerCast:
9593 case CK_AnyPointerToBlockPointerCast:
9594 case CK_AddressSpaceConversion:
9595 if (!Visit(SubExpr))
9596 return false;
9597 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
9598 // permitted in constant expressions in C++11. Bitcasts from cv void* are
9599 // also static_casts, but we disallow them as a resolution to DR1312.
9600 if (!E->getType()->isVoidPointerType()) {
9601 // In some circumstances, we permit casting from void* to cv1 T*, when the
9602 // actual pointee object is actually a cv2 T.
9603 bool HasValidResult = !Result.InvalidBase && !Result.Designator.Invalid &&
9604 !Result.IsNullPtr;
9605 bool VoidPtrCastMaybeOK =
9606 Result.IsNullPtr ||
9607 (HasValidResult &&
9608 Info.Ctx.hasSimilarType(Result.Designator.getType(Info.Ctx),
9609 E->getType()->getPointeeType()));
9610 // 1. We'll allow it in std::allocator::allocate, and anything which that
9611 // calls.
9612 // 2. HACK 2022-03-28: Work around an issue with libstdc++'s
9613 // <source_location> header. Fixed in GCC 12 and later (2022-04-??).
9614 // We'll allow it in the body of std::source_location::current. GCC's
9615 // implementation had a parameter of type `void*`, and casts from
9616 // that back to `const __impl*` in its body.
9617 if (VoidPtrCastMaybeOK &&
9618 (Info.getStdAllocatorCaller("allocate") ||
9619 IsDeclSourceLocationCurrent(Info.CurrentCall->Callee) ||
9620 Info.getLangOpts().CPlusPlus26)) {
9621 // Permitted.
9622 } else {
9623 if (SubExpr->getType()->isVoidPointerType() &&
9624 Info.getLangOpts().CPlusPlus) {
9625 if (HasValidResult)
9626 CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
9627 << SubExpr->getType() << Info.getLangOpts().CPlusPlus26
9628 << Result.Designator.getType(Info.Ctx).getCanonicalType()
9629 << E->getType()->getPointeeType();
9630 else
9631 CCEDiag(E, diag::note_constexpr_invalid_cast)
9632 << 3 << SubExpr->getType();
9633 } else
9634 CCEDiag(E, diag::note_constexpr_invalid_cast)
9635 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9636 Result.Designator.setInvalid();
9637 }
9638 }
9639 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
9640 ZeroInitialization(E);
9641 return true;
9642
9643 case CK_DerivedToBase:
9644 case CK_UncheckedDerivedToBase:
9645 if (!evaluatePointer(E->getSubExpr(), Result))
9646 return false;
9647 if (!Result.Base && Result.Offset.isZero())
9648 return true;
9649
9650 // Now figure out the necessary offset to add to the base LV to get from
9651 // the derived class to the base class.
9652 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
9653 castAs<PointerType>()->getPointeeType(),
9654 Result);
9655
9656 case CK_BaseToDerived:
9657 if (!Visit(E->getSubExpr()))
9658 return false;
9659 if (!Result.Base && Result.Offset.isZero())
9660 return true;
9661 return HandleBaseToDerivedCast(Info, E, Result);
9662
9663 case CK_Dynamic:
9664 if (!Visit(E->getSubExpr()))
9665 return false;
9666 return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
9667
9668 case CK_NullToPointer:
9669 VisitIgnoredValue(E->getSubExpr());
9670 return ZeroInitialization(E);
9671
9672 case CK_IntegralToPointer: {
9673 CCEDiag(E, diag::note_constexpr_invalid_cast)
9674 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
9675
9676 APValue Value;
9677 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
9678 break;
9679
9680 if (Value.isInt()) {
9681 unsigned Size = Info.Ctx.getTypeSize(E->getType());
9682 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
9683 Result.Base = (Expr*)nullptr;
9684 Result.InvalidBase = false;
9685 Result.Offset = CharUnits::fromQuantity(N);
9686 Result.Designator.setInvalid();
9687 Result.IsNullPtr = false;
9688 return true;
9689 } else {
9690 // In rare instances, the value isn't an lvalue.
9691 // For example, when the value is the difference between the addresses of
9692 // two labels. We reject that as a constant expression because we can't
9693 // compute a valid offset to convert into a pointer.
9694 if (!Value.isLValue())
9695 return false;
9696
9697 // Cast is of an lvalue, no need to change value.
9698 Result.setFrom(Info.Ctx, Value);
9699 return true;
9700 }
9701 }
9702
9703 case CK_ArrayToPointerDecay: {
9704 if (SubExpr->isGLValue()) {
9705 if (!evaluateLValue(SubExpr, Result))
9706 return false;
9707 } else {
9708 APValue &Value = Info.CurrentCall->createTemporary(
9709 SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
9710 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
9711 return false;
9712 }
9713 // The result is a pointer to the first element of the array.
9714 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
9715 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
9716 Result.addArray(Info, E, CAT);
9717 else
9718 Result.addUnsizedArray(Info, E, AT->getElementType());
9719 return true;
9720 }
9721
9722 case CK_FunctionToPointerDecay:
9723 return evaluateLValue(SubExpr, Result);
9724
9725 case CK_LValueToRValue: {
9726 LValue LVal;
9727 if (!evaluateLValue(E->getSubExpr(), LVal))
9728 return false;
9729
9730 APValue RVal;
9731 // Note, we use the subexpression's type in order to retain cv-qualifiers.
9732 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
9733 LVal, RVal))
9734 return InvalidBaseOK &&
9735 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
9736 return Success(RVal, E);
9737 }
9738 }
9739
9740 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9741}
9742
9744 UnaryExprOrTypeTrait ExprKind) {
9745 // C++ [expr.alignof]p3:
9746 // When alignof is applied to a reference type, the result is the
9747 // alignment of the referenced type.
9748 T = T.getNonReferenceType();
9749
9750 if (T.getQualifiers().hasUnaligned())
9751 return CharUnits::One();
9752
9753 const bool AlignOfReturnsPreferred =
9754 Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
9755
9756 // __alignof is defined to return the preferred alignment.
9757 // Before 8, clang returned the preferred alignment for alignof and _Alignof
9758 // as well.
9759 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
9760 return Ctx.toCharUnitsFromBits(Ctx.getPreferredTypeAlign(T.getTypePtr()));
9761 // alignof and _Alignof are defined to return the ABI alignment.
9762 else if (ExprKind == UETT_AlignOf)
9763 return Ctx.getTypeAlignInChars(T.getTypePtr());
9764 else
9765 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
9766}
9767
9769 UnaryExprOrTypeTrait ExprKind) {
9770 E = E->IgnoreParens();
9771
9772 // The kinds of expressions that we have special-case logic here for
9773 // should be kept up to date with the special checks for those
9774 // expressions in Sema.
9775
9776 // alignof decl is always accepted, even if it doesn't make sense: we default
9777 // to 1 in those cases.
9778 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9779 return Ctx.getDeclAlign(DRE->getDecl(),
9780 /*RefAsPointee*/ true);
9781
9782 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
9783 return Ctx.getDeclAlign(ME->getMemberDecl(),
9784 /*RefAsPointee*/ true);
9785
9786 return GetAlignOfType(Ctx, E->getType(), ExprKind);
9787}
9788
9789static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
9790 if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
9791 return Info.Ctx.getDeclAlign(VD);
9792 if (const auto *E = Value.Base.dyn_cast<const Expr *>())
9793 return GetAlignOfExpr(Info.Ctx, E, UETT_AlignOf);
9794 return GetAlignOfType(Info.Ctx, Value.Base.getTypeInfoType(), UETT_AlignOf);
9795}
9796
9797/// Evaluate the value of the alignment argument to __builtin_align_{up,down},
9798/// __builtin_is_aligned and __builtin_assume_aligned.
9799static bool getAlignmentArgument(const Expr *E, QualType ForType,
9800 EvalInfo &Info, APSInt &Alignment) {
9801 if (!EvaluateInteger(E, Alignment, Info))
9802 return false;
9803 if (Alignment < 0 || !Alignment.isPowerOf2()) {
9804 Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
9805 return false;
9806 }
9807 unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
9808 APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
9809 if (APSInt::compareValues(Alignment, MaxValue) > 0) {
9810 Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
9811 << MaxValue << ForType << Alignment;
9812 return false;
9813 }
9814 // Ensure both alignment and source value have the same bit width so that we
9815 // don't assert when computing the resulting value.
9816 APSInt ExtAlignment =
9817 APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
9818 assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
9819 "Alignment should not be changed by ext/trunc");
9820 Alignment = ExtAlignment;
9821 assert(Alignment.getBitWidth() == SrcWidth);
9822 return true;
9823}
9824
9825// To be clear: this happily visits unsupported builtins. Better name welcomed.
9826bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
9827 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
9828 return true;
9829
9830 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
9831 return false;
9832
9833 Result.setInvalid(E);
9834 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
9835 Result.addUnsizedArray(Info, E, PointeeTy);
9836 return true;
9837}
9838
9839bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
9840 if (!IsConstantEvaluatedBuiltinCall(E))
9841 return visitNonBuiltinCallExpr(E);
9842 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
9843}
9844
9845// Determine if T is a character type for which we guarantee that
9846// sizeof(T) == 1.
9848 return T->isCharType() || T->isChar8Type();
9849}
9850
9851bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9852 unsigned BuiltinOp) {
9854 return Success(E);
9855
9856 switch (BuiltinOp) {
9857 case Builtin::BIaddressof:
9858 case Builtin::BI__addressof:
9859 case Builtin::BI__builtin_addressof:
9860 return evaluateLValue(E->getArg(0), Result);
9861 case Builtin::BI__builtin_assume_aligned: {
9862 // We need to be very careful here because: if the pointer does not have the
9863 // asserted alignment, then the behavior is undefined, and undefined
9864 // behavior is non-constant.
9865 if (!evaluatePointer(E->getArg(0), Result))
9866 return false;
9867
9868 LValue OffsetResult(Result);
9869 APSInt Alignment;
9870 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9871 Alignment))
9872 return false;
9873 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
9874
9875 if (E->getNumArgs() > 2) {
9876 APSInt Offset;
9877 if (!EvaluateInteger(E->getArg(2), Offset, Info))
9878 return false;
9879
9880 int64_t AdditionalOffset = -Offset.getZExtValue();
9881 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9882 }
9883
9884 // If there is a base object, then it must have the correct alignment.
9885 if (OffsetResult.Base) {
9886 CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9887
9888 if (BaseAlignment < Align) {
9889 Result.Designator.setInvalid();
9890 CCEDiag(E->getArg(0), diag::note_constexpr_baa_insufficient_alignment)
9891 << 0 << BaseAlignment.getQuantity() << Align.getQuantity();
9892 return false;
9893 }
9894 }
9895
9896 // The offset must also have the correct alignment.
9897 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9898 Result.Designator.setInvalid();
9899
9900 (OffsetResult.Base
9901 ? CCEDiag(E->getArg(0),
9902 diag::note_constexpr_baa_insufficient_alignment)
9903 << 1
9904 : CCEDiag(E->getArg(0),
9905 diag::note_constexpr_baa_value_insufficient_alignment))
9906 << OffsetResult.Offset.getQuantity() << Align.getQuantity();
9907 return false;
9908 }
9909
9910 return true;
9911 }
9912 case Builtin::BI__builtin_align_up:
9913 case Builtin::BI__builtin_align_down: {
9914 if (!evaluatePointer(E->getArg(0), Result))
9915 return false;
9916 APSInt Alignment;
9917 if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9918 Alignment))
9919 return false;
9920 CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9921 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9922 // For align_up/align_down, we can return the same value if the alignment
9923 // is known to be greater or equal to the requested value.
9924 if (PtrAlign.getQuantity() >= Alignment)
9925 return true;
9926
9927 // The alignment could be greater than the minimum at run-time, so we cannot
9928 // infer much about the resulting pointer value. One case is possible:
9929 // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9930 // can infer the correct index if the requested alignment is smaller than
9931 // the base alignment so we can perform the computation on the offset.
9932 if (BaseAlignment.getQuantity() >= Alignment) {
9933 assert(Alignment.getBitWidth() <= 64 &&
9934 "Cannot handle > 64-bit address-space");
9935 uint64_t Alignment64 = Alignment.getZExtValue();
9937 BuiltinOp == Builtin::BI__builtin_align_down
9938 ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9939 : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9940 Result.adjustOffset(NewOffset - Result.Offset);
9941 // TODO: diagnose out-of-bounds values/only allow for arrays?
9942 return true;
9943 }
9944 // Otherwise, we cannot constant-evaluate the result.
9945 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9946 << Alignment;
9947 return false;
9948 }
9949 case Builtin::BI__builtin_operator_new:
9950 return HandleOperatorNewCall(Info, E, Result);
9951 case Builtin::BI__builtin_launder:
9952 return evaluatePointer(E->getArg(0), Result);
9953 case Builtin::BIstrchr:
9954 case Builtin::BIwcschr:
9955 case Builtin::BImemchr:
9956 case Builtin::BIwmemchr:
9957 if (Info.getLangOpts().CPlusPlus11)
9958 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9959 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
9960 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
9961 else
9962 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9963 [[fallthrough]];
9964 case Builtin::BI__builtin_strchr:
9965 case Builtin::BI__builtin_wcschr:
9966 case Builtin::BI__builtin_memchr:
9967 case Builtin::BI__builtin_char_memchr:
9968 case Builtin::BI__builtin_wmemchr: {
9969 if (!Visit(E->getArg(0)))
9970 return false;
9971 APSInt Desired;
9972 if (!EvaluateInteger(E->getArg(1), Desired, Info))
9973 return false;
9974 uint64_t MaxLength = uint64_t(-1);
9975 if (BuiltinOp != Builtin::BIstrchr &&
9976 BuiltinOp != Builtin::BIwcschr &&
9977 BuiltinOp != Builtin::BI__builtin_strchr &&
9978 BuiltinOp != Builtin::BI__builtin_wcschr) {
9979 APSInt N;
9980 if (!EvaluateInteger(E->getArg(2), N, Info))
9981 return false;
9982 MaxLength = N.getZExtValue();
9983 }
9984 // We cannot find the value if there are no candidates to match against.
9985 if (MaxLength == 0u)
9986 return ZeroInitialization(E);
9987 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9988 Result.Designator.Invalid)
9989 return false;
9990 QualType CharTy = Result.Designator.getType(Info.Ctx);
9991 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9992 BuiltinOp == Builtin::BI__builtin_memchr;
9993 assert(IsRawByte ||
9994 Info.Ctx.hasSameUnqualifiedType(
9995 CharTy, E->getArg(0)->getType()->getPointeeType()));
9996 // Pointers to const void may point to objects of incomplete type.
9997 if (IsRawByte && CharTy->isIncompleteType()) {
9998 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9999 return false;
10000 }
10001 // Give up on byte-oriented matching against multibyte elements.
10002 // FIXME: We can compare the bytes in the correct order.
10003 if (IsRawByte && !isOneByteCharacterType(CharTy)) {
10004 Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
10005 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy;
10006 return false;
10007 }
10008 // Figure out what value we're actually looking for (after converting to
10009 // the corresponding unsigned type if necessary).
10010 uint64_t DesiredVal;
10011 bool StopAtNull = false;
10012 switch (BuiltinOp) {
10013 case Builtin::BIstrchr:
10014 case Builtin::BI__builtin_strchr:
10015 // strchr compares directly to the passed integer, and therefore
10016 // always fails if given an int that is not a char.
10017 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
10018 E->getArg(1)->getType(),
10019 Desired),
10020 Desired))
10021 return ZeroInitialization(E);
10022 StopAtNull = true;
10023 [[fallthrough]];
10024 case Builtin::BImemchr:
10025 case Builtin::BI__builtin_memchr:
10026 case Builtin::BI__builtin_char_memchr:
10027 // memchr compares by converting both sides to unsigned char. That's also
10028 // correct for strchr if we get this far (to cope with plain char being
10029 // unsigned in the strchr case).
10030 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
10031 break;
10032
10033 case Builtin::BIwcschr:
10034 case Builtin::BI__builtin_wcschr:
10035 StopAtNull = true;
10036 [[fallthrough]];
10037 case Builtin::BIwmemchr:
10038 case Builtin::BI__builtin_wmemchr:
10039 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
10040 DesiredVal = Desired.getZExtValue();
10041 break;
10042 }
10043
10044 for (; MaxLength; --MaxLength) {
10045 APValue Char;
10046 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
10047 !Char.isInt())
10048 return false;
10049 if (Char.getInt().getZExtValue() == DesiredVal)
10050 return true;
10051 if (StopAtNull && !Char.getInt())
10052 break;
10053 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
10054 return false;
10055 }
10056 // Not found: return nullptr.
10057 return ZeroInitialization(E);
10058 }
10059
10060 case Builtin::BImemcpy:
10061 case Builtin::BImemmove:
10062 case Builtin::BIwmemcpy:
10063 case Builtin::BIwmemmove:
10064 if (Info.getLangOpts().CPlusPlus11)
10065 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10066 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
10067 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
10068 else
10069 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10070 [[fallthrough]];
10071 case Builtin::BI__builtin_memcpy:
10072 case Builtin::BI__builtin_memmove:
10073 case Builtin::BI__builtin_wmemcpy:
10074 case Builtin::BI__builtin_wmemmove: {
10075 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
10076 BuiltinOp == Builtin::BIwmemmove ||
10077 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
10078 BuiltinOp == Builtin::BI__builtin_wmemmove;
10079 bool Move = BuiltinOp == Builtin::BImemmove ||
10080 BuiltinOp == Builtin::BIwmemmove ||
10081 BuiltinOp == Builtin::BI__builtin_memmove ||
10082 BuiltinOp == Builtin::BI__builtin_wmemmove;
10083
10084 // The result of mem* is the first argument.
10085 if (!Visit(E->getArg(0)))
10086 return false;
10087 LValue Dest = Result;
10088
10089 LValue Src;
10090 if (!EvaluatePointer(E->getArg(1), Src, Info))
10091 return false;
10092
10093 APSInt N;
10094 if (!EvaluateInteger(E->getArg(2), N, Info))
10095 return false;
10096 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
10097
10098 // If the size is zero, we treat this as always being a valid no-op.
10099 // (Even if one of the src and dest pointers is null.)
10100 if (!N)
10101 return true;
10102
10103 // Otherwise, if either of the operands is null, we can't proceed. Don't
10104 // try to determine the type of the copied objects, because there aren't
10105 // any.
10106 if (!Src.Base || !Dest.Base) {
10107 APValue Val;
10108 (!Src.Base ? Src : Dest).moveInto(Val);
10109 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
10110 << Move << WChar << !!Src.Base
10111 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
10112 return false;
10113 }
10114 if (Src.Designator.Invalid || Dest.Designator.Invalid)
10115 return false;
10116
10117 // We require that Src and Dest are both pointers to arrays of
10118 // trivially-copyable type. (For the wide version, the designator will be
10119 // invalid if the designated object is not a wchar_t.)
10120 QualType T = Dest.Designator.getType(Info.Ctx);
10121 QualType SrcT = Src.Designator.getType(Info.Ctx);
10122 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
10123 // FIXME: Consider using our bit_cast implementation to support this.
10124 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
10125 return false;
10126 }
10127 if (T->isIncompleteType()) {
10128 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
10129 return false;
10130 }
10131 if (!T.isTriviallyCopyableType(Info.Ctx)) {
10132 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
10133 return false;
10134 }
10135
10136 // Figure out how many T's we're copying.
10137 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
10138 if (TSize == 0)
10139 return false;
10140 if (!WChar) {
10141 uint64_t Remainder;
10142 llvm::APInt OrigN = N;
10143 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
10144 if (Remainder) {
10145 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10146 << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
10147 << (unsigned)TSize;
10148 return false;
10149 }
10150 }
10151
10152 // Check that the copying will remain within the arrays, just so that we
10153 // can give a more meaningful diagnostic. This implicitly also checks that
10154 // N fits into 64 bits.
10155 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
10156 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
10157 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
10158 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
10159 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
10160 << toString(N, 10, /*Signed*/false);
10161 return false;
10162 }
10163 uint64_t NElems = N.getZExtValue();
10164 uint64_t NBytes = NElems * TSize;
10165
10166 // Check for overlap.
10167 int Direction = 1;
10168 if (HasSameBase(Src, Dest)) {
10169 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
10170 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
10171 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
10172 // Dest is inside the source region.
10173 if (!Move) {
10174 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10175 return false;
10176 }
10177 // For memmove and friends, copy backwards.
10178 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
10179 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
10180 return false;
10181 Direction = -1;
10182 } else if (!Move && SrcOffset >= DestOffset &&
10183 SrcOffset - DestOffset < NBytes) {
10184 // Src is inside the destination region for memcpy: invalid.
10185 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
10186 return false;
10187 }
10188 }
10189
10190 while (true) {
10191 APValue Val;
10192 // FIXME: Set WantObjectRepresentation to true if we're copying a
10193 // char-like type?
10194 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
10195 !handleAssignment(Info, E, Dest, T, Val))
10196 return false;
10197 // Do not iterate past the last element; if we're copying backwards, that
10198 // might take us off the start of the array.
10199 if (--NElems == 0)
10200 return true;
10201 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
10202 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
10203 return false;
10204 }
10205 }
10206
10207 default:
10208 return false;
10209 }
10210}
10211
10212static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10213 APValue &Result, const InitListExpr *ILE,
10214 QualType AllocType);
10215static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10216 APValue &Result,
10217 const CXXConstructExpr *CCE,
10218 QualType AllocType);
10219
10220bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
10221 if (!Info.getLangOpts().CPlusPlus20)
10222 Info.CCEDiag(E, diag::note_constexpr_new);
10223
10224 // We cannot speculatively evaluate a delete expression.
10225 if (Info.SpeculativeEvaluationDepth)
10226 return false;
10227
10228 FunctionDecl *OperatorNew = E->getOperatorNew();
10229 QualType AllocType = E->getAllocatedType();
10230 QualType TargetType = AllocType;
10231
10232 bool IsNothrow = false;
10233 bool IsPlacement = false;
10234
10235 if (E->getNumPlacementArgs() == 1 &&
10236 E->getPlacementArg(0)->getType()->isNothrowT()) {
10237 // The only new-placement list we support is of the form (std::nothrow).
10238 //
10239 // FIXME: There is no restriction on this, but it's not clear that any
10240 // other form makes any sense. We get here for cases such as:
10241 //
10242 // new (std::align_val_t{N}) X(int)
10243 //
10244 // (which should presumably be valid only if N is a multiple of
10245 // alignof(int), and in any case can't be deallocated unless N is
10246 // alignof(X) and X has new-extended alignment).
10247 LValue Nothrow;
10248 if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
10249 return false;
10250 IsNothrow = true;
10251 } else if (OperatorNew->isReservedGlobalPlacementOperator()) {
10252 if (Info.CurrentCall->isStdFunction() || Info.getLangOpts().CPlusPlus26 ||
10253 (Info.CurrentCall->CanEvalMSConstexpr &&
10254 OperatorNew->hasAttr<MSConstexprAttr>())) {
10255 if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
10256 return false;
10257 if (Result.Designator.Invalid)
10258 return false;
10259 TargetType = E->getPlacementArg(0)->getType();
10260 IsPlacement = true;
10261 } else {
10262 Info.FFDiag(E, diag::note_constexpr_new_placement)
10263 << /*C++26 feature*/ 1 << E->getSourceRange();
10264 return false;
10265 }
10266 } else if (E->getNumPlacementArgs()) {
10267 Info.FFDiag(E, diag::note_constexpr_new_placement)
10268 << /*Unsupported*/ 0 << E->getSourceRange();
10269 return false;
10270 } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
10271 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
10272 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
10273 return false;
10274 }
10275
10276 const Expr *Init = E->getInitializer();
10277 const InitListExpr *ResizedArrayILE = nullptr;
10278 const CXXConstructExpr *ResizedArrayCCE = nullptr;
10279 bool ValueInit = false;
10280
10281 if (std::optional<const Expr *> ArraySize = E->getArraySize()) {
10282 const Expr *Stripped = *ArraySize;
10283 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
10284 Stripped = ICE->getSubExpr())
10285 if (ICE->getCastKind() != CK_NoOp &&
10286 ICE->getCastKind() != CK_IntegralCast)
10287 break;
10288
10289 llvm::APSInt ArrayBound;
10290 if (!EvaluateInteger(Stripped, ArrayBound, Info))
10291 return false;
10292
10293 // C++ [expr.new]p9:
10294 // The expression is erroneous if:
10295 // -- [...] its value before converting to size_t [or] applying the
10296 // second standard conversion sequence is less than zero
10297 if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
10298 if (IsNothrow)
10299 return ZeroInitialization(E);
10300
10301 Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
10302 << ArrayBound << (*ArraySize)->getSourceRange();
10303 return false;
10304 }
10305
10306 // -- its value is such that the size of the allocated object would
10307 // exceed the implementation-defined limit
10308 if (!Info.CheckArraySize(ArraySize.value()->getExprLoc(),
10310 Info.Ctx, AllocType, ArrayBound),
10311 ArrayBound.getZExtValue(), /*Diag=*/!IsNothrow)) {
10312 if (IsNothrow)
10313 return ZeroInitialization(E);
10314 return false;
10315 }
10316
10317 // -- the new-initializer is a braced-init-list and the number of
10318 // array elements for which initializers are provided [...]
10319 // exceeds the number of elements to initialize
10320 if (!Init) {
10321 // No initialization is performed.
10322 } else if (isa<CXXScalarValueInitExpr>(Init) ||
10323 isa<ImplicitValueInitExpr>(Init)) {
10324 ValueInit = true;
10325 } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
10326 ResizedArrayCCE = CCE;
10327 } else {
10328 auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
10329 assert(CAT && "unexpected type for array initializer");
10330
10331 unsigned Bits =
10332 std::max(CAT->getSizeBitWidth(), ArrayBound.getBitWidth());
10333 llvm::APInt InitBound = CAT->getSize().zext(Bits);
10334 llvm::APInt AllocBound = ArrayBound.zext(Bits);
10335 if (InitBound.ugt(AllocBound)) {
10336 if (IsNothrow)
10337 return ZeroInitialization(E);
10338
10339 Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
10340 << toString(AllocBound, 10, /*Signed=*/false)
10341 << toString(InitBound, 10, /*Signed=*/false)
10342 << (*ArraySize)->getSourceRange();
10343 return false;
10344 }
10345
10346 // If the sizes differ, we must have an initializer list, and we need
10347 // special handling for this case when we initialize.
10348 if (InitBound != AllocBound)
10349 ResizedArrayILE = cast<InitListExpr>(Init);
10350 }
10351
10352 AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
10353 ArraySizeModifier::Normal, 0);
10354 } else {
10355 assert(!AllocType->isArrayType() &&
10356 "array allocation with non-array new");
10357 }
10358
10359 APValue *Val;
10360 if (IsPlacement) {
10362 struct FindObjectHandler {
10363 EvalInfo &Info;
10364 const Expr *E;
10365 QualType AllocType;
10366 const AccessKinds AccessKind;
10367 APValue *Value;
10368
10369 typedef bool result_type;
10370 bool failed() { return false; }
10371 bool found(APValue &Subobj, QualType SubobjType) {
10372 // FIXME: Reject the cases where [basic.life]p8 would not permit the
10373 // old name of the object to be used to name the new object.
10374 unsigned SubobjectSize = 1;
10375 unsigned AllocSize = 1;
10376 if (auto *CAT = dyn_cast<ConstantArrayType>(AllocType))
10377 AllocSize = CAT->getZExtSize();
10378 if (auto *CAT = dyn_cast<ConstantArrayType>(SubobjType))
10379 SubobjectSize = CAT->getZExtSize();
10380 if (SubobjectSize < AllocSize ||
10381 !Info.Ctx.hasSimilarType(Info.Ctx.getBaseElementType(SubobjType),
10382 Info.Ctx.getBaseElementType(AllocType))) {
10383 Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type)
10384 << SubobjType << AllocType;
10385 return false;
10386 }
10387 Value = &Subobj;
10388 return true;
10389 }
10390 bool found(APSInt &Value, QualType SubobjType) {
10391 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10392 return false;
10393 }
10394 bool found(APFloat &Value, QualType SubobjType) {
10395 Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
10396 return false;
10397 }
10398 } Handler = {Info, E, AllocType, AK, nullptr};
10399
10400 CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
10401 if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
10402 return false;
10403
10404 Val = Handler.Value;
10405
10406 // [basic.life]p1:
10407 // The lifetime of an object o of type T ends when [...] the storage
10408 // which the object occupies is [...] reused by an object that is not
10409 // nested within o (6.6.2).
10410 *Val = APValue();
10411 } else {
10412 // Perform the allocation and obtain a pointer to the resulting object.
10413 Val = Info.createHeapAlloc(E, AllocType, Result);
10414 if (!Val)
10415 return false;
10416 }
10417
10418 if (ValueInit) {
10419 ImplicitValueInitExpr VIE(AllocType);
10420 if (!EvaluateInPlace(*Val, Info, Result, &VIE))
10421 return false;
10422 } else if (ResizedArrayILE) {
10423 if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
10424 AllocType))
10425 return false;
10426 } else if (ResizedArrayCCE) {
10427 if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
10428 AllocType))
10429 return false;
10430 } else if (Init) {
10431 if (!EvaluateInPlace(*Val, Info, Result, Init))
10432 return false;
10433 } else if (!handleDefaultInitValue(AllocType, *Val)) {
10434 return false;
10435 }
10436
10437 // Array new returns a pointer to the first element, not a pointer to the
10438 // array.
10439 if (auto *AT = AllocType->getAsArrayTypeUnsafe())
10440 Result.addArray(Info, E, cast<ConstantArrayType>(AT));
10441
10442 return true;
10443}
10444//===----------------------------------------------------------------------===//
10445// Member Pointer Evaluation
10446//===----------------------------------------------------------------------===//
10447
10448namespace {
10449class MemberPointerExprEvaluator
10450 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
10451 MemberPtr &Result;
10452
10453 bool Success(const ValueDecl *D) {
10454 Result = MemberPtr(D);
10455 return true;
10456 }
10457public:
10458
10459 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
10460 : ExprEvaluatorBaseTy(Info), Result(Result) {}
10461
10462 bool Success(const APValue &V, const Expr *E) {
10463 Result.setFrom(V);
10464 return true;
10465 }
10466 bool ZeroInitialization(const Expr *E) {
10467 return Success((const ValueDecl*)nullptr);
10468 }
10469
10470 bool VisitCastExpr(const CastExpr *E);
10471 bool VisitUnaryAddrOf(const UnaryOperator *E);
10472};
10473} // end anonymous namespace
10474
10475static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
10476 EvalInfo &Info) {
10477 assert(!E->isValueDependent());
10478 assert(E->isPRValue() && E->getType()->isMemberPointerType());
10479 return MemberPointerExprEvaluator(Info, Result).Visit(E);
10480}
10481
10482bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
10483 switch (E->getCastKind()) {
10484 default:
10485 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10486
10487 case CK_NullToMemberPointer:
10488 VisitIgnoredValue(E->getSubExpr());
10489 return ZeroInitialization(E);
10490
10491 case CK_BaseToDerivedMemberPointer: {
10492 if (!Visit(E->getSubExpr()))
10493 return false;
10494 if (E->path_empty())
10495 return true;
10496 // Base-to-derived member pointer casts store the path in derived-to-base
10497 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
10498 // the wrong end of the derived->base arc, so stagger the path by one class.
10499 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
10500 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
10501 PathI != PathE; ++PathI) {
10502 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10503 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
10504 if (!Result.castToDerived(Derived))
10505 return Error(E);
10506 }
10507 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
10508 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
10509 return Error(E);
10510 return true;
10511 }
10512
10513 case CK_DerivedToBaseMemberPointer:
10514 if (!Visit(E->getSubExpr()))
10515 return false;
10516 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10517 PathE = E->path_end(); PathI != PathE; ++PathI) {
10518 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
10519 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10520 if (!Result.castToBase(Base))
10521 return Error(E);
10522 }
10523 return true;
10524 }
10525}
10526
10527bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
10528 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
10529 // member can be formed.
10530 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
10531}
10532
10533//===----------------------------------------------------------------------===//
10534// Record Evaluation
10535//===----------------------------------------------------------------------===//
10536
10537namespace {
10538 class RecordExprEvaluator
10539 : public ExprEvaluatorBase<RecordExprEvaluator> {
10540 const LValue &This;
10541 APValue &Result;
10542 public:
10543
10544 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
10545 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
10546
10547 bool Success(const APValue &V, const Expr *E) {
10548 Result = V;
10549 return true;
10550 }
10551 bool ZeroInitialization(const Expr *E) {
10552 return ZeroInitialization(E, E->getType());
10553 }
10554 bool ZeroInitialization(const Expr *E, QualType T);
10555
10556 bool VisitCallExpr(const CallExpr *E) {
10557 return handleCallExpr(E, Result, &This);
10558 }
10559 bool VisitCastExpr(const CastExpr *E);
10560 bool VisitInitListExpr(const InitListExpr *E);
10561 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10562 return VisitCXXConstructExpr(E, E->getType());
10563 }
10564 bool VisitLambdaExpr(const LambdaExpr *E);
10565 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
10566 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
10567 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
10568 bool VisitBinCmp(const BinaryOperator *E);
10569 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
10570 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
10571 ArrayRef<Expr *> Args);
10572 };
10573}
10574
10575/// Perform zero-initialization on an object of non-union class type.
10576/// C++11 [dcl.init]p5:
10577/// To zero-initialize an object or reference of type T means:
10578/// [...]
10579/// -- if T is a (possibly cv-qualified) non-union class type,
10580/// each non-static data member and each base-class subobject is
10581/// zero-initialized
10582static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
10583 const RecordDecl *RD,
10584 const LValue &This, APValue &Result) {
10585 assert(!RD->isUnion() && "Expected non-union class type");
10586 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
10587 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
10588 std::distance(RD->field_begin(), RD->field_end()));
10589
10590 if (RD->isInvalidDecl()) return false;
10591 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10592
10593 if (CD) {
10594 unsigned Index = 0;
10596 End = CD->bases_end(); I != End; ++I, ++Index) {
10597 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
10598 LValue Subobject = This;
10599 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
10600 return false;
10601 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
10602 Result.getStructBase(Index)))
10603 return false;
10604 }
10605 }
10606
10607 for (const auto *I : RD->fields()) {
10608 // -- if T is a reference type, no initialization is performed.
10609 if (I->isUnnamedBitField() || I->getType()->isReferenceType())
10610 continue;
10611
10612 LValue Subobject = This;
10613 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
10614 return false;
10615
10616 ImplicitValueInitExpr VIE(I->getType());
10617 if (!EvaluateInPlace(
10618 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
10619 return false;
10620 }
10621
10622 return true;
10623}
10624
10625bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
10626 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
10627 if (RD->isInvalidDecl()) return false;
10628 if (RD->isUnion()) {
10629 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
10630 // object's first non-static named data member is zero-initialized
10632 while (I != RD->field_end() && (*I)->isUnnamedBitField())
10633 ++I;
10634 if (I == RD->field_end()) {
10635 Result = APValue((const FieldDecl*)nullptr);
10636 return true;
10637 }
10638
10639 LValue Subobject = This;
10640 if (!HandleLValueMember(Info, E, Subobject, *I))
10641 return false;
10642 Result = APValue(*I);
10643 ImplicitValueInitExpr VIE(I->getType());
10644 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
10645 }
10646
10647 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
10648 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
10649 return false;
10650 }
10651
10652 return HandleClassZeroInitialization(Info, E, RD, This, Result);
10653}
10654
10655bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
10656 switch (E->getCastKind()) {
10657 default:
10658 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10659
10660 case CK_ConstructorConversion:
10661 return Visit(E->getSubExpr());
10662
10663 case CK_DerivedToBase:
10664 case CK_UncheckedDerivedToBase: {
10665 APValue DerivedObject;
10666 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
10667 return false;
10668 if (!DerivedObject.isStruct())
10669 return Error(E->getSubExpr());
10670
10671 // Derived-to-base rvalue conversion: just slice off the derived part.
10672 APValue *Value = &DerivedObject;
10673 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
10674 for (CastExpr::path_const_iterator PathI = E->path_begin(),
10675 PathE = E->path_end(); PathI != PathE; ++PathI) {
10676 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
10677 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
10678 Value = &Value->getStructBase(getBaseIndex(RD, Base));
10679 RD = Base;
10680 }
10681 Result = *Value;
10682 return true;
10683 }
10684 }
10685}
10686
10687bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10688 if (E->isTransparent())
10689 return Visit(E->getInit(0));
10690 return VisitCXXParenListOrInitListExpr(E, E->inits());
10691}
10692
10693bool RecordExprEvaluator::VisitCXXParenListOrInitListExpr(
10694 const Expr *ExprToVisit, ArrayRef<Expr *> Args) {
10695 const RecordDecl *RD =
10696 ExprToVisit->getType()->castAs<RecordType>()->getDecl();
10697 if (RD->isInvalidDecl()) return false;
10698 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
10699 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
10700
10701 EvalInfo::EvaluatingConstructorRAII EvalObj(
10702 Info,
10703 ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
10704 CXXRD && CXXRD->getNumBases());
10705
10706 if (RD->isUnion()) {
10707 const FieldDecl *Field;
10708 if (auto *ILE = dyn_cast<InitListExpr>(ExprToVisit)) {
10709 Field = ILE->getInitializedFieldInUnion();
10710 } else if (auto *PLIE = dyn_cast<CXXParenListInitExpr>(ExprToVisit)) {
10711 Field = PLIE->getInitializedFieldInUnion();
10712 } else {
10713 llvm_unreachable(
10714 "Expression is neither an init list nor a C++ paren list");
10715 }
10716
10717 Result = APValue(Field);
10718 if (!Field)
10719 return true;
10720
10721 // If the initializer list for a union does not contain any elements, the
10722 // first element of the union is value-initialized.
10723 // FIXME: The element should be initialized from an initializer list.
10724 // Is this difference ever observable for initializer lists which
10725 // we don't build?
10726 ImplicitValueInitExpr VIE(Field->getType());
10727 const Expr *InitExpr = Args.empty() ? &VIE : Args[0];
10728
10729 LValue Subobject = This;
10730 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
10731 return false;
10732
10733 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10734 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10735 isa<CXXDefaultInitExpr>(InitExpr));
10736
10737 if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
10738 if (Field->isBitField())
10739 return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
10740 Field);
10741 return true;
10742 }
10743
10744 return false;
10745 }
10746
10747 if (!Result.hasValue())
10748 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
10749 std::distance(RD->field_begin(), RD->field_end()));
10750 unsigned ElementNo = 0;
10751 bool Success = true;
10752
10753 // Initialize base classes.
10754 if (CXXRD && CXXRD->getNumBases()) {
10755 for (const auto &Base : CXXRD->bases()) {
10756 assert(ElementNo < Args.size() && "missing init for base class");
10757 const Expr *Init = Args[ElementNo];
10758
10759 LValue Subobject = This;
10760 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
10761 return false;
10762
10763 APValue &FieldVal = Result.getStructBase(ElementNo);
10764 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
10765 if (!Info.noteFailure())
10766 return false;
10767 Success = false;
10768 }
10769 ++ElementNo;
10770 }
10771
10772 EvalObj.finishedConstructingBases();
10773 }
10774
10775 // Initialize members.
10776 for (const auto *Field : RD->fields()) {
10777 // Anonymous bit-fields are not considered members of the class for
10778 // purposes of aggregate initialization.
10779 if (Field->isUnnamedBitField())
10780 continue;
10781
10782 LValue Subobject = This;
10783
10784 bool HaveInit = ElementNo < Args.size();
10785
10786 // FIXME: Diagnostics here should point to the end of the initializer
10787 // list, not the start.
10788 if (!HandleLValueMember(Info, HaveInit ? Args[ElementNo] : ExprToVisit,
10789 Subobject, Field, &Layout))
10790 return false;
10791
10792 // Perform an implicit value-initialization for members beyond the end of
10793 // the initializer list.
10794 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
10795 const Expr *Init = HaveInit ? Args[ElementNo++] : &VIE;
10796
10797 if (Field->getType()->isIncompleteArrayType()) {
10798 if (auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType())) {
10799 if (!CAT->isZeroSize()) {
10800 // Bail out for now. This might sort of "work", but the rest of the
10801 // code isn't really prepared to handle it.
10802 Info.FFDiag(Init, diag::note_constexpr_unsupported_flexible_array);
10803 return false;
10804 }
10805 }
10806 }
10807
10808 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
10809 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
10810 isa<CXXDefaultInitExpr>(Init));
10811
10812 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10813 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
10814 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
10815 FieldVal, Field))) {
10816 if (!Info.noteFailure())
10817 return false;
10818 Success = false;
10819 }
10820 }
10821
10822 EvalObj.finishedConstructingFields();
10823
10824 return Success;
10825}
10826
10827bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10828 QualType T) {
10829 // Note that E's type is not necessarily the type of our class here; we might
10830 // be initializing an array element instead.
10831 const CXXConstructorDecl *FD = E->getConstructor();
10832 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
10833
10834 bool ZeroInit = E->requiresZeroInitialization();
10835 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
10836 // If we've already performed zero-initialization, we're already done.
10837 if (Result.hasValue())
10838 return true;
10839
10840 if (ZeroInit)
10841 return ZeroInitialization(E, T);
10842
10843 return handleDefaultInitValue(T, Result);
10844 }
10845
10846 const FunctionDecl *Definition = nullptr;
10847 auto Body = FD->getBody(Definition);
10848
10849 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10850 return false;
10851
10852 // Avoid materializing a temporary for an elidable copy/move constructor.
10853 if (E->isElidable() && !ZeroInit) {
10854 // FIXME: This only handles the simplest case, where the source object
10855 // is passed directly as the first argument to the constructor.
10856 // This should also handle stepping though implicit casts and
10857 // and conversion sequences which involve two steps, with a
10858 // conversion operator followed by a converting constructor.
10859 const Expr *SrcObj = E->getArg(0);
10860 assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
10861 assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
10862 if (const MaterializeTemporaryExpr *ME =
10863 dyn_cast<MaterializeTemporaryExpr>(SrcObj))
10864 return Visit(ME->getSubExpr());
10865 }
10866
10867 if (ZeroInit && !ZeroInitialization(E, T))
10868 return false;
10869
10870 auto Args = llvm::ArrayRef(E->getArgs(), E->getNumArgs());
10871 return HandleConstructorCall(E, This, Args,
10872 cast<CXXConstructorDecl>(Definition), Info,
10873 Result);
10874}
10875
10876bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
10877 const CXXInheritedCtorInitExpr *E) {
10878 if (!Info.CurrentCall) {
10879 assert(Info.checkingPotentialConstantExpression());
10880 return false;
10881 }
10882
10883 const CXXConstructorDecl *FD = E->getConstructor();
10884 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
10885 return false;
10886
10887 const FunctionDecl *Definition = nullptr;
10888 auto Body = FD->getBody(Definition);
10889
10890 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
10891 return false;
10892
10893 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
10894 cast<CXXConstructorDecl>(Definition), Info,
10895 Result);
10896}
10897
10898bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
10901 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
10902
10903 LValue Array;
10904 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
10905 return false;
10906
10907 assert(ArrayType && "unexpected type for array initializer");
10908
10909 // Get a pointer to the first element of the array.
10910 Array.addArray(Info, E, ArrayType);
10911
10912 // FIXME: What if the initializer_list type has base classes, etc?
10913 Result = APValue(APValue::UninitStruct(), 0, 2);
10914 Array.moveInto(Result.getStructField(0));
10915
10916 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10917 RecordDecl::field_iterator Field = Record->field_begin();
10918 assert(Field != Record->field_end() &&
10919 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10921 "Expected std::initializer_list first field to be const E *");
10922 ++Field;
10923 assert(Field != Record->field_end() &&
10924 "Expected std::initializer_list to have two fields");
10925
10926 if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType())) {
10927 // Length.
10928 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10929 } else {
10930 // End pointer.
10931 assert(Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10933 "Expected std::initializer_list second field to be const E *");
10934 if (!HandleLValueArrayAdjustment(Info, E, Array,
10936 ArrayType->getZExtSize()))
10937 return false;
10938 Array.moveInto(Result.getStructField(1));
10939 }
10940
10941 assert(++Field == Record->field_end() &&
10942 "Expected std::initializer_list to only have two fields");
10943
10944 return true;
10945}
10946
10947bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10948 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10949 if (ClosureClass->isInvalidDecl())
10950 return false;
10951
10952 const size_t NumFields =
10953 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10954
10955 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10956 E->capture_init_end()) &&
10957 "The number of lambda capture initializers should equal the number of "
10958 "fields within the closure type");
10959
10960 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10961 // Iterate through all the lambda's closure object's fields and initialize
10962 // them.
10963 auto *CaptureInitIt = E->capture_init_begin();
10964 bool Success = true;
10965 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10966 for (const auto *Field : ClosureClass->fields()) {
10967 assert(CaptureInitIt != E->capture_init_end());
10968 // Get the initializer for this field
10969 Expr *const CurFieldInit = *CaptureInitIt++;
10970
10971 // If there is no initializer, either this is a VLA or an error has
10972 // occurred.
10973 if (!CurFieldInit)
10974 return Error(E);
10975
10976 LValue Subobject = This;
10977
10978 if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10979 return false;
10980
10981 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10982 if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10983 if (!Info.keepEvaluatingAfterFailure())
10984 return false;
10985 Success = false;
10986 }
10987 }
10988 return Success;
10989}
10990
10991static bool EvaluateRecord(const Expr *E, const LValue &This,
10992 APValue &Result, EvalInfo &Info) {
10993 assert(!E->isValueDependent());
10994 assert(E->isPRValue() && E->getType()->isRecordType() &&
10995 "can't evaluate expression as a record rvalue");
10996 return RecordExprEvaluator(Info, This, Result).Visit(E);
10997}
10998
10999//===----------------------------------------------------------------------===//
11000// Temporary Evaluation
11001//
11002// Temporaries are represented in the AST as rvalues, but generally behave like
11003// lvalues. The full-object of which the temporary is a subobject is implicitly
11004// materialized so that a reference can bind to it.
11005//===----------------------------------------------------------------------===//
11006namespace {
11007class TemporaryExprEvaluator
11008 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
11009public:
11010 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
11011 LValueExprEvaluatorBaseTy(Info, Result, false) {}
11012
11013 /// Visit an expression which constructs the value of this temporary.
11014 bool VisitConstructExpr(const Expr *E) {
11015 APValue &Value = Info.CurrentCall->createTemporary(
11016 E, E->getType(), ScopeKind::FullExpression, Result);
11017 return EvaluateInPlace(Value, Info, Result, E);
11018 }
11019
11020 bool VisitCastExpr(const CastExpr *E) {
11021 switch (E->getCastKind()) {
11022 default:
11023 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
11024
11025 case CK_ConstructorConversion:
11026 return VisitConstructExpr(E->getSubExpr());
11027 }
11028 }
11029 bool VisitInitListExpr(const InitListExpr *E) {
11030 return VisitConstructExpr(E);
11031 }
11032 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
11033 return VisitConstructExpr(E);
11034 }
11035 bool VisitCallExpr(const CallExpr *E) {
11036 return VisitConstructExpr(E);
11037 }
11038 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
11039 return VisitConstructExpr(E);
11040 }
11041 bool VisitLambdaExpr(const LambdaExpr *E) {
11042 return VisitConstructExpr(E);
11043 }
11044};
11045} // end anonymous namespace
11046
11047/// Evaluate an expression of record type as a temporary.
11048static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
11049 assert(!E->isValueDependent());
11050 assert(E->isPRValue() && E->getType()->isRecordType());
11051 return TemporaryExprEvaluator(Info, Result).Visit(E);
11052}
11053
11054//===----------------------------------------------------------------------===//
11055// Vector Evaluation
11056//===----------------------------------------------------------------------===//
11057
11058namespace {
11059 class VectorExprEvaluator
11060 : public ExprEvaluatorBase<VectorExprEvaluator> {
11061 APValue &Result;
11062 public:
11063
11064 VectorExprEvaluator(EvalInfo &info, APValue &Result)
11065 : ExprEvaluatorBaseTy(info), Result(Result) {}
11066
11067 bool Success(ArrayRef<APValue> V, const Expr *E) {
11068 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
11069 // FIXME: remove this APValue copy.
11070 Result = APValue(V.data(), V.size());
11071 return true;
11072 }
11073 bool Success(const APValue &V, const Expr *E) {
11074 assert(V.isVector());
11075 Result = V;
11076 return true;
11077 }
11078 bool ZeroInitialization(const Expr *E);
11079
11080 bool VisitUnaryReal(const UnaryOperator *E)
11081 { return Visit(E->getSubExpr()); }
11082 bool VisitCastExpr(const CastExpr* E);
11083 bool VisitInitListExpr(const InitListExpr *E);
11084 bool VisitUnaryImag(const UnaryOperator *E);
11085 bool VisitBinaryOperator(const BinaryOperator *E);
11086 bool VisitUnaryOperator(const UnaryOperator *E);
11087 bool VisitCallExpr(const CallExpr *E);
11088 bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
11089 bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
11090
11091 // FIXME: Missing: conditional operator (for GNU
11092 // conditional select), ExtVectorElementExpr
11093 };
11094} // end anonymous namespace
11095
11096static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
11097 assert(E->isPRValue() && E->getType()->isVectorType() &&
11098 "not a vector prvalue");
11099 return VectorExprEvaluator(Info, Result).Visit(E);
11100}
11101
11102bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
11103 const VectorType *VTy = E->getType()->castAs<VectorType>();
11104 unsigned NElts = VTy->getNumElements();
11105
11106 const Expr *SE = E->getSubExpr();
11107 QualType SETy = SE->getType();
11108
11109 switch (E->getCastKind()) {
11110 case CK_VectorSplat: {
11111 APValue Val = APValue();
11112 if (SETy->isIntegerType()) {
11113 APSInt IntResult;
11114 if (!EvaluateInteger(SE, IntResult, Info))
11115 return false;
11116 Val = APValue(std::move(IntResult));
11117 } else if (SETy->isRealFloatingType()) {
11118 APFloat FloatResult(0.0);
11119 if (!EvaluateFloat(SE, FloatResult, Info))
11120 return false;
11121 Val = APValue(std::move(FloatResult));
11122 } else {
11123 return Error(E);
11124 }
11125
11126 // Splat and create vector APValue.
11127 SmallVector<APValue, 4> Elts(NElts, Val);
11128 return Success(Elts, E);
11129 }
11130 case CK_BitCast: {
11131 APValue SVal;
11132 if (!Evaluate(SVal, Info, SE))
11133 return false;
11134
11135 if (!SVal.isInt() && !SVal.isFloat() && !SVal.isVector()) {
11136 // Give up if the input isn't an int, float, or vector. For example, we
11137 // reject "(v4i16)(intptr_t)&a".
11138 Info.FFDiag(E, diag::note_constexpr_invalid_cast)
11139 << 2 << Info.Ctx.getLangOpts().CPlusPlus;
11140 return false;
11141 }
11142
11143 if (!handleRValueToRValueBitCast(Info, Result, SVal, E))
11144 return false;
11145
11146 return true;
11147 }
11148 case CK_HLSLVectorTruncation: {
11149 APValue Val;
11150 SmallVector<APValue, 4> Elements;
11151 if (!EvaluateVector(SE, Val, Info))
11152 return Error(E);
11153 for (unsigned I = 0; I < NElts; I++)
11154 Elements.push_back(Val.getVectorElt(I));
11155 return Success(Elements, E);
11156 }
11157 default:
11158 return ExprEvaluatorBaseTy::VisitCastExpr(E);
11159 }
11160}
11161
11162bool
11163VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11164 const VectorType *VT = E->getType()->castAs<VectorType>();
11165 unsigned NumInits = E->getNumInits();
11166 unsigned NumElements = VT->getNumElements();
11167
11168 QualType EltTy = VT->getElementType();
11169 SmallVector<APValue, 4> Elements;
11170
11171 // The number of initializers can be less than the number of
11172 // vector elements. For OpenCL, this can be due to nested vector
11173 // initialization. For GCC compatibility, missing trailing elements
11174 // should be initialized with zeroes.
11175 unsigned CountInits = 0, CountElts = 0;
11176 while (CountElts < NumElements) {
11177 // Handle nested vector initialization.
11178 if (CountInits < NumInits
11179 && E->getInit(CountInits)->getType()->isVectorType()) {
11180 APValue v;
11181 if (!EvaluateVector(E->getInit(CountInits), v, Info))
11182 return Error(E);
11183 unsigned vlen = v.getVectorLength();
11184 for (unsigned j = 0; j < vlen; j++)
11185 Elements.push_back(v.getVectorElt(j));
11186 CountElts += vlen;
11187 } else if (EltTy->isIntegerType()) {
11188 llvm::APSInt sInt(32);
11189 if (CountInits < NumInits) {
11190 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
11191 return false;
11192 } else // trailing integer zero.
11193 sInt = Info.Ctx.MakeIntValue(0, EltTy);
11194 Elements.push_back(APValue(sInt));
11195 CountElts++;
11196 } else {
11197 llvm::APFloat f(0.0);
11198 if (CountInits < NumInits) {
11199 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
11200 return false;
11201 } else // trailing float zero.
11202 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
11203 Elements.push_back(APValue(f));
11204 CountElts++;
11205 }
11206 CountInits++;
11207 }
11208 return Success(Elements, E);
11209}
11210
11211bool
11212VectorExprEvaluator::ZeroInitialization(const Expr *E) {
11213 const auto *VT = E->getType()->castAs<VectorType>();
11214 QualType EltTy = VT->getElementType();
11215 APValue ZeroElement;
11216 if (EltTy->isIntegerType())
11217 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
11218 else
11219 ZeroElement =
11220 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
11221
11222 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
11223 return Success(Elements, E);
11224}
11225
11226bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11227 VisitIgnoredValue(E->getSubExpr());
11228 return ZeroInitialization(E);
11229}
11230
11231bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11232 BinaryOperatorKind Op = E->getOpcode();
11233 assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
11234 "Operation not supported on vector types");
11235
11236 if (Op == BO_Comma)
11237 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11238
11239 Expr *LHS = E->getLHS();
11240 Expr *RHS = E->getRHS();
11241
11242 assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
11243 "Must both be vector types");
11244 // Checking JUST the types are the same would be fine, except shifts don't
11245 // need to have their types be the same (since you always shift by an int).
11246 assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
11248 RHS->getType()->castAs<VectorType>()->getNumElements() ==
11250 "All operands must be the same size.");
11251
11252 APValue LHSValue;
11253 APValue RHSValue;
11254 bool LHSOK = Evaluate(LHSValue, Info, LHS);
11255 if (!LHSOK && !Info.noteFailure())
11256 return false;
11257 if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
11258 return false;
11259
11260 if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
11261 return false;
11262
11263 return Success(LHSValue, E);
11264}
11265
11266static std::optional<APValue> handleVectorUnaryOperator(ASTContext &Ctx,
11267 QualType ResultTy,
11269 APValue Elt) {
11270 switch (Op) {
11271 case UO_Plus:
11272 // Nothing to do here.
11273 return Elt;
11274 case UO_Minus:
11275 if (Elt.getKind() == APValue::Int) {
11276 Elt.getInt().negate();
11277 } else {
11278 assert(Elt.getKind() == APValue::Float &&
11279 "Vector can only be int or float type");
11280 Elt.getFloat().changeSign();
11281 }
11282 return Elt;
11283 case UO_Not:
11284 // This is only valid for integral types anyway, so we don't have to handle
11285 // float here.
11286 assert(Elt.getKind() == APValue::Int &&
11287 "Vector operator ~ can only be int");
11288 Elt.getInt().flipAllBits();
11289 return Elt;
11290 case UO_LNot: {
11291 if (Elt.getKind() == APValue::Int) {
11292 Elt.getInt() = !Elt.getInt();
11293 // operator ! on vectors returns -1 for 'truth', so negate it.
11294 Elt.getInt().negate();
11295 return Elt;
11296 }
11297 assert(Elt.getKind() == APValue::Float &&
11298 "Vector can only be int or float type");
11299 // Float types result in an int of the same size, but -1 for true, or 0 for
11300 // false.
11301 APSInt EltResult{Ctx.getIntWidth(ResultTy),
11302 ResultTy->isUnsignedIntegerType()};
11303 if (Elt.getFloat().isZero())
11304 EltResult.setAllBits();
11305 else
11306 EltResult.clearAllBits();
11307
11308 return APValue{EltResult};
11309 }
11310 default:
11311 // FIXME: Implement the rest of the unary operators.
11312 return std::nullopt;
11313 }
11314}
11315
11316bool VectorExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11317 Expr *SubExpr = E->getSubExpr();
11318 const auto *VD = SubExpr->getType()->castAs<VectorType>();
11319 // This result element type differs in the case of negating a floating point
11320 // vector, since the result type is the a vector of the equivilant sized
11321 // integer.
11322 const QualType ResultEltTy = VD->getElementType();
11323 UnaryOperatorKind Op = E->getOpcode();
11324
11325 APValue SubExprValue;
11326 if (!Evaluate(SubExprValue, Info, SubExpr))
11327 return false;
11328
11329 // FIXME: This vector evaluator someday needs to be changed to be LValue
11330 // aware/keep LValue information around, rather than dealing with just vector
11331 // types directly. Until then, we cannot handle cases where the operand to
11332 // these unary operators is an LValue. The only case I've been able to see
11333 // cause this is operator++ assigning to a member expression (only valid in
11334 // altivec compilations) in C mode, so this shouldn't limit us too much.
11335 if (SubExprValue.isLValue())
11336 return false;
11337
11338 assert(SubExprValue.getVectorLength() == VD->getNumElements() &&
11339 "Vector length doesn't match type?");
11340
11341 SmallVector<APValue, 4> ResultElements;
11342 for (unsigned EltNum = 0; EltNum < VD->getNumElements(); ++EltNum) {
11343 std::optional<APValue> Elt = handleVectorUnaryOperator(
11344 Info.Ctx, ResultEltTy, Op, SubExprValue.getVectorElt(EltNum));
11345 if (!Elt)
11346 return false;
11347 ResultElements.push_back(*Elt);
11348 }
11349 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11350}
11351
11352static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO,
11353 const Expr *E, QualType SourceTy,
11354 QualType DestTy, APValue const &Original,
11355 APValue &Result) {
11356 if (SourceTy->isIntegerType()) {
11357 if (DestTy->isRealFloatingType()) {
11358 Result = APValue(APFloat(0.0));
11359 return HandleIntToFloatCast(Info, E, FPO, SourceTy, Original.getInt(),
11360 DestTy, Result.getFloat());
11361 }
11362 if (DestTy->isIntegerType()) {
11363 Result = APValue(
11364 HandleIntToIntCast(Info, E, DestTy, SourceTy, Original.getInt()));
11365 return true;
11366 }
11367 } else if (SourceTy->isRealFloatingType()) {
11368 if (DestTy->isRealFloatingType()) {
11369 Result = Original;
11370 return HandleFloatToFloatCast(Info, E, SourceTy, DestTy,
11371 Result.getFloat());
11372 }
11373 if (DestTy->isIntegerType()) {
11374 Result = APValue(APSInt());
11375 return HandleFloatToIntCast(Info, E, SourceTy, Original.getFloat(),
11376 DestTy, Result.getInt());
11377 }
11378 }
11379
11380 Info.FFDiag(E, diag::err_convertvector_constexpr_unsupported_vector_cast)
11381 << SourceTy << DestTy;
11382 return false;
11383}
11384
11385bool VectorExprEvaluator::VisitCallExpr(const CallExpr *E) {
11386 if (!IsConstantEvaluatedBuiltinCall(E))
11387 return ExprEvaluatorBaseTy::VisitCallExpr(E);
11388
11389 switch (E->getBuiltinCallee()) {
11390 default:
11391 return false;
11392 case Builtin::BI__builtin_elementwise_popcount:
11393 case Builtin::BI__builtin_elementwise_bitreverse: {
11394 APValue Source;
11395 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
11396 return false;
11397
11398 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11399 unsigned SourceLen = Source.getVectorLength();
11400 SmallVector<APValue, 4> ResultElements;
11401 ResultElements.reserve(SourceLen);
11402
11403 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11404 APSInt Elt = Source.getVectorElt(EltNum).getInt();
11405 switch (E->getBuiltinCallee()) {
11406 case Builtin::BI__builtin_elementwise_popcount:
11407 ResultElements.push_back(APValue(
11408 APSInt(APInt(Info.Ctx.getIntWidth(DestEltTy), Elt.popcount()),
11409 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11410 break;
11411 case Builtin::BI__builtin_elementwise_bitreverse:
11412 ResultElements.push_back(
11413 APValue(APSInt(Elt.reverseBits(),
11414 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11415 break;
11416 }
11417 }
11418
11419 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11420 }
11421 case Builtin::BI__builtin_elementwise_add_sat:
11422 case Builtin::BI__builtin_elementwise_sub_sat: {
11423 APValue SourceLHS, SourceRHS;
11424 if (!EvaluateAsRValue(Info, E->getArg(0), SourceLHS) ||
11425 !EvaluateAsRValue(Info, E->getArg(1), SourceRHS))
11426 return false;
11427
11428 QualType DestEltTy = E->getType()->castAs<VectorType>()->getElementType();
11429 unsigned SourceLen = SourceLHS.getVectorLength();
11430 SmallVector<APValue, 4> ResultElements;
11431 ResultElements.reserve(SourceLen);
11432
11433 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11434 APSInt LHS = SourceLHS.getVectorElt(EltNum).getInt();
11435 APSInt RHS = SourceRHS.getVectorElt(EltNum).getInt();
11436 switch (E->getBuiltinCallee()) {
11437 case Builtin::BI__builtin_elementwise_add_sat:
11438 ResultElements.push_back(APValue(
11439 APSInt(LHS.isSigned() ? LHS.sadd_sat(RHS) : RHS.uadd_sat(RHS),
11440 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11441 break;
11442 case Builtin::BI__builtin_elementwise_sub_sat:
11443 ResultElements.push_back(APValue(
11444 APSInt(LHS.isSigned() ? LHS.ssub_sat(RHS) : RHS.usub_sat(RHS),
11445 DestEltTy->isUnsignedIntegerOrEnumerationType())));
11446 break;
11447 }
11448 }
11449
11450 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11451 }
11452 }
11453}
11454
11455bool VectorExprEvaluator::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
11456 APValue Source;
11457 QualType SourceVecType = E->getSrcExpr()->getType();
11458 if (!EvaluateAsRValue(Info, E->getSrcExpr(), Source))
11459 return false;
11460
11461 QualType DestTy = E->getType()->castAs<VectorType>()->getElementType();
11462 QualType SourceTy = SourceVecType->castAs<VectorType>()->getElementType();
11463
11464 const FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11465
11466 auto SourceLen = Source.getVectorLength();
11467 SmallVector<APValue, 4> ResultElements;
11468 ResultElements.reserve(SourceLen);
11469 for (unsigned EltNum = 0; EltNum < SourceLen; ++EltNum) {
11470 APValue Elt;
11471 if (!handleVectorElementCast(Info, FPO, E, SourceTy, DestTy,
11472 Source.getVectorElt(EltNum), Elt))
11473 return false;
11474 ResultElements.push_back(std::move(Elt));
11475 }
11476
11477 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11478}
11479
11480static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E,
11481 QualType ElemType, APValue const &VecVal1,
11482 APValue const &VecVal2, unsigned EltNum,
11483 APValue &Result) {
11484 unsigned const TotalElementsInInputVector1 = VecVal1.getVectorLength();
11485 unsigned const TotalElementsInInputVector2 = VecVal2.getVectorLength();
11486
11487 APSInt IndexVal = E->getShuffleMaskIdx(Info.Ctx, EltNum);
11488 int64_t index = IndexVal.getExtValue();
11489 // The spec says that -1 should be treated as undef for optimizations,
11490 // but in constexpr we'd have to produce an APValue::Indeterminate,
11491 // which is prohibited from being a top-level constant value. Emit a
11492 // diagnostic instead.
11493 if (index == -1) {
11494 Info.FFDiag(
11495 E, diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
11496 << EltNum;
11497 return false;
11498 }
11499
11500 if (index < 0 ||
11501 index >= TotalElementsInInputVector1 + TotalElementsInInputVector2)
11502 llvm_unreachable("Out of bounds shuffle index");
11503
11504 if (index >= TotalElementsInInputVector1)
11505 Result = VecVal2.getVectorElt(index - TotalElementsInInputVector1);
11506 else
11507 Result = VecVal1.getVectorElt(index);
11508 return true;
11509}
11510
11511bool VectorExprEvaluator::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
11512 APValue VecVal1;
11513 const Expr *Vec1 = E->getExpr(0);
11514 if (!EvaluateAsRValue(Info, Vec1, VecVal1))
11515 return false;
11516 APValue VecVal2;
11517 const Expr *Vec2 = E->getExpr(1);
11518 if (!EvaluateAsRValue(Info, Vec2, VecVal2))
11519 return false;
11520
11521 VectorType const *DestVecTy = E->getType()->castAs<VectorType>();
11522 QualType DestElTy = DestVecTy->getElementType();
11523
11524 auto TotalElementsInOutputVector = DestVecTy->getNumElements();
11525
11526 SmallVector<APValue, 4> ResultElements;
11527 ResultElements.reserve(TotalElementsInOutputVector);
11528 for (unsigned EltNum = 0; EltNum < TotalElementsInOutputVector; ++EltNum) {
11529 APValue Elt;
11530 if (!handleVectorShuffle(Info, E, DestElTy, VecVal1, VecVal2, EltNum, Elt))
11531 return false;
11532 ResultElements.push_back(std::move(Elt));
11533 }
11534
11535 return Success(APValue(ResultElements.data(), ResultElements.size()), E);
11536}
11537
11538//===----------------------------------------------------------------------===//
11539// Array Evaluation
11540//===----------------------------------------------------------------------===//
11541
11542namespace {
11543 class ArrayExprEvaluator
11544 : public ExprEvaluatorBase<ArrayExprEvaluator> {
11545 const LValue &This;
11546 APValue &Result;
11547 public:
11548
11549 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
11550 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11551
11552 bool Success(const APValue &V, const Expr *E) {
11553 assert(V.isArray() && "expected array");
11554 Result = V;
11555 return true;
11556 }
11557
11558 bool ZeroInitialization(const Expr *E) {
11559 const ConstantArrayType *CAT =
11560 Info.Ctx.getAsConstantArrayType(E->getType());
11561 if (!CAT) {
11562 if (E->getType()->isIncompleteArrayType()) {
11563 // We can be asked to zero-initialize a flexible array member; this
11564 // is represented as an ImplicitValueInitExpr of incomplete array
11565 // type. In this case, the array has zero elements.
11566 Result = APValue(APValue::UninitArray(), 0, 0);
11567 return true;
11568 }
11569 // FIXME: We could handle VLAs here.
11570 return Error(E);
11571 }
11572
11573 Result = APValue(APValue::UninitArray(), 0, CAT->getZExtSize());
11574 if (!Result.hasArrayFiller())
11575 return true;
11576
11577 // Zero-initialize all elements.
11578 LValue Subobject = This;
11579 Subobject.addArray(Info, E, CAT);
11581 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
11582 }
11583
11584 bool VisitCallExpr(const CallExpr *E) {
11585 return handleCallExpr(E, Result, &This);
11586 }
11587 bool VisitInitListExpr(const InitListExpr *E,
11588 QualType AllocType = QualType());
11589 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
11590 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
11591 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
11592 const LValue &Subobject,
11594 bool VisitStringLiteral(const StringLiteral *E,
11595 QualType AllocType = QualType()) {
11596 expandStringLiteral(Info, E, Result, AllocType);
11597 return true;
11598 }
11599 bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
11600 bool VisitCXXParenListOrInitListExpr(const Expr *ExprToVisit,
11601 ArrayRef<Expr *> Args,
11602 const Expr *ArrayFiller,
11603 QualType AllocType = QualType());
11604 };
11605} // end anonymous namespace
11606
11607static bool EvaluateArray(const Expr *E, const LValue &This,
11608 APValue &Result, EvalInfo &Info) {
11609 assert(!E->isValueDependent());
11610 assert(E->isPRValue() && E->getType()->isArrayType() &&
11611 "not an array prvalue");
11612 return ArrayExprEvaluator(Info, This, Result).Visit(E);
11613}
11614
11615static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
11616 APValue &Result, const InitListExpr *ILE,
11617 QualType AllocType) {
11618 assert(!ILE->isValueDependent());
11619 assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
11620 "not an array prvalue");
11621 return ArrayExprEvaluator(Info, This, Result)
11622 .VisitInitListExpr(ILE, AllocType);
11623}
11624
11625static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
11626 APValue &Result,
11627 const CXXConstructExpr *CCE,
11628 QualType AllocType) {
11629 assert(!CCE->isValueDependent());
11630 assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
11631 "not an array prvalue");
11632 return ArrayExprEvaluator(Info, This, Result)
11633 .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
11634}
11635
11636// Return true iff the given array filler may depend on the element index.
11637static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
11638 // For now, just allow non-class value-initialization and initialization
11639 // lists comprised of them.
11640 if (isa<ImplicitValueInitExpr>(FillerExpr))
11641 return false;
11642 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
11643 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
11644 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
11645 return true;
11646 }
11647
11648 if (ILE->hasArrayFiller() &&
11649 MaybeElementDependentArrayFiller(ILE->getArrayFiller()))
11650 return true;
11651
11652 return false;
11653 }
11654 return true;
11655}
11656
11657bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
11658 QualType AllocType) {
11659 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11660 AllocType.isNull() ? E->getType() : AllocType);
11661 if (!CAT)
11662 return Error(E);
11663
11664 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
11665 // an appropriately-typed string literal enclosed in braces.
11666 if (E->isStringLiteralInit()) {
11667 auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
11668 // FIXME: Support ObjCEncodeExpr here once we support it in
11669 // ArrayExprEvaluator generally.
11670 if (!SL)
11671 return Error(E);
11672 return VisitStringLiteral(SL, AllocType);
11673 }
11674 // Any other transparent list init will need proper handling of the
11675 // AllocType; we can't just recurse to the inner initializer.
11676 assert(!E->isTransparent() &&
11677 "transparent array list initialization is not string literal init?");
11678
11679 return VisitCXXParenListOrInitListExpr(E, E->inits(), E->getArrayFiller(),
11680 AllocType);
11681}
11682
11683bool ArrayExprEvaluator::VisitCXXParenListOrInitListExpr(
11684 const Expr *ExprToVisit, ArrayRef<Expr *> Args, const Expr *ArrayFiller,
11685 QualType AllocType) {
11686 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
11687 AllocType.isNull() ? ExprToVisit->getType() : AllocType);
11688
11689 bool Success = true;
11690
11691 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
11692 "zero-initialized array shouldn't have any initialized elts");
11693 APValue Filler;
11694 if (Result.isArray() && Result.hasArrayFiller())
11695 Filler = Result.getArrayFiller();
11696
11697 unsigned NumEltsToInit = Args.size();
11698 unsigned NumElts = CAT->getZExtSize();
11699
11700 // If the initializer might depend on the array index, run it for each
11701 // array element.
11702 if (NumEltsToInit != NumElts &&
11703 MaybeElementDependentArrayFiller(ArrayFiller)) {
11704 NumEltsToInit = NumElts;
11705 } else {
11706 for (auto *Init : Args) {
11707 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts()))
11708 NumEltsToInit += EmbedS->getDataElementCount() - 1;
11709 }
11710 if (NumEltsToInit > NumElts)
11711 NumEltsToInit = NumElts;
11712 }
11713
11714 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
11715 << NumEltsToInit << ".\n");
11716
11717 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
11718
11719 // If the array was previously zero-initialized, preserve the
11720 // zero-initialized values.
11721 if (Filler.hasValue()) {
11722 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
11723 Result.getArrayInitializedElt(I) = Filler;
11724 if (Result.hasArrayFiller())
11725 Result.getArrayFiller() = Filler;
11726 }
11727
11728 LValue Subobject = This;
11729 Subobject.addArray(Info, ExprToVisit, CAT);
11730 auto Eval = [&](const Expr *Init, unsigned ArrayIndex) {
11731 if (Init->isValueDependent())
11732 return EvaluateDependentExpr(Init, Info);
11733
11734 if (!EvaluateInPlace(Result.getArrayInitializedElt(ArrayIndex), Info,
11735 Subobject, Init) ||
11736 !HandleLValueArrayAdjustment(Info, Init, Subobject,
11737 CAT->getElementType(), 1)) {
11738 if (!Info.noteFailure())
11739 return false;
11740 Success = false;
11741 }
11742 return true;
11743 };
11744 unsigned ArrayIndex = 0;
11745 QualType DestTy = CAT->getElementType();
11746 APSInt Value(Info.Ctx.getTypeSize(DestTy), DestTy->isUnsignedIntegerType());
11747 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
11748 const Expr *Init = Index < Args.size() ? Args[Index] : ArrayFiller;
11749 if (ArrayIndex >= NumEltsToInit)
11750 break;
11751 if (auto *EmbedS = dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
11752 StringLiteral *SL = EmbedS->getDataStringLiteral();
11753 for (unsigned I = EmbedS->getStartingElementPos(),
11754 N = EmbedS->getDataElementCount();
11755 I != EmbedS->getStartingElementPos() + N; ++I) {
11756 Value = SL->getCodeUnit(I);
11757 if (DestTy->isIntegerType()) {
11758 Result.getArrayInitializedElt(ArrayIndex) = APValue(Value);
11759 } else {
11760 assert(DestTy->isFloatingType() && "unexpected type");
11761 const FPOptions FPO =
11762 Init->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
11763 APFloat FValue(0.0);
11764 if (!HandleIntToFloatCast(Info, Init, FPO, EmbedS->getType(), Value,
11765 DestTy, FValue))
11766 return false;
11767 Result.getArrayInitializedElt(ArrayIndex) = APValue(FValue);
11768 }
11769 ArrayIndex++;
11770 }
11771 } else {
11772 if (!Eval(Init, ArrayIndex))
11773 return false;
11774 ++ArrayIndex;
11775 }
11776 }
11777
11778 if (!Result.hasArrayFiller())
11779 return Success;
11780
11781 // If we get here, we have a trivial filler, which we can just evaluate
11782 // once and splat over the rest of the array elements.
11783 assert(ArrayFiller && "no array filler for incomplete init list");
11784 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
11785 ArrayFiller) &&
11786 Success;
11787}
11788
11789bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
11790 LValue CommonLV;
11791 if (E->getCommonExpr() &&
11792 !Evaluate(Info.CurrentCall->createTemporary(
11793 E->getCommonExpr(),
11794 getStorageType(Info.Ctx, E->getCommonExpr()),
11795 ScopeKind::FullExpression, CommonLV),
11796 Info, E->getCommonExpr()->getSourceExpr()))
11797 return false;
11798
11799 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
11800
11801 uint64_t Elements = CAT->getZExtSize();
11802 Result = APValue(APValue::UninitArray(), Elements, Elements);
11803
11804 LValue Subobject = This;
11805 Subobject.addArray(Info, E, CAT);
11806
11807 bool Success = true;
11808 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
11809 // C++ [class.temporary]/5
11810 // There are four contexts in which temporaries are destroyed at a different
11811 // point than the end of the full-expression. [...] The second context is
11812 // when a copy constructor is called to copy an element of an array while
11813 // the entire array is copied [...]. In either case, if the constructor has
11814 // one or more default arguments, the destruction of every temporary created
11815 // in a default argument is sequenced before the construction of the next
11816 // array element, if any.
11817 FullExpressionRAII Scope(Info);
11818
11819 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
11820 Info, Subobject, E->getSubExpr()) ||
11821 !HandleLValueArrayAdjustment(Info, E, Subobject,
11822 CAT->getElementType(), 1)) {
11823 if (!Info.noteFailure())
11824 return false;
11825 Success = false;
11826 }
11827
11828 // Make sure we run the destructors too.
11829 Scope.destroy();
11830 }
11831
11832 return Success;
11833}
11834
11835bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
11836 return VisitCXXConstructExpr(E, This, &Result, E->getType());
11837}
11838
11839bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
11840 const LValue &Subobject,
11841 APValue *Value,
11842 QualType Type) {
11843 bool HadZeroInit = Value->hasValue();
11844
11845 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
11846 unsigned FinalSize = CAT->getZExtSize();
11847
11848 // Preserve the array filler if we had prior zero-initialization.
11849 APValue Filler =
11850 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
11851 : APValue();
11852
11853 *Value = APValue(APValue::UninitArray(), 0, FinalSize);
11854 if (FinalSize == 0)
11855 return true;
11856
11857 bool HasTrivialConstructor = CheckTrivialDefaultConstructor(
11858 Info, E->getExprLoc(), E->getConstructor(),
11859 E->requiresZeroInitialization());
11860 LValue ArrayElt = Subobject;
11861 ArrayElt.addArray(Info, E, CAT);
11862 // We do the whole initialization in two passes, first for just one element,
11863 // then for the whole array. It's possible we may find out we can't do const
11864 // init in the first pass, in which case we avoid allocating a potentially
11865 // large array. We don't do more passes because expanding array requires
11866 // copying the data, which is wasteful.
11867 for (const unsigned N : {1u, FinalSize}) {
11868 unsigned OldElts = Value->getArrayInitializedElts();
11869 if (OldElts == N)
11870 break;
11871
11872 // Expand the array to appropriate size.
11873 APValue NewValue(APValue::UninitArray(), N, FinalSize);
11874 for (unsigned I = 0; I < OldElts; ++I)
11875 NewValue.getArrayInitializedElt(I).swap(
11876 Value->getArrayInitializedElt(I));
11877 Value->swap(NewValue);
11878
11879 if (HadZeroInit)
11880 for (unsigned I = OldElts; I < N; ++I)
11881 Value->getArrayInitializedElt(I) = Filler;
11882
11883 if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
11884 // If we have a trivial constructor, only evaluate it once and copy
11885 // the result into all the array elements.
11886 APValue &FirstResult = Value->getArrayInitializedElt(0);
11887 for (unsigned I = OldElts; I < FinalSize; ++I)
11888 Value->getArrayInitializedElt(I) = FirstResult;
11889 } else {
11890 for (unsigned I = OldElts; I < N; ++I) {
11891 if (!VisitCXXConstructExpr(E, ArrayElt,
11892 &Value->getArrayInitializedElt(I),
11893 CAT->getElementType()) ||
11894 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
11895 CAT->getElementType(), 1))
11896 return false;
11897 // When checking for const initilization any diagnostic is considered
11898 // an error.
11899 if (Info.EvalStatus.Diag && !Info.EvalStatus.Diag->empty() &&
11900 !Info.keepEvaluatingAfterFailure())
11901 return false;
11902 }
11903 }
11904 }
11905
11906 return true;
11907 }
11908
11909 if (!Type->isRecordType())
11910 return Error(E);
11911
11912 return RecordExprEvaluator(Info, Subobject, *Value)
11913 .VisitCXXConstructExpr(E, Type);
11914}
11915
11916bool ArrayExprEvaluator::VisitCXXParenListInitExpr(
11917 const CXXParenListInitExpr *E) {
11918 assert(E->getType()->isConstantArrayType() &&
11919 "Expression result is not a constant array type");
11920
11921 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs(),
11922 E->getArrayFiller());
11923}
11924
11925//===----------------------------------------------------------------------===//
11926// Integer Evaluation
11927//
11928// As a GNU extension, we support casting pointers to sufficiently-wide integer
11929// types and back in constant folding. Integer values are thus represented
11930// either as an integer-valued APValue, or as an lvalue-valued APValue.
11931//===----------------------------------------------------------------------===//
11932
11933namespace {
11934class IntExprEvaluator
11935 : public ExprEvaluatorBase<IntExprEvaluator> {
11936 APValue &Result;
11937public:
11938 IntExprEvaluator(EvalInfo &info, APValue &result)
11939 : ExprEvaluatorBaseTy(info), Result(result) {}
11940
11941 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
11942 assert(E->getType()->isIntegralOrEnumerationType() &&
11943 "Invalid evaluation result.");
11944 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
11945 "Invalid evaluation result.");
11946 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11947 "Invalid evaluation result.");
11948 Result = APValue(SI);
11949 return true;
11950 }
11951 bool Success(const llvm::APSInt &SI, const Expr *E) {
11952 return Success(SI, E, Result);
11953 }
11954
11955 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
11956 assert(E->getType()->isIntegralOrEnumerationType() &&
11957 "Invalid evaluation result.");
11958 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
11959 "Invalid evaluation result.");
11960 Result = APValue(APSInt(I));
11961 Result.getInt().setIsUnsigned(
11963 return true;
11964 }
11965 bool Success(const llvm::APInt &I, const Expr *E) {
11966 return Success(I, E, Result);
11967 }
11968
11969 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11970 assert(E->getType()->isIntegralOrEnumerationType() &&
11971 "Invalid evaluation result.");
11972 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
11973 return true;
11974 }
11975 bool Success(uint64_t Value, const Expr *E) {
11976 return Success(Value, E, Result);
11977 }
11978
11979 bool Success(CharUnits Size, const Expr *E) {
11980 return Success(Size.getQuantity(), E);
11981 }
11982
11983 bool Success(const APValue &V, const Expr *E) {
11984 // C++23 [expr.const]p8 If we have a variable that is unknown reference or
11985 // pointer allow further evaluation of the value.
11986 if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate() ||
11987 V.allowConstexprUnknown()) {
11988 Result = V;
11989 return true;
11990 }
11991 return Success(V.getInt(), E);
11992 }
11993
11994 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
11995
11996 friend std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &,
11997 const CallExpr *);
11998
11999 //===--------------------------------------------------------------------===//
12000 // Visitor Methods
12001 //===--------------------------------------------------------------------===//
12002
12003 bool VisitIntegerLiteral(const IntegerLiteral *E) {
12004 return Success(E->getValue(), E);
12005 }
12006 bool VisitCharacterLiteral(const CharacterLiteral *E) {
12007 return Success(E->getValue(), E);
12008 }
12009
12010 bool CheckReferencedDecl(const Expr *E, const Decl *D);
12011 bool VisitDeclRefExpr(const DeclRefExpr *E) {
12012 if (CheckReferencedDecl(E, E->getDecl()))
12013 return true;
12014
12015 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
12016 }
12017 bool VisitMemberExpr(const MemberExpr *E) {
12018 if (CheckReferencedDecl(E, E->getMemberDecl())) {
12019 VisitIgnoredBaseExpression(E->getBase());
12020 return true;
12021 }
12022
12023 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
12024 }
12025
12026 bool VisitCallExpr(const CallExpr *E);
12027 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
12028 bool VisitBinaryOperator(const BinaryOperator *E);
12029 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
12030 bool VisitUnaryOperator(const UnaryOperator *E);
12031
12032 bool VisitCastExpr(const CastExpr* E);
12033 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
12034
12035 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
12036 return Success(E->getValue(), E);
12037 }
12038
12039 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
12040 return Success(E->getValue(), E);
12041 }
12042
12043 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
12044 if (Info.ArrayInitIndex == uint64_t(-1)) {
12045 // We were asked to evaluate this subexpression independent of the
12046 // enclosing ArrayInitLoopExpr. We can't do that.
12047 Info.FFDiag(E);
12048 return false;
12049 }
12050 return Success(Info.ArrayInitIndex, E);
12051 }
12052
12053 // Note, GNU defines __null as an integer, not a pointer.
12054 bool VisitGNUNullExpr(const GNUNullExpr *E) {
12055 return ZeroInitialization(E);
12056 }
12057
12058 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
12059 return Success(E->getValue(), E);
12060 }
12061
12062 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
12063 return Success(E->getValue(), E);
12064 }
12065
12066 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
12067 return Success(E->getValue(), E);
12068 }
12069
12070 bool VisitOpenACCAsteriskSizeExpr(const OpenACCAsteriskSizeExpr *E) {
12071 // This should not be evaluated during constant expr evaluation, as it
12072 // should always be in an unevaluated context (the args list of a 'gang' or
12073 // 'tile' clause).
12074 return Error(E);
12075 }
12076
12077 bool VisitUnaryReal(const UnaryOperator *E);
12078 bool VisitUnaryImag(const UnaryOperator *E);
12079
12080 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
12081 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
12082 bool VisitSourceLocExpr(const SourceLocExpr *E);
12083 bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
12084 bool VisitRequiresExpr(const RequiresExpr *E);
12085 // FIXME: Missing: array subscript of vector, member of vector
12086};
12087
12088class FixedPointExprEvaluator
12089 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
12090 APValue &Result;
12091
12092 public:
12093 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
12094 : ExprEvaluatorBaseTy(info), Result(result) {}
12095
12096 bool Success(const llvm::APInt &I, const Expr *E) {
12097 return Success(
12098 APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12099 }
12100
12101 bool Success(uint64_t Value, const Expr *E) {
12102 return Success(
12103 APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
12104 }
12105
12106 bool Success(const APValue &V, const Expr *E) {
12107 return Success(V.getFixedPoint(), E);
12108 }
12109
12110 bool Success(const APFixedPoint &V, const Expr *E) {
12111 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
12112 assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
12113 "Invalid evaluation result.");
12114 Result = APValue(V);
12115 return true;
12116 }
12117
12118 bool ZeroInitialization(const Expr *E) {
12119 return Success(0, E);
12120 }
12121
12122 //===--------------------------------------------------------------------===//
12123 // Visitor Methods
12124 //===--------------------------------------------------------------------===//
12125
12126 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
12127 return Success(E->getValue(), E);
12128 }
12129
12130 bool VisitCastExpr(const CastExpr *E);
12131 bool VisitUnaryOperator(const UnaryOperator *E);
12132 bool VisitBinaryOperator(const BinaryOperator *E);
12133};
12134} // end anonymous namespace
12135
12136/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
12137/// produce either the integer value or a pointer.
12138///
12139/// GCC has a heinous extension which folds casts between pointer types and
12140/// pointer-sized integral types. We support this by allowing the evaluation of
12141/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
12142/// Some simple arithmetic on such values is supported (they are treated much
12143/// like char*).
12144static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
12145 EvalInfo &Info) {
12146 assert(!E->isValueDependent());
12147 assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
12148 return IntExprEvaluator(Info, Result).Visit(E);
12149}
12150
12151static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
12152 assert(!E->isValueDependent());
12153 APValue Val;
12154 if (!EvaluateIntegerOrLValue(E, Val, Info))
12155 return false;
12156 if (!Val.isInt()) {
12157 // FIXME: It would be better to produce the diagnostic for casting
12158 // a pointer to an integer.
12159 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12160 return false;
12161 }
12162 Result = Val.getInt();
12163 return true;
12164}
12165
12166bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
12167 APValue Evaluated = E->EvaluateInContext(
12168 Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
12169 return Success(Evaluated, E);
12170}
12171
12172static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
12173 EvalInfo &Info) {
12174 assert(!E->isValueDependent());
12175 if (E->getType()->isFixedPointType()) {
12176 APValue Val;
12177 if (!FixedPointExprEvaluator(Info, Val).Visit(E))
12178 return false;
12179 if (!Val.isFixedPoint())
12180 return false;
12181
12182 Result = Val.getFixedPoint();
12183 return true;
12184 }
12185 return false;
12186}
12187
12188static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
12189 EvalInfo &Info) {
12190 assert(!E->isValueDependent());
12191 if (E->getType()->isIntegerType()) {
12192 auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
12193 APSInt Val;
12194 if (!EvaluateInteger(E, Val, Info))
12195 return false;
12196 Result = APFixedPoint(Val, FXSema);
12197 return true;
12198 } else if (E->getType()->isFixedPointType()) {
12199 return EvaluateFixedPoint(E, Result, Info);
12200 }
12201 return false;
12202}
12203
12204/// Check whether the given declaration can be directly converted to an integral
12205/// rvalue. If not, no diagnostic is produced; there are other things we can
12206/// try.
12207bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
12208 // Enums are integer constant exprs.
12209 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
12210 // Check for signedness/width mismatches between E type and ECD value.
12211 bool SameSign = (ECD->getInitVal().isSigned()
12213 bool SameWidth = (ECD->getInitVal().getBitWidth()
12214 == Info.Ctx.getIntWidth(E->getType()));
12215 if (SameSign && SameWidth)
12216 return Success(ECD->getInitVal(), E);
12217 else {
12218 // Get rid of mismatch (otherwise Success assertions will fail)
12219 // by computing a new value matching the type of E.
12220 llvm::APSInt Val = ECD->getInitVal();
12221 if (!SameSign)
12222 Val.setIsSigned(!ECD->getInitVal().isSigned());
12223 if (!SameWidth)
12224 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
12225 return Success(Val, E);
12226 }
12227 }
12228 return false;
12229}
12230
12231/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12232/// as GCC.
12234 const LangOptions &LangOpts) {
12235 assert(!T->isDependentType() && "unexpected dependent type");
12236
12237 QualType CanTy = T.getCanonicalType();
12238
12239 switch (CanTy->getTypeClass()) {
12240#define TYPE(ID, BASE)
12241#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
12242#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
12243#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
12244#include "clang/AST/TypeNodes.inc"
12245 case Type::Auto:
12246 case Type::DeducedTemplateSpecialization:
12247 llvm_unreachable("unexpected non-canonical or dependent type");
12248
12249 case Type::Builtin:
12250 switch (cast<BuiltinType>(CanTy)->getKind()) {
12251#define BUILTIN_TYPE(ID, SINGLETON_ID)
12252#define SIGNED_TYPE(ID, SINGLETON_ID) \
12253 case BuiltinType::ID: return GCCTypeClass::Integer;
12254#define FLOATING_TYPE(ID, SINGLETON_ID) \
12255 case BuiltinType::ID: return GCCTypeClass::RealFloat;
12256#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
12257 case BuiltinType::ID: break;
12258#include "clang/AST/BuiltinTypes.def"
12259 case BuiltinType::Void:
12260 return GCCTypeClass::Void;
12261
12262 case BuiltinType::Bool:
12263 return GCCTypeClass::Bool;
12264
12265 case BuiltinType::Char_U:
12266 case BuiltinType::UChar:
12267 case BuiltinType::WChar_U:
12268 case BuiltinType::Char8:
12269 case BuiltinType::Char16:
12270 case BuiltinType::Char32:
12271 case BuiltinType::UShort:
12272 case BuiltinType::UInt:
12273 case BuiltinType::ULong:
12274 case BuiltinType::ULongLong:
12275 case BuiltinType::UInt128:
12276 return GCCTypeClass::Integer;
12277
12278 case BuiltinType::UShortAccum:
12279 case BuiltinType::UAccum:
12280 case BuiltinType::ULongAccum:
12281 case BuiltinType::UShortFract:
12282 case BuiltinType::UFract:
12283 case BuiltinType::ULongFract:
12284 case BuiltinType::SatUShortAccum:
12285 case BuiltinType::SatUAccum:
12286 case BuiltinType::SatULongAccum:
12287 case BuiltinType::SatUShortFract:
12288 case BuiltinType::SatUFract:
12289 case BuiltinType::SatULongFract:
12290 return GCCTypeClass::None;
12291
12292 case BuiltinType::NullPtr:
12293
12294 case BuiltinType::ObjCId:
12295 case BuiltinType::ObjCClass:
12296 case BuiltinType::ObjCSel:
12297#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
12298 case BuiltinType::Id:
12299#include "clang/Basic/OpenCLImageTypes.def"
12300#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
12301 case BuiltinType::Id:
12302#include "clang/Basic/OpenCLExtensionTypes.def"
12303 case BuiltinType::OCLSampler:
12304 case BuiltinType::OCLEvent:
12305 case BuiltinType::OCLClkEvent:
12306 case BuiltinType::OCLQueue:
12307 case BuiltinType::OCLReserveID:
12308#define SVE_TYPE(Name, Id, SingletonId) \
12309 case BuiltinType::Id:
12310#include "clang/Basic/AArch64SVEACLETypes.def"
12311#define PPC_VECTOR_TYPE(Name, Id, Size) \
12312 case BuiltinType::Id:
12313#include "clang/Basic/PPCTypes.def"
12314#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12315#include "clang/Basic/RISCVVTypes.def"
12316#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12317#include "clang/Basic/WebAssemblyReferenceTypes.def"
12318#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
12319#include "clang/Basic/AMDGPUTypes.def"
12320#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
12321#include "clang/Basic/HLSLIntangibleTypes.def"
12322 return GCCTypeClass::None;
12323
12324 case BuiltinType::Dependent:
12325 llvm_unreachable("unexpected dependent type");
12326 };
12327 llvm_unreachable("unexpected placeholder type");
12328
12329 case Type::Enum:
12330 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
12331
12332 case Type::Pointer:
12333 case Type::ConstantArray:
12334 case Type::VariableArray:
12335 case Type::IncompleteArray:
12336 case Type::FunctionNoProto:
12337 case Type::FunctionProto:
12338 case Type::ArrayParameter:
12339 return GCCTypeClass::Pointer;
12340
12341 case Type::MemberPointer:
12342 return CanTy->isMemberDataPointerType()
12343 ? GCCTypeClass::PointerToDataMember
12344 : GCCTypeClass::PointerToMemberFunction;
12345
12346 case Type::Complex:
12347 return GCCTypeClass::Complex;
12348
12349 case Type::Record:
12350 return CanTy->isUnionType() ? GCCTypeClass::Union
12351 : GCCTypeClass::ClassOrStruct;
12352
12353 case Type::Atomic:
12354 // GCC classifies _Atomic T the same as T.
12356 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
12357
12358 case Type::Vector:
12359 case Type::ExtVector:
12360 return GCCTypeClass::Vector;
12361
12362 case Type::BlockPointer:
12363 case Type::ConstantMatrix:
12364 case Type::ObjCObject:
12365 case Type::ObjCInterface:
12366 case Type::ObjCObjectPointer:
12367 case Type::Pipe:
12368 case Type::HLSLAttributedResource:
12369 // Classify all other types that don't fit into the regular
12370 // classification the same way.
12371 return GCCTypeClass::None;
12372
12373 case Type::BitInt:
12374 return GCCTypeClass::BitInt;
12375
12376 case Type::LValueReference:
12377 case Type::RValueReference:
12378 llvm_unreachable("invalid type for expression");
12379 }
12380
12381 llvm_unreachable("unexpected type class");
12382}
12383
12384/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
12385/// as GCC.
12386static GCCTypeClass
12388 // If no argument was supplied, default to None. This isn't
12389 // ideal, however it is what gcc does.
12390 if (E->getNumArgs() == 0)
12391 return GCCTypeClass::None;
12392
12393 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
12394 // being an ICE, but still folds it to a constant using the type of the first
12395 // argument.
12396 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
12397}
12398
12399/// EvaluateBuiltinConstantPForLValue - Determine the result of
12400/// __builtin_constant_p when applied to the given pointer.
12401///
12402/// A pointer is only "constant" if it is null (or a pointer cast to integer)
12403/// or it points to the first character of a string literal.
12406 if (Base.isNull()) {
12407 // A null base is acceptable.
12408 return true;
12409 } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
12410 if (!isa<StringLiteral>(E))
12411 return false;
12412 return LV.getLValueOffset().isZero();
12413 } else if (Base.is<TypeInfoLValue>()) {
12414 // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
12415 // evaluate to true.
12416 return true;
12417 } else {
12418 // Any other base is not constant enough for GCC.
12419 return false;
12420 }
12421}
12422
12423/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
12424/// GCC as we can manage.
12425static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
12426 // This evaluation is not permitted to have side-effects, so evaluate it in
12427 // a speculative evaluation context.
12428 SpeculativeEvaluationRAII SpeculativeEval(Info);
12429
12430 // Constant-folding is always enabled for the operand of __builtin_constant_p
12431 // (even when the enclosing evaluation context otherwise requires a strict
12432 // language-specific constant expression).
12433 FoldConstant Fold(Info, true);
12434
12435 QualType ArgType = Arg->getType();
12436
12437 // __builtin_constant_p always has one operand. The rules which gcc follows
12438 // are not precisely documented, but are as follows:
12439 //
12440 // - If the operand is of integral, floating, complex or enumeration type,
12441 // and can be folded to a known value of that type, it returns 1.
12442 // - If the operand can be folded to a pointer to the first character
12443 // of a string literal (or such a pointer cast to an integral type)
12444 // or to a null pointer or an integer cast to a pointer, it returns 1.
12445 //
12446 // Otherwise, it returns 0.
12447 //
12448 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
12449 // its support for this did not work prior to GCC 9 and is not yet well
12450 // understood.
12451 if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
12452 ArgType->isAnyComplexType() || ArgType->isPointerType() ||
12453 ArgType->isNullPtrType()) {
12454 APValue V;
12455 if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
12456 Fold.keepDiagnostics();
12457 return false;
12458 }
12459
12460 // For a pointer (possibly cast to integer), there are special rules.
12461 if (V.getKind() == APValue::LValue)
12463
12464 // Otherwise, any constant value is good enough.
12465 return V.hasValue();
12466 }
12467
12468 // Anything else isn't considered to be sufficiently constant.
12469 return false;
12470}
12471
12472/// Retrieves the "underlying object type" of the given expression,
12473/// as used by __builtin_object_size.
12475 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
12476 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
12477 return VD->getType();
12478 } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
12479 if (isa<CompoundLiteralExpr>(E))
12480 return E->getType();
12481 } else if (B.is<TypeInfoLValue>()) {
12482 return B.getTypeInfoType();
12483 } else if (B.is<DynamicAllocLValue>()) {
12484 return B.getDynamicAllocType();
12485 }
12486
12487 return QualType();
12488}
12489
12490/// A more selective version of E->IgnoreParenCasts for
12491/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
12492/// to change the type of E.
12493/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
12494///
12495/// Always returns an RValue with a pointer representation.
12497 assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
12498
12499 const Expr *NoParens = E->IgnoreParens();
12500 const auto *Cast = dyn_cast<CastExpr>(NoParens);
12501 if (Cast == nullptr)
12502 return NoParens;
12503
12504 // We only conservatively allow a few kinds of casts, because this code is
12505 // inherently a simple solution that seeks to support the common case.
12506 auto CastKind = Cast->getCastKind();
12507 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
12508 CastKind != CK_AddressSpaceConversion)
12509 return NoParens;
12510
12511 const auto *SubExpr = Cast->getSubExpr();
12512 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
12513 return NoParens;
12514 return ignorePointerCastsAndParens(SubExpr);
12515}
12516
12517/// Checks to see if the given LValue's Designator is at the end of the LValue's
12518/// record layout. e.g.
12519/// struct { struct { int a, b; } fst, snd; } obj;
12520/// obj.fst // no
12521/// obj.snd // yes
12522/// obj.fst.a // no
12523/// obj.fst.b // no
12524/// obj.snd.a // no
12525/// obj.snd.b // yes
12526///
12527/// Please note: this function is specialized for how __builtin_object_size
12528/// views "objects".
12529///
12530/// If this encounters an invalid RecordDecl or otherwise cannot determine the
12531/// correct result, it will always return true.
12532static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
12533 assert(!LVal.Designator.Invalid);
12534
12535 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
12536 const RecordDecl *Parent = FD->getParent();
12537 Invalid = Parent->isInvalidDecl();
12538 if (Invalid || Parent->isUnion())
12539 return true;
12540 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
12541 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
12542 };
12543
12544 auto &Base = LVal.getLValueBase();
12545 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
12546 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
12547 bool Invalid;
12548 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12549 return Invalid;
12550 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
12551 for (auto *FD : IFD->chain()) {
12552 bool Invalid;
12553 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
12554 return Invalid;
12555 }
12556 }
12557 }
12558
12559 unsigned I = 0;
12560 QualType BaseType = getType(Base);
12561 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
12562 // If we don't know the array bound, conservatively assume we're looking at
12563 // the final array element.
12564 ++I;
12565 if (BaseType->isIncompleteArrayType())
12566 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
12567 else
12568 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
12569 }
12570
12571 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
12572 const auto &Entry = LVal.Designator.Entries[I];
12573 if (BaseType->isArrayType()) {
12574 // Because __builtin_object_size treats arrays as objects, we can ignore
12575 // the index iff this is the last array in the Designator.
12576 if (I + 1 == E)
12577 return true;
12578 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
12579 uint64_t Index = Entry.getAsArrayIndex();
12580 if (Index + 1 != CAT->getZExtSize())
12581 return false;
12582 BaseType = CAT->getElementType();
12583 } else if (BaseType->isAnyComplexType()) {
12584 const auto *CT = BaseType->castAs<ComplexType>();
12585 uint64_t Index = Entry.getAsArrayIndex();
12586 if (Index != 1)
12587 return false;
12588 BaseType = CT->getElementType();
12589 } else if (auto *FD = getAsField(Entry)) {
12590 bool Invalid;
12591 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
12592 return Invalid;
12593 BaseType = FD->getType();
12594 } else {
12595 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
12596 return false;
12597 }
12598 }
12599 return true;
12600}
12601
12602/// Tests to see if the LValue has a user-specified designator (that isn't
12603/// necessarily valid). Note that this always returns 'true' if the LValue has
12604/// an unsized array as its first designator entry, because there's currently no
12605/// way to tell if the user typed *foo or foo[0].
12606static bool refersToCompleteObject(const LValue &LVal) {
12607 if (LVal.Designator.Invalid)
12608 return false;
12609
12610 if (!LVal.Designator.Entries.empty())
12611 return LVal.Designator.isMostDerivedAnUnsizedArray();
12612
12613 if (!LVal.InvalidBase)
12614 return true;
12615
12616 // If `E` is a MemberExpr, then the first part of the designator is hiding in
12617 // the LValueBase.
12618 const auto *E = LVal.Base.dyn_cast<const Expr *>();
12619 return !E || !isa<MemberExpr>(E);
12620}
12621
12622/// Attempts to detect a user writing into a piece of memory that's impossible
12623/// to figure out the size of by just using types.
12624static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
12625 const SubobjectDesignator &Designator = LVal.Designator;
12626 // Notes:
12627 // - Users can only write off of the end when we have an invalid base. Invalid
12628 // bases imply we don't know where the memory came from.
12629 // - We used to be a bit more aggressive here; we'd only be conservative if
12630 // the array at the end was flexible, or if it had 0 or 1 elements. This
12631 // broke some common standard library extensions (PR30346), but was
12632 // otherwise seemingly fine. It may be useful to reintroduce this behavior
12633 // with some sort of list. OTOH, it seems that GCC is always
12634 // conservative with the last element in structs (if it's an array), so our
12635 // current behavior is more compatible than an explicit list approach would
12636 // be.
12637 auto isFlexibleArrayMember = [&] {
12639 FAMKind StrictFlexArraysLevel =
12640 Ctx.getLangOpts().getStrictFlexArraysLevel();
12641
12642 if (Designator.isMostDerivedAnUnsizedArray())
12643 return true;
12644
12645 if (StrictFlexArraysLevel == FAMKind::Default)
12646 return true;
12647
12648 if (Designator.getMostDerivedArraySize() == 0 &&
12649 StrictFlexArraysLevel != FAMKind::IncompleteOnly)
12650 return true;
12651
12652 if (Designator.getMostDerivedArraySize() == 1 &&
12653 StrictFlexArraysLevel == FAMKind::OneZeroOrIncomplete)
12654 return true;
12655
12656 return false;
12657 };
12658
12659 return LVal.InvalidBase &&
12660 Designator.Entries.size() == Designator.MostDerivedPathLength &&
12661 Designator.MostDerivedIsArrayElement && isFlexibleArrayMember() &&
12662 isDesignatorAtObjectEnd(Ctx, LVal);
12663}
12664
12665/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
12666/// Fails if the conversion would cause loss of precision.
12667static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
12668 CharUnits &Result) {
12669 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
12670 if (Int.ugt(CharUnitsMax))
12671 return false;
12672 Result = CharUnits::fromQuantity(Int.getZExtValue());
12673 return true;
12674}
12675
12676/// If we're evaluating the object size of an instance of a struct that
12677/// contains a flexible array member, add the size of the initializer.
12678static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T,
12679 const LValue &LV, CharUnits &Size) {
12680 if (!T.isNull() && T->isStructureType() &&
12682 if (const auto *V = LV.getLValueBase().dyn_cast<const ValueDecl *>())
12683 if (const auto *VD = dyn_cast<VarDecl>(V))
12684 if (VD->hasInit())
12685 Size += VD->getFlexibleArrayInitChars(Info.Ctx);
12686}
12687
12688/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
12689/// determine how many bytes exist from the beginning of the object to either
12690/// the end of the current subobject, or the end of the object itself, depending
12691/// on what the LValue looks like + the value of Type.
12692///
12693/// If this returns false, the value of Result is undefined.
12694static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
12695 unsigned Type, const LValue &LVal,
12696 CharUnits &EndOffset) {
12697 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
12698
12699 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
12700 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
12701 return false;
12702
12703 if (Ty->isReferenceType())
12704 Ty = Ty.getNonReferenceType();
12705
12706 return HandleSizeof(Info, ExprLoc, Ty, Result);
12707 };
12708
12709 // We want to evaluate the size of the entire object. This is a valid fallback
12710 // for when Type=1 and the designator is invalid, because we're asked for an
12711 // upper-bound.
12712 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
12713 // Type=3 wants a lower bound, so we can't fall back to this.
12714 if (Type == 3 && !DetermineForCompleteObject)
12715 return false;
12716
12717 llvm::APInt APEndOffset;
12718 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12719 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12720 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12721
12722 if (LVal.InvalidBase)
12723 return false;
12724
12725 QualType BaseTy = getObjectType(LVal.getLValueBase());
12726 const bool Ret = CheckedHandleSizeof(BaseTy, EndOffset);
12727 addFlexibleArrayMemberInitSize(Info, BaseTy, LVal, EndOffset);
12728 return Ret;
12729 }
12730
12731 // We want to evaluate the size of a subobject.
12732 const SubobjectDesignator &Designator = LVal.Designator;
12733
12734 // The following is a moderately common idiom in C:
12735 //
12736 // struct Foo { int a; char c[1]; };
12737 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
12738 // strcpy(&F->c[0], Bar);
12739 //
12740 // In order to not break too much legacy code, we need to support it.
12741 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
12742 // If we can resolve this to an alloc_size call, we can hand that back,
12743 // because we know for certain how many bytes there are to write to.
12744 llvm::APInt APEndOffset;
12745 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
12746 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
12747 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
12748
12749 // If we cannot determine the size of the initial allocation, then we can't
12750 // given an accurate upper-bound. However, we are still able to give
12751 // conservative lower-bounds for Type=3.
12752 if (Type == 1)
12753 return false;
12754 }
12755
12756 CharUnits BytesPerElem;
12757 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
12758 return false;
12759
12760 // According to the GCC documentation, we want the size of the subobject
12761 // denoted by the pointer. But that's not quite right -- what we actually
12762 // want is the size of the immediately-enclosing array, if there is one.
12763 int64_t ElemsRemaining;
12764 if (Designator.MostDerivedIsArrayElement &&
12765 Designator.Entries.size() == Designator.MostDerivedPathLength) {
12766 uint64_t ArraySize = Designator.getMostDerivedArraySize();
12767 uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
12768 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
12769 } else {
12770 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
12771 }
12772
12773 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
12774 return true;
12775}
12776
12777/// Tries to evaluate the __builtin_object_size for @p E. If successful,
12778/// returns true and stores the result in @p Size.
12779///
12780/// If @p WasError is non-null, this will report whether the failure to evaluate
12781/// is to be treated as an Error in IntExprEvaluator.
12782static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
12783 EvalInfo &Info, uint64_t &Size) {
12784 // Determine the denoted object.
12785 LValue LVal;
12786 {
12787 // The operand of __builtin_object_size is never evaluated for side-effects.
12788 // If there are any, but we can determine the pointed-to object anyway, then
12789 // ignore the side-effects.
12790 SpeculativeEvaluationRAII SpeculativeEval(Info);
12791 IgnoreSideEffectsRAII Fold(Info);
12792
12793 if (E->isGLValue()) {
12794 // It's possible for us to be given GLValues if we're called via
12795 // Expr::tryEvaluateObjectSize.
12796 APValue RVal;
12797 if (!EvaluateAsRValue(Info, E, RVal))
12798 return false;
12799 LVal.setFrom(Info.Ctx, RVal);
12800 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
12801 /*InvalidBaseOK=*/true))
12802 return false;
12803 }
12804
12805 // If we point to before the start of the object, there are no accessible
12806 // bytes.
12807 if (LVal.getLValueOffset().isNegative()) {
12808 Size = 0;
12809 return true;
12810 }
12811
12812 CharUnits EndOffset;
12813 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
12814 return false;
12815
12816 // If we've fallen outside of the end offset, just pretend there's nothing to
12817 // write to/read from.
12818 if (EndOffset <= LVal.getLValueOffset())
12819 Size = 0;
12820 else
12821 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
12822 return true;
12823}
12824
12825bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
12826 if (!IsConstantEvaluatedBuiltinCall(E))
12827 return ExprEvaluatorBaseTy::VisitCallExpr(E);
12828 return VisitBuiltinCallExpr(E, E->getBuiltinCallee());
12829}
12830
12831static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
12832 APValue &Val, APSInt &Alignment) {
12833 QualType SrcTy = E->getArg(0)->getType();
12834 if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
12835 return false;
12836 // Even though we are evaluating integer expressions we could get a pointer
12837 // argument for the __builtin_is_aligned() case.
12838 if (SrcTy->isPointerType()) {
12839 LValue Ptr;
12840 if (!EvaluatePointer(E->getArg(0), Ptr, Info))
12841 return false;
12842 Ptr.moveInto(Val);
12843 } else if (!SrcTy->isIntegralOrEnumerationType()) {
12844 Info.FFDiag(E->getArg(0));
12845 return false;
12846 } else {
12847 APSInt SrcInt;
12848 if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
12849 return false;
12850 assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
12851 "Bit widths must be the same");
12852 Val = APValue(SrcInt);
12853 }
12854 assert(Val.hasValue());
12855 return true;
12856}
12857
12858bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
12859 unsigned BuiltinOp) {
12860 switch (BuiltinOp) {
12861 default:
12862 return false;
12863
12864 case Builtin::BI__builtin_dynamic_object_size:
12865 case Builtin::BI__builtin_object_size: {
12866 // The type was checked when we built the expression.
12867 unsigned Type =
12868 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
12869 assert(Type <= 3 && "unexpected type");
12870
12871 uint64_t Size;
12872 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
12873 return Success(Size, E);
12874
12875 if (E->getArg(0)->HasSideEffects(Info.Ctx))
12876 return Success((Type & 2) ? 0 : -1, E);
12877
12878 // Expression had no side effects, but we couldn't statically determine the
12879 // size of the referenced object.
12880 switch (Info.EvalMode) {
12881 case EvalInfo::EM_ConstantExpression:
12882 case EvalInfo::EM_ConstantFold:
12883 case EvalInfo::EM_IgnoreSideEffects:
12884 // Leave it to IR generation.
12885 return Error(E);
12886 case EvalInfo::EM_ConstantExpressionUnevaluated:
12887 // Reduce it to a constant now.
12888 return Success((Type & 2) ? 0 : -1, E);
12889 }
12890
12891 llvm_unreachable("unexpected EvalMode");
12892 }
12893
12894 case Builtin::BI__builtin_os_log_format_buffer_size: {
12897 return Success(Layout.size().getQuantity(), E);
12898 }
12899
12900 case Builtin::BI__builtin_is_aligned: {
12901 APValue Src;
12902 APSInt Alignment;
12903 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12904 return false;
12905 if (Src.isLValue()) {
12906 // If we evaluated a pointer, check the minimum known alignment.
12907 LValue Ptr;
12908 Ptr.setFrom(Info.Ctx, Src);
12909 CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
12910 CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
12911 // We can return true if the known alignment at the computed offset is
12912 // greater than the requested alignment.
12913 assert(PtrAlign.isPowerOfTwo());
12914 assert(Alignment.isPowerOf2());
12915 if (PtrAlign.getQuantity() >= Alignment)
12916 return Success(1, E);
12917 // If the alignment is not known to be sufficient, some cases could still
12918 // be aligned at run time. However, if the requested alignment is less or
12919 // equal to the base alignment and the offset is not aligned, we know that
12920 // the run-time value can never be aligned.
12921 if (BaseAlignment.getQuantity() >= Alignment &&
12922 PtrAlign.getQuantity() < Alignment)
12923 return Success(0, E);
12924 // Otherwise we can't infer whether the value is sufficiently aligned.
12925 // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
12926 // in cases where we can't fully evaluate the pointer.
12927 Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
12928 << Alignment;
12929 return false;
12930 }
12931 assert(Src.isInt());
12932 return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
12933 }
12934 case Builtin::BI__builtin_align_up: {
12935 APValue Src;
12936 APSInt Alignment;
12937 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12938 return false;
12939 if (!Src.isInt())
12940 return Error(E);
12941 APSInt AlignedVal =
12942 APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
12943 Src.getInt().isUnsigned());
12944 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12945 return Success(AlignedVal, E);
12946 }
12947 case Builtin::BI__builtin_align_down: {
12948 APValue Src;
12949 APSInt Alignment;
12950 if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
12951 return false;
12952 if (!Src.isInt())
12953 return Error(E);
12954 APSInt AlignedVal =
12955 APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
12956 assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
12957 return Success(AlignedVal, E);
12958 }
12959
12960 case Builtin::BI__builtin_bitreverse8:
12961 case Builtin::BI__builtin_bitreverse16:
12962 case Builtin::BI__builtin_bitreverse32:
12963 case Builtin::BI__builtin_bitreverse64:
12964 case Builtin::BI__builtin_elementwise_bitreverse: {
12965 APSInt Val;
12966 if (!EvaluateInteger(E->getArg(0), Val, Info))
12967 return false;
12968
12969 return Success(Val.reverseBits(), E);
12970 }
12971
12972 case Builtin::BI__builtin_bswap16:
12973 case Builtin::BI__builtin_bswap32:
12974 case Builtin::BI__builtin_bswap64: {
12975 APSInt Val;
12976 if (!EvaluateInteger(E->getArg(0), Val, Info))
12977 return false;
12978
12979 return Success(Val.byteSwap(), E);
12980 }
12981
12982 case Builtin::BI__builtin_classify_type:
12983 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
12984
12985 case Builtin::BI__builtin_clrsb:
12986 case Builtin::BI__builtin_clrsbl:
12987 case Builtin::BI__builtin_clrsbll: {
12988 APSInt Val;
12989 if (!EvaluateInteger(E->getArg(0), Val, Info))
12990 return false;
12991
12992 return Success(Val.getBitWidth() - Val.getSignificantBits(), E);
12993 }
12994
12995 case Builtin::BI__builtin_clz:
12996 case Builtin::BI__builtin_clzl:
12997 case Builtin::BI__builtin_clzll:
12998 case Builtin::BI__builtin_clzs:
12999 case Builtin::BI__builtin_clzg:
13000 case Builtin::BI__lzcnt16: // Microsoft variants of count leading-zeroes
13001 case Builtin::BI__lzcnt:
13002 case Builtin::BI__lzcnt64: {
13003 APSInt Val;
13004 if (!EvaluateInteger(E->getArg(0), Val, Info))
13005 return false;
13006
13007 std::optional<APSInt> Fallback;
13008 if (BuiltinOp == Builtin::BI__builtin_clzg && E->getNumArgs() > 1) {
13009 APSInt FallbackTemp;
13010 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13011 return false;
13012 Fallback = FallbackTemp;
13013 }
13014
13015 if (!Val) {
13016 if (Fallback)
13017 return Success(*Fallback, E);
13018
13019 // When the argument is 0, the result of GCC builtins is undefined,
13020 // whereas for Microsoft intrinsics, the result is the bit-width of the
13021 // argument.
13022 bool ZeroIsUndefined = BuiltinOp != Builtin::BI__lzcnt16 &&
13023 BuiltinOp != Builtin::BI__lzcnt &&
13024 BuiltinOp != Builtin::BI__lzcnt64;
13025
13026 if (ZeroIsUndefined)
13027 return Error(E);
13028 }
13029
13030 return Success(Val.countl_zero(), E);
13031 }
13032
13033 case Builtin::BI__builtin_constant_p: {
13034 const Expr *Arg = E->getArg(0);
13035 if (EvaluateBuiltinConstantP(Info, Arg))
13036 return Success(true, E);
13037 if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
13038 // Outside a constant context, eagerly evaluate to false in the presence
13039 // of side-effects in order to avoid -Wunsequenced false-positives in
13040 // a branch on __builtin_constant_p(expr).
13041 return Success(false, E);
13042 }
13043 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13044 return false;
13045 }
13046
13047 case Builtin::BI__noop:
13048 // __noop always evaluates successfully and returns 0.
13049 return Success(0, E);
13050
13051 case Builtin::BI__builtin_is_constant_evaluated: {
13052 const auto *Callee = Info.CurrentCall->getCallee();
13053 if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
13054 (Info.CallStackDepth == 1 ||
13055 (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
13056 Callee->getIdentifier() &&
13057 Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
13058 // FIXME: Find a better way to avoid duplicated diagnostics.
13059 if (Info.EvalStatus.Diag)
13060 Info.report((Info.CallStackDepth == 1)
13061 ? E->getExprLoc()
13062 : Info.CurrentCall->getCallRange().getBegin(),
13063 diag::warn_is_constant_evaluated_always_true_constexpr)
13064 << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
13065 : "std::is_constant_evaluated");
13066 }
13067
13068 return Success(Info.InConstantContext, E);
13069 }
13070
13071 case Builtin::BI__builtin_is_within_lifetime:
13072 if (auto result = EvaluateBuiltinIsWithinLifetime(*this, E))
13073 return Success(*result, E);
13074 return false;
13075
13076 case Builtin::BI__builtin_ctz:
13077 case Builtin::BI__builtin_ctzl:
13078 case Builtin::BI__builtin_ctzll:
13079 case Builtin::BI__builtin_ctzs:
13080 case Builtin::BI__builtin_ctzg: {
13081 APSInt Val;
13082 if (!EvaluateInteger(E->getArg(0), Val, Info))
13083 return false;
13084
13085 std::optional<APSInt> Fallback;
13086 if (BuiltinOp == Builtin::BI__builtin_ctzg && E->getNumArgs() > 1) {
13087 APSInt FallbackTemp;
13088 if (!EvaluateInteger(E->getArg(1), FallbackTemp, Info))
13089 return false;
13090 Fallback = FallbackTemp;
13091 }
13092
13093 if (!Val) {
13094 if (Fallback)
13095 return Success(*Fallback, E);
13096
13097 return Error(E);
13098 }
13099
13100 return Success(Val.countr_zero(), E);
13101 }
13102
13103 case Builtin::BI__builtin_eh_return_data_regno: {
13104 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
13105 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
13106 return Success(Operand, E);
13107 }
13108
13109 case Builtin::BI__builtin_expect:
13110 case Builtin::BI__builtin_expect_with_probability:
13111 return Visit(E->getArg(0));
13112
13113 case Builtin::BI__builtin_ptrauth_string_discriminator: {
13114 const auto *Literal =
13115 cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts());
13116 uint64_t Result = getPointerAuthStableSipHash(Literal->getString());
13117 return Success(Result, E);
13118 }
13119
13120 case Builtin::BI__builtin_ffs:
13121 case Builtin::BI__builtin_ffsl:
13122 case Builtin::BI__builtin_ffsll: {
13123 APSInt Val;
13124 if (!EvaluateInteger(E->getArg(0), Val, Info))
13125 return false;
13126
13127 unsigned N = Val.countr_zero();
13128 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
13129 }
13130
13131 case Builtin::BI__builtin_fpclassify: {
13132 APFloat Val(0.0);
13133 if (!EvaluateFloat(E->getArg(5), Val, Info))
13134 return false;
13135 unsigned Arg;
13136 switch (Val.getCategory()) {
13137 case APFloat::fcNaN: Arg = 0; break;
13138 case APFloat::fcInfinity: Arg = 1; break;
13139 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
13140 case APFloat::fcZero: Arg = 4; break;
13141 }
13142 return Visit(E->getArg(Arg));
13143 }
13144
13145 case Builtin::BI__builtin_isinf_sign: {
13146 APFloat Val(0.0);
13147 return EvaluateFloat(E->getArg(0), Val, Info) &&
13148 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
13149 }
13150
13151 case Builtin::BI__builtin_isinf: {
13152 APFloat Val(0.0);
13153 return EvaluateFloat(E->getArg(0), Val, Info) &&
13154 Success(Val.isInfinity() ? 1 : 0, E);
13155 }
13156
13157 case Builtin::BI__builtin_isfinite: {
13158 APFloat Val(0.0);
13159 return EvaluateFloat(E->getArg(0), Val, Info) &&
13160 Success(Val.isFinite() ? 1 : 0, E);
13161 }
13162
13163 case Builtin::BI__builtin_isnan: {
13164 APFloat Val(0.0);
13165 return EvaluateFloat(E->getArg(0), Val, Info) &&
13166 Success(Val.isNaN() ? 1 : 0, E);
13167 }
13168
13169 case Builtin::BI__builtin_isnormal: {
13170 APFloat Val(0.0);
13171 return EvaluateFloat(E->getArg(0), Val, Info) &&
13172 Success(Val.isNormal() ? 1 : 0, E);
13173 }
13174
13175 case Builtin::BI__builtin_issubnormal: {
13176 APFloat Val(0.0);
13177 return EvaluateFloat(E->getArg(0), Val, Info) &&
13178 Success(Val.isDenormal() ? 1 : 0, E);
13179 }
13180
13181 case Builtin::BI__builtin_iszero: {
13182 APFloat Val(0.0);
13183 return EvaluateFloat(E->getArg(0), Val, Info) &&
13184 Success(Val.isZero() ? 1 : 0, E);
13185 }
13186
13187 case Builtin::BI__builtin_signbit:
13188 case Builtin::BI__builtin_signbitf:
13189 case Builtin::BI__builtin_signbitl: {
13190 APFloat Val(0.0);
13191 return EvaluateFloat(E->getArg(0), Val, Info) &&
13192 Success(Val.isNegative() ? 1 : 0, E);
13193 }
13194
13195 case Builtin::BI__builtin_isgreater:
13196 case Builtin::BI__builtin_isgreaterequal:
13197 case Builtin::BI__builtin_isless:
13198 case Builtin::BI__builtin_islessequal:
13199 case Builtin::BI__builtin_islessgreater:
13200 case Builtin::BI__builtin_isunordered: {
13201 APFloat LHS(0.0);
13202 APFloat RHS(0.0);
13203 if (!EvaluateFloat(E->getArg(0), LHS, Info) ||
13204 !EvaluateFloat(E->getArg(1), RHS, Info))
13205 return false;
13206
13207 return Success(
13208 [&] {
13209 switch (BuiltinOp) {
13210 case Builtin::BI__builtin_isgreater:
13211 return LHS > RHS;
13212 case Builtin::BI__builtin_isgreaterequal:
13213 return LHS >= RHS;
13214 case Builtin::BI__builtin_isless:
13215 return LHS < RHS;
13216 case Builtin::BI__builtin_islessequal:
13217 return LHS <= RHS;
13218 case Builtin::BI__builtin_islessgreater: {
13219 APFloat::cmpResult cmp = LHS.compare(RHS);
13220 return cmp == APFloat::cmpResult::cmpLessThan ||
13221 cmp == APFloat::cmpResult::cmpGreaterThan;
13222 }
13223 case Builtin::BI__builtin_isunordered:
13224 return LHS.compare(RHS) == APFloat::cmpResult::cmpUnordered;
13225 default:
13226 llvm_unreachable("Unexpected builtin ID: Should be a floating "
13227 "point comparison function");
13228 }
13229 }()
13230 ? 1
13231 : 0,
13232 E);
13233 }
13234
13235 case Builtin::BI__builtin_issignaling: {
13236 APFloat Val(0.0);
13237 return EvaluateFloat(E->getArg(0), Val, Info) &&
13238 Success(Val.isSignaling() ? 1 : 0, E);
13239 }
13240
13241 case Builtin::BI__builtin_isfpclass: {
13242 APSInt MaskVal;
13243 if (!EvaluateInteger(E->getArg(1), MaskVal, Info))
13244 return false;
13245 unsigned Test = static_cast<llvm::FPClassTest>(MaskVal.getZExtValue());
13246 APFloat Val(0.0);
13247 return EvaluateFloat(E->getArg(0), Val, Info) &&
13248 Success((Val.classify() & Test) ? 1 : 0, E);
13249 }
13250
13251 case Builtin::BI__builtin_parity:
13252 case Builtin::BI__builtin_parityl:
13253 case Builtin::BI__builtin_parityll: {
13254 APSInt Val;
13255 if (!EvaluateInteger(E->getArg(0), Val, Info))
13256 return false;
13257
13258 return Success(Val.popcount() % 2, E);
13259 }
13260
13261 case Builtin::BI__builtin_abs:
13262 case Builtin::BI__builtin_labs:
13263 case Builtin::BI__builtin_llabs: {
13264 APSInt Val;
13265 if (!EvaluateInteger(E->getArg(0), Val, Info))
13266 return false;
13267 if (Val == APSInt(APInt::getSignedMinValue(Val.getBitWidth()),
13268 /*IsUnsigned=*/false))
13269 return false;
13270 if (Val.isNegative())
13271 Val.negate();
13272 return Success(Val, E);
13273 }
13274
13275 case Builtin::BI__builtin_popcount:
13276 case Builtin::BI__builtin_popcountl:
13277 case Builtin::BI__builtin_popcountll:
13278 case Builtin::BI__builtin_popcountg:
13279 case Builtin::BI__builtin_elementwise_popcount:
13280 case Builtin::BI__popcnt16: // Microsoft variants of popcount
13281 case Builtin::BI__popcnt:
13282 case Builtin::BI__popcnt64: {
13283 APSInt Val;
13284 if (!EvaluateInteger(E->getArg(0), Val, Info))
13285 return false;
13286
13287 return Success(Val.popcount(), E);
13288 }
13289
13290 case Builtin::BI__builtin_rotateleft8:
13291 case Builtin::BI__builtin_rotateleft16:
13292 case Builtin::BI__builtin_rotateleft32:
13293 case Builtin::BI__builtin_rotateleft64:
13294 case Builtin::BI_rotl8: // Microsoft variants of rotate right
13295 case Builtin::BI_rotl16:
13296 case Builtin::BI_rotl:
13297 case Builtin::BI_lrotl:
13298 case Builtin::BI_rotl64: {
13299 APSInt Val, Amt;
13300 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13301 !EvaluateInteger(E->getArg(1), Amt, Info))
13302 return false;
13303
13304 return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
13305 }
13306
13307 case Builtin::BI__builtin_rotateright8:
13308 case Builtin::BI__builtin_rotateright16:
13309 case Builtin::BI__builtin_rotateright32:
13310 case Builtin::BI__builtin_rotateright64:
13311 case Builtin::BI_rotr8: // Microsoft variants of rotate right
13312 case Builtin::BI_rotr16:
13313 case Builtin::BI_rotr:
13314 case Builtin::BI_lrotr:
13315 case Builtin::BI_rotr64: {
13316 APSInt Val, Amt;
13317 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13318 !EvaluateInteger(E->getArg(1), Amt, Info))
13319 return false;
13320
13321 return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
13322 }
13323
13324 case Builtin::BI__builtin_elementwise_add_sat: {
13325 APSInt LHS, RHS;
13326 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13327 !EvaluateInteger(E->getArg(1), RHS, Info))
13328 return false;
13329
13330 APInt Result = LHS.isSigned() ? LHS.sadd_sat(RHS) : LHS.uadd_sat(RHS);
13331 return Success(APSInt(Result, !LHS.isSigned()), E);
13332 }
13333 case Builtin::BI__builtin_elementwise_sub_sat: {
13334 APSInt LHS, RHS;
13335 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13336 !EvaluateInteger(E->getArg(1), RHS, Info))
13337 return false;
13338
13339 APInt Result = LHS.isSigned() ? LHS.ssub_sat(RHS) : LHS.usub_sat(RHS);
13340 return Success(APSInt(Result, !LHS.isSigned()), E);
13341 }
13342
13343 case Builtin::BIstrlen:
13344 case Builtin::BIwcslen:
13345 // A call to strlen is not a constant expression.
13346 if (Info.getLangOpts().CPlusPlus11)
13347 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13348 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13349 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13350 else
13351 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13352 [[fallthrough]];
13353 case Builtin::BI__builtin_strlen:
13354 case Builtin::BI__builtin_wcslen: {
13355 // As an extension, we support __builtin_strlen() as a constant expression,
13356 // and support folding strlen() to a constant.
13357 uint64_t StrLen;
13358 if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
13359 return Success(StrLen, E);
13360 return false;
13361 }
13362
13363 case Builtin::BIstrcmp:
13364 case Builtin::BIwcscmp:
13365 case Builtin::BIstrncmp:
13366 case Builtin::BIwcsncmp:
13367 case Builtin::BImemcmp:
13368 case Builtin::BIbcmp:
13369 case Builtin::BIwmemcmp:
13370 // A call to strlen is not a constant expression.
13371 if (Info.getLangOpts().CPlusPlus11)
13372 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
13373 << /*isConstexpr*/ 0 << /*isConstructor*/ 0
13374 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp);
13375 else
13376 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
13377 [[fallthrough]];
13378 case Builtin::BI__builtin_strcmp:
13379 case Builtin::BI__builtin_wcscmp:
13380 case Builtin::BI__builtin_strncmp:
13381 case Builtin::BI__builtin_wcsncmp:
13382 case Builtin::BI__builtin_memcmp:
13383 case Builtin::BI__builtin_bcmp:
13384 case Builtin::BI__builtin_wmemcmp: {
13385 LValue String1, String2;
13386 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
13387 !EvaluatePointer(E->getArg(1), String2, Info))
13388 return false;
13389
13390 uint64_t MaxLength = uint64_t(-1);
13391 if (BuiltinOp != Builtin::BIstrcmp &&
13392 BuiltinOp != Builtin::BIwcscmp &&
13393 BuiltinOp != Builtin::BI__builtin_strcmp &&
13394 BuiltinOp != Builtin::BI__builtin_wcscmp) {
13395 APSInt N;
13396 if (!EvaluateInteger(E->getArg(2), N, Info))
13397 return false;
13398 MaxLength = N.getZExtValue();
13399 }
13400
13401 // Empty substrings compare equal by definition.
13402 if (MaxLength == 0u)
13403 return Success(0, E);
13404
13405 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13406 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
13407 String1.Designator.Invalid || String2.Designator.Invalid)
13408 return false;
13409
13410 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
13411 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
13412
13413 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
13414 BuiltinOp == Builtin::BIbcmp ||
13415 BuiltinOp == Builtin::BI__builtin_memcmp ||
13416 BuiltinOp == Builtin::BI__builtin_bcmp;
13417
13418 assert(IsRawByte ||
13419 (Info.Ctx.hasSameUnqualifiedType(
13420 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
13421 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
13422
13423 // For memcmp, allow comparing any arrays of '[[un]signed] char' or
13424 // 'char8_t', but no other types.
13425 if (IsRawByte &&
13426 !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
13427 // FIXME: Consider using our bit_cast implementation to support this.
13428 Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
13429 << Info.Ctx.BuiltinInfo.getQuotedName(BuiltinOp) << CharTy1
13430 << CharTy2;
13431 return false;
13432 }
13433
13434 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
13435 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
13436 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
13437 Char1.isInt() && Char2.isInt();
13438 };
13439 const auto &AdvanceElems = [&] {
13440 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
13441 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
13442 };
13443
13444 bool StopAtNull =
13445 (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
13446 BuiltinOp != Builtin::BIwmemcmp &&
13447 BuiltinOp != Builtin::BI__builtin_memcmp &&
13448 BuiltinOp != Builtin::BI__builtin_bcmp &&
13449 BuiltinOp != Builtin::BI__builtin_wmemcmp);
13450 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
13451 BuiltinOp == Builtin::BIwcsncmp ||
13452 BuiltinOp == Builtin::BIwmemcmp ||
13453 BuiltinOp == Builtin::BI__builtin_wcscmp ||
13454 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
13455 BuiltinOp == Builtin::BI__builtin_wmemcmp;
13456
13457 for (; MaxLength; --MaxLength) {
13458 APValue Char1, Char2;
13459 if (!ReadCurElems(Char1, Char2))
13460 return false;
13461 if (Char1.getInt().ne(Char2.getInt())) {
13462 if (IsWide) // wmemcmp compares with wchar_t signedness.
13463 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
13464 // memcmp always compares unsigned chars.
13465 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
13466 }
13467 if (StopAtNull && !Char1.getInt())
13468 return Success(0, E);
13469 assert(!(StopAtNull && !Char2.getInt()));
13470 if (!AdvanceElems())
13471 return false;
13472 }
13473 // We hit the strncmp / memcmp limit.
13474 return Success(0, E);
13475 }
13476
13477 case Builtin::BI__atomic_always_lock_free:
13478 case Builtin::BI__atomic_is_lock_free:
13479 case Builtin::BI__c11_atomic_is_lock_free: {
13480 APSInt SizeVal;
13481 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
13482 return false;
13483
13484 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
13485 // of two less than or equal to the maximum inline atomic width, we know it
13486 // is lock-free. If the size isn't a power of two, or greater than the
13487 // maximum alignment where we promote atomics, we know it is not lock-free
13488 // (at least not in the sense of atomic_is_lock_free). Otherwise,
13489 // the answer can only be determined at runtime; for example, 16-byte
13490 // atomics have lock-free implementations on some, but not all,
13491 // x86-64 processors.
13492
13493 // Check power-of-two.
13494 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
13495 if (Size.isPowerOfTwo()) {
13496 // Check against inlining width.
13497 unsigned InlineWidthBits =
13498 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
13499 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
13500 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
13501 Size == CharUnits::One())
13502 return Success(1, E);
13503
13504 // If the pointer argument can be evaluated to a compile-time constant
13505 // integer (or nullptr), check if that value is appropriately aligned.
13506 const Expr *PtrArg = E->getArg(1);
13508 APSInt IntResult;
13509 if (PtrArg->EvaluateAsRValue(ExprResult, Info.Ctx) &&
13510 ExprResult.Val.toIntegralConstant(IntResult, PtrArg->getType(),
13511 Info.Ctx) &&
13512 IntResult.isAligned(Size.getAsAlign()))
13513 return Success(1, E);
13514
13515 // Otherwise, check if the type's alignment against Size.
13516 if (auto *ICE = dyn_cast<ImplicitCastExpr>(PtrArg)) {
13517 // Drop the potential implicit-cast to 'const volatile void*', getting
13518 // the underlying type.
13519 if (ICE->getCastKind() == CK_BitCast)
13520 PtrArg = ICE->getSubExpr();
13521 }
13522
13523 if (auto PtrTy = PtrArg->getType()->getAs<PointerType>()) {
13524 QualType PointeeType = PtrTy->getPointeeType();
13525 if (!PointeeType->isIncompleteType() &&
13526 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
13527 // OK, we will inline operations on this object.
13528 return Success(1, E);
13529 }
13530 }
13531 }
13532 }
13533
13534 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
13535 Success(0, E) : Error(E);
13536 }
13537 case Builtin::BI__builtin_addcb:
13538 case Builtin::BI__builtin_addcs:
13539 case Builtin::BI__builtin_addc:
13540 case Builtin::BI__builtin_addcl:
13541 case Builtin::BI__builtin_addcll:
13542 case Builtin::BI__builtin_subcb:
13543 case Builtin::BI__builtin_subcs:
13544 case Builtin::BI__builtin_subc:
13545 case Builtin::BI__builtin_subcl:
13546 case Builtin::BI__builtin_subcll: {
13547 LValue CarryOutLValue;
13548 APSInt LHS, RHS, CarryIn, CarryOut, Result;
13549 QualType ResultType = E->getArg(0)->getType();
13550 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13551 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13552 !EvaluateInteger(E->getArg(2), CarryIn, Info) ||
13553 !EvaluatePointer(E->getArg(3), CarryOutLValue, Info))
13554 return false;
13555 // Copy the number of bits and sign.
13556 Result = LHS;
13557 CarryOut = LHS;
13558
13559 bool FirstOverflowed = false;
13560 bool SecondOverflowed = false;
13561 switch (BuiltinOp) {
13562 default:
13563 llvm_unreachable("Invalid value for BuiltinOp");
13564 case Builtin::BI__builtin_addcb:
13565 case Builtin::BI__builtin_addcs:
13566 case Builtin::BI__builtin_addc:
13567 case Builtin::BI__builtin_addcl:
13568 case Builtin::BI__builtin_addcll:
13569 Result =
13570 LHS.uadd_ov(RHS, FirstOverflowed).uadd_ov(CarryIn, SecondOverflowed);
13571 break;
13572 case Builtin::BI__builtin_subcb:
13573 case Builtin::BI__builtin_subcs:
13574 case Builtin::BI__builtin_subc:
13575 case Builtin::BI__builtin_subcl:
13576 case Builtin::BI__builtin_subcll:
13577 Result =
13578 LHS.usub_ov(RHS, FirstOverflowed).usub_ov(CarryIn, SecondOverflowed);
13579 break;
13580 }
13581
13582 // It is possible for both overflows to happen but CGBuiltin uses an OR so
13583 // this is consistent.
13584 CarryOut = (uint64_t)(FirstOverflowed | SecondOverflowed);
13585 APValue APV{CarryOut};
13586 if (!handleAssignment(Info, E, CarryOutLValue, ResultType, APV))
13587 return false;
13588 return Success(Result, E);
13589 }
13590 case Builtin::BI__builtin_add_overflow:
13591 case Builtin::BI__builtin_sub_overflow:
13592 case Builtin::BI__builtin_mul_overflow:
13593 case Builtin::BI__builtin_sadd_overflow:
13594 case Builtin::BI__builtin_uadd_overflow:
13595 case Builtin::BI__builtin_uaddl_overflow:
13596 case Builtin::BI__builtin_uaddll_overflow:
13597 case Builtin::BI__builtin_usub_overflow:
13598 case Builtin::BI__builtin_usubl_overflow:
13599 case Builtin::BI__builtin_usubll_overflow:
13600 case Builtin::BI__builtin_umul_overflow:
13601 case Builtin::BI__builtin_umull_overflow:
13602 case Builtin::BI__builtin_umulll_overflow:
13603 case Builtin::BI__builtin_saddl_overflow:
13604 case Builtin::BI__builtin_saddll_overflow:
13605 case Builtin::BI__builtin_ssub_overflow:
13606 case Builtin::BI__builtin_ssubl_overflow:
13607 case Builtin::BI__builtin_ssubll_overflow:
13608 case Builtin::BI__builtin_smul_overflow:
13609 case Builtin::BI__builtin_smull_overflow:
13610 case Builtin::BI__builtin_smulll_overflow: {
13611 LValue ResultLValue;
13612 APSInt LHS, RHS;
13613
13614 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
13615 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
13616 !EvaluateInteger(E->getArg(1), RHS, Info) ||
13617 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
13618 return false;
13619
13620 APSInt Result;
13621 bool DidOverflow = false;
13622
13623 // If the types don't have to match, enlarge all 3 to the largest of them.
13624 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13625 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13626 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13627 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
13629 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
13631 uint64_t LHSSize = LHS.getBitWidth();
13632 uint64_t RHSSize = RHS.getBitWidth();
13633 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
13634 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
13635
13636 // Add an additional bit if the signedness isn't uniformly agreed to. We
13637 // could do this ONLY if there is a signed and an unsigned that both have
13638 // MaxBits, but the code to check that is pretty nasty. The issue will be
13639 // caught in the shrink-to-result later anyway.
13640 if (IsSigned && !AllSigned)
13641 ++MaxBits;
13642
13643 LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
13644 RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
13645 Result = APSInt(MaxBits, !IsSigned);
13646 }
13647
13648 // Find largest int.
13649 switch (BuiltinOp) {
13650 default:
13651 llvm_unreachable("Invalid value for BuiltinOp");
13652 case Builtin::BI__builtin_add_overflow:
13653 case Builtin::BI__builtin_sadd_overflow:
13654 case Builtin::BI__builtin_saddl_overflow:
13655 case Builtin::BI__builtin_saddll_overflow:
13656 case Builtin::BI__builtin_uadd_overflow:
13657 case Builtin::BI__builtin_uaddl_overflow:
13658 case Builtin::BI__builtin_uaddll_overflow:
13659 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
13660 : LHS.uadd_ov(RHS, DidOverflow);
13661 break;
13662 case Builtin::BI__builtin_sub_overflow:
13663 case Builtin::BI__builtin_ssub_overflow:
13664 case Builtin::BI__builtin_ssubl_overflow:
13665 case Builtin::BI__builtin_ssubll_overflow:
13666 case Builtin::BI__builtin_usub_overflow:
13667 case Builtin::BI__builtin_usubl_overflow:
13668 case Builtin::BI__builtin_usubll_overflow:
13669 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
13670 : LHS.usub_ov(RHS, DidOverflow);
13671 break;
13672 case Builtin::BI__builtin_mul_overflow:
13673 case Builtin::BI__builtin_smul_overflow:
13674 case Builtin::BI__builtin_smull_overflow:
13675 case Builtin::BI__builtin_smulll_overflow:
13676 case Builtin::BI__builtin_umul_overflow:
13677 case Builtin::BI__builtin_umull_overflow:
13678 case Builtin::BI__builtin_umulll_overflow:
13679 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
13680 : LHS.umul_ov(RHS, DidOverflow);
13681 break;
13682 }
13683
13684 // In the case where multiple sizes are allowed, truncate and see if
13685 // the values are the same.
13686 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
13687 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
13688 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
13689 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
13690 // since it will give us the behavior of a TruncOrSelf in the case where
13691 // its parameter <= its size. We previously set Result to be at least the
13692 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
13693 // will work exactly like TruncOrSelf.
13694 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
13695 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
13696
13697 if (!APSInt::isSameValue(Temp, Result))
13698 DidOverflow = true;
13699 Result = Temp;
13700 }
13701
13702 APValue APV{Result};
13703 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13704 return false;
13705 return Success(DidOverflow, E);
13706 }
13707
13708 case Builtin::BI__builtin_reduce_add:
13709 case Builtin::BI__builtin_reduce_mul:
13710 case Builtin::BI__builtin_reduce_and:
13711 case Builtin::BI__builtin_reduce_or:
13712 case Builtin::BI__builtin_reduce_xor:
13713 case Builtin::BI__builtin_reduce_min:
13714 case Builtin::BI__builtin_reduce_max: {
13715 APValue Source;
13716 if (!EvaluateAsRValue(Info, E->getArg(0), Source))
13717 return false;
13718
13719 unsigned SourceLen = Source.getVectorLength();
13720 APSInt Reduced = Source.getVectorElt(0).getInt();
13721 for (unsigned EltNum = 1; EltNum < SourceLen; ++EltNum) {
13722 switch (BuiltinOp) {
13723 default:
13724 return false;
13725 case Builtin::BI__builtin_reduce_add: {
13727 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13728 Reduced.getBitWidth() + 1, std::plus<APSInt>(), Reduced))
13729 return false;
13730 break;
13731 }
13732 case Builtin::BI__builtin_reduce_mul: {
13734 Info, E, Reduced, Source.getVectorElt(EltNum).getInt(),
13735 Reduced.getBitWidth() * 2, std::multiplies<APSInt>(), Reduced))
13736 return false;
13737 break;
13738 }
13739 case Builtin::BI__builtin_reduce_and: {
13740 Reduced &= Source.getVectorElt(EltNum).getInt();
13741 break;
13742 }
13743 case Builtin::BI__builtin_reduce_or: {
13744 Reduced |= Source.getVectorElt(EltNum).getInt();
13745 break;
13746 }
13747 case Builtin::BI__builtin_reduce_xor: {
13748 Reduced ^= Source.getVectorElt(EltNum).getInt();
13749 break;
13750 }
13751 case Builtin::BI__builtin_reduce_min: {
13752 Reduced = std::min(Reduced, Source.getVectorElt(EltNum).getInt());
13753 break;
13754 }
13755 case Builtin::BI__builtin_reduce_max: {
13756 Reduced = std::max(Reduced, Source.getVectorElt(EltNum).getInt());
13757 break;
13758 }
13759 }
13760 }
13761
13762 return Success(Reduced, E);
13763 }
13764
13765 case clang::X86::BI__builtin_ia32_addcarryx_u32:
13766 case clang::X86::BI__builtin_ia32_addcarryx_u64:
13767 case clang::X86::BI__builtin_ia32_subborrow_u32:
13768 case clang::X86::BI__builtin_ia32_subborrow_u64: {
13769 LValue ResultLValue;
13770 APSInt CarryIn, LHS, RHS;
13771 QualType ResultType = E->getArg(3)->getType()->getPointeeType();
13772 if (!EvaluateInteger(E->getArg(0), CarryIn, Info) ||
13773 !EvaluateInteger(E->getArg(1), LHS, Info) ||
13774 !EvaluateInteger(E->getArg(2), RHS, Info) ||
13775 !EvaluatePointer(E->getArg(3), ResultLValue, Info))
13776 return false;
13777
13778 bool IsAdd = BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u32 ||
13779 BuiltinOp == clang::X86::BI__builtin_ia32_addcarryx_u64;
13780
13781 unsigned BitWidth = LHS.getBitWidth();
13782 unsigned CarryInBit = CarryIn.ugt(0) ? 1 : 0;
13783 APInt ExResult =
13784 IsAdd
13785 ? (LHS.zext(BitWidth + 1) + (RHS.zext(BitWidth + 1) + CarryInBit))
13786 : (LHS.zext(BitWidth + 1) - (RHS.zext(BitWidth + 1) + CarryInBit));
13787
13788 APInt Result = ExResult.extractBits(BitWidth, 0);
13789 uint64_t CarryOut = ExResult.extractBitsAsZExtValue(1, BitWidth);
13790
13791 APValue APV{APSInt(Result, /*isUnsigned=*/true)};
13792 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
13793 return false;
13794 return Success(CarryOut, E);
13795 }
13796
13797 case clang::X86::BI__builtin_ia32_bextr_u32:
13798 case clang::X86::BI__builtin_ia32_bextr_u64:
13799 case clang::X86::BI__builtin_ia32_bextri_u32:
13800 case clang::X86::BI__builtin_ia32_bextri_u64: {
13801 APSInt Val, Idx;
13802 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13803 !EvaluateInteger(E->getArg(1), Idx, Info))
13804 return false;
13805
13806 unsigned BitWidth = Val.getBitWidth();
13807 uint64_t Shift = Idx.extractBitsAsZExtValue(8, 0);
13808 uint64_t Length = Idx.extractBitsAsZExtValue(8, 8);
13809 Length = Length > BitWidth ? BitWidth : Length;
13810
13811 // Handle out of bounds cases.
13812 if (Length == 0 || Shift >= BitWidth)
13813 return Success(0, E);
13814
13815 uint64_t Result = Val.getZExtValue() >> Shift;
13816 Result &= llvm::maskTrailingOnes<uint64_t>(Length);
13817 return Success(Result, E);
13818 }
13819
13820 case clang::X86::BI__builtin_ia32_bzhi_si:
13821 case clang::X86::BI__builtin_ia32_bzhi_di: {
13822 APSInt Val, Idx;
13823 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13824 !EvaluateInteger(E->getArg(1), Idx, Info))
13825 return false;
13826
13827 unsigned BitWidth = Val.getBitWidth();
13828 unsigned Index = Idx.extractBitsAsZExtValue(8, 0);
13829 if (Index < BitWidth)
13830 Val.clearHighBits(BitWidth - Index);
13831 return Success(Val, E);
13832 }
13833
13834 case clang::X86::BI__builtin_ia32_lzcnt_u16:
13835 case clang::X86::BI__builtin_ia32_lzcnt_u32:
13836 case clang::X86::BI__builtin_ia32_lzcnt_u64: {
13837 APSInt Val;
13838 if (!EvaluateInteger(E->getArg(0), Val, Info))
13839 return false;
13840 return Success(Val.countLeadingZeros(), E);
13841 }
13842
13843 case clang::X86::BI__builtin_ia32_tzcnt_u16:
13844 case clang::X86::BI__builtin_ia32_tzcnt_u32:
13845 case clang::X86::BI__builtin_ia32_tzcnt_u64: {
13846 APSInt Val;
13847 if (!EvaluateInteger(E->getArg(0), Val, Info))
13848 return false;
13849 return Success(Val.countTrailingZeros(), E);
13850 }
13851
13852 case clang::X86::BI__builtin_ia32_pdep_si:
13853 case clang::X86::BI__builtin_ia32_pdep_di: {
13854 APSInt Val, Msk;
13855 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13856 !EvaluateInteger(E->getArg(1), Msk, Info))
13857 return false;
13858
13859 unsigned BitWidth = Val.getBitWidth();
13860 APInt Result = APInt::getZero(BitWidth);
13861 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13862 if (Msk[I])
13863 Result.setBitVal(I, Val[P++]);
13864 return Success(Result, E);
13865 }
13866
13867 case clang::X86::BI__builtin_ia32_pext_si:
13868 case clang::X86::BI__builtin_ia32_pext_di: {
13869 APSInt Val, Msk;
13870 if (!EvaluateInteger(E->getArg(0), Val, Info) ||
13871 !EvaluateInteger(E->getArg(1), Msk, Info))
13872 return false;
13873
13874 unsigned BitWidth = Val.getBitWidth();
13875 APInt Result = APInt::getZero(BitWidth);
13876 for (unsigned I = 0, P = 0; I != BitWidth; ++I)
13877 if (Msk[I])
13878 Result.setBitVal(P++, Val[I]);
13879 return Success(Result, E);
13880 }
13881 }
13882}
13883
13884/// Determine whether this is a pointer past the end of the complete
13885/// object referred to by the lvalue.
13887 const LValue &LV) {
13888 // A null pointer can be viewed as being "past the end" but we don't
13889 // choose to look at it that way here.
13890 if (!LV.getLValueBase())
13891 return false;
13892
13893 // If the designator is valid and refers to a subobject, we're not pointing
13894 // past the end.
13895 if (!LV.getLValueDesignator().Invalid &&
13896 !LV.getLValueDesignator().isOnePastTheEnd())
13897 return false;
13898
13899 // A pointer to an incomplete type might be past-the-end if the type's size is
13900 // zero. We cannot tell because the type is incomplete.
13901 QualType Ty = getType(LV.getLValueBase());
13902 if (Ty->isIncompleteType())
13903 return true;
13904
13905 // Can't be past the end of an invalid object.
13906 if (LV.getLValueDesignator().Invalid)
13907 return false;
13908
13909 // We're a past-the-end pointer if we point to the byte after the object,
13910 // no matter what our type or path is.
13911 auto Size = Ctx.getTypeSizeInChars(Ty);
13912 return LV.getLValueOffset() == Size;
13913}
13914
13915namespace {
13916
13917/// Data recursive integer evaluator of certain binary operators.
13918///
13919/// We use a data recursive algorithm for binary operators so that we are able
13920/// to handle extreme cases of chained binary operators without causing stack
13921/// overflow.
13922class DataRecursiveIntBinOpEvaluator {
13923 struct EvalResult {
13924 APValue Val;
13925 bool Failed = false;
13926
13927 EvalResult() = default;
13928
13929 void swap(EvalResult &RHS) {
13930 Val.swap(RHS.Val);
13931 Failed = RHS.Failed;
13932 RHS.Failed = false;
13933 }
13934 };
13935
13936 struct Job {
13937 const Expr *E;
13938 EvalResult LHSResult; // meaningful only for binary operator expression.
13939 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
13940
13941 Job() = default;
13942 Job(Job &&) = default;
13943
13944 void startSpeculativeEval(EvalInfo &Info) {
13945 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
13946 }
13947
13948 private:
13949 SpeculativeEvaluationRAII SpecEvalRAII;
13950 };
13951
13953
13954 IntExprEvaluator &IntEval;
13955 EvalInfo &Info;
13956 APValue &FinalResult;
13957
13958public:
13959 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
13960 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
13961
13962 /// True if \param E is a binary operator that we are going to handle
13963 /// data recursively.
13964 /// We handle binary operators that are comma, logical, or that have operands
13965 /// with integral or enumeration type.
13966 static bool shouldEnqueue(const BinaryOperator *E) {
13967 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
13969 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
13970 E->getRHS()->getType()->isIntegralOrEnumerationType());
13971 }
13972
13973 bool Traverse(const BinaryOperator *E) {
13974 enqueue(E);
13975 EvalResult PrevResult;
13976 while (!Queue.empty())
13977 process(PrevResult);
13978
13979 if (PrevResult.Failed) return false;
13980
13981 FinalResult.swap(PrevResult.Val);
13982 return true;
13983 }
13984
13985private:
13986 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
13987 return IntEval.Success(Value, E, Result);
13988 }
13989 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
13990 return IntEval.Success(Value, E, Result);
13991 }
13992 bool Error(const Expr *E) {
13993 return IntEval.Error(E);
13994 }
13995 bool Error(const Expr *E, diag::kind D) {
13996 return IntEval.Error(E, D);
13997 }
13998
13999 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
14000 return Info.CCEDiag(E, D);
14001 }
14002
14003 // Returns true if visiting the RHS is necessary, false otherwise.
14004 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14005 bool &SuppressRHSDiags);
14006
14007 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14008 const BinaryOperator *E, APValue &Result);
14009
14010 void EvaluateExpr(const Expr *E, EvalResult &Result) {
14011 Result.Failed = !Evaluate(Result.Val, Info, E);
14012 if (Result.Failed)
14013 Result.Val = APValue();
14014 }
14015
14016 void process(EvalResult &Result);
14017
14018 void enqueue(const Expr *E) {
14019 E = E->IgnoreParens();
14020 Queue.resize(Queue.size()+1);
14021 Queue.back().E = E;
14022 Queue.back().Kind = Job::AnyExprKind;
14023 }
14024};
14025
14026}
14027
14028bool DataRecursiveIntBinOpEvaluator::
14029 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
14030 bool &SuppressRHSDiags) {
14031 if (E->getOpcode() == BO_Comma) {
14032 // Ignore LHS but note if we could not evaluate it.
14033 if (LHSResult.Failed)
14034 return Info.noteSideEffect();
14035 return true;
14036 }
14037
14038 if (E->isLogicalOp()) {
14039 bool LHSAsBool;
14040 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
14041 // We were able to evaluate the LHS, see if we can get away with not
14042 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
14043 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
14044 Success(LHSAsBool, E, LHSResult.Val);
14045 return false; // Ignore RHS
14046 }
14047 } else {
14048 LHSResult.Failed = true;
14049
14050 // Since we weren't able to evaluate the left hand side, it
14051 // might have had side effects.
14052 if (!Info.noteSideEffect())
14053 return false;
14054
14055 // We can't evaluate the LHS; however, sometimes the result
14056 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14057 // Don't ignore RHS and suppress diagnostics from this arm.
14058 SuppressRHSDiags = true;
14059 }
14060
14061 return true;
14062 }
14063
14064 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14065 E->getRHS()->getType()->isIntegralOrEnumerationType());
14066
14067 if (LHSResult.Failed && !Info.noteFailure())
14068 return false; // Ignore RHS;
14069
14070 return true;
14071}
14072
14073static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
14074 bool IsSub) {
14075 // Compute the new offset in the appropriate width, wrapping at 64 bits.
14076 // FIXME: When compiling for a 32-bit target, we should use 32-bit
14077 // offsets.
14078 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
14079 CharUnits &Offset = LVal.getLValueOffset();
14080 uint64_t Offset64 = Offset.getQuantity();
14081 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
14082 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
14083 : Offset64 + Index64);
14084}
14085
14086bool DataRecursiveIntBinOpEvaluator::
14087 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
14088 const BinaryOperator *E, APValue &Result) {
14089 if (E->getOpcode() == BO_Comma) {
14090 if (RHSResult.Failed)
14091 return false;
14092 Result = RHSResult.Val;
14093 return true;
14094 }
14095
14096 if (E->isLogicalOp()) {
14097 bool lhsResult, rhsResult;
14098 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
14099 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
14100
14101 if (LHSIsOK) {
14102 if (RHSIsOK) {
14103 if (E->getOpcode() == BO_LOr)
14104 return Success(lhsResult || rhsResult, E, Result);
14105 else
14106 return Success(lhsResult && rhsResult, E, Result);
14107 }
14108 } else {
14109 if (RHSIsOK) {
14110 // We can't evaluate the LHS; however, sometimes the result
14111 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
14112 if (rhsResult == (E->getOpcode() == BO_LOr))
14113 return Success(rhsResult, E, Result);
14114 }
14115 }
14116
14117 return false;
14118 }
14119
14120 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
14121 E->getRHS()->getType()->isIntegralOrEnumerationType());
14122
14123 if (LHSResult.Failed || RHSResult.Failed)
14124 return false;
14125
14126 const APValue &LHSVal = LHSResult.Val;
14127 const APValue &RHSVal = RHSResult.Val;
14128
14129 // Handle cases like (unsigned long)&a + 4.
14130 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
14131 Result = LHSVal;
14132 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
14133 return true;
14134 }
14135
14136 // Handle cases like 4 + (unsigned long)&a
14137 if (E->getOpcode() == BO_Add &&
14138 RHSVal.isLValue() && LHSVal.isInt()) {
14139 Result = RHSVal;
14140 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
14141 return true;
14142 }
14143
14144 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
14145 // Handle (intptr_t)&&A - (intptr_t)&&B.
14146 if (!LHSVal.getLValueOffset().isZero() ||
14147 !RHSVal.getLValueOffset().isZero())
14148 return false;
14149 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
14150 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
14151 if (!LHSExpr || !RHSExpr)
14152 return false;
14153 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14154 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14155 if (!LHSAddrExpr || !RHSAddrExpr)
14156 return false;
14157 // Make sure both labels come from the same function.
14158 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14159 RHSAddrExpr->getLabel()->getDeclContext())
14160 return false;
14161 Result = APValue(LHSAddrExpr, RHSAddrExpr);
14162 return true;
14163 }
14164
14165 // All the remaining cases expect both operands to be an integer
14166 if (!LHSVal.isInt() || !RHSVal.isInt())
14167 return Error(E);
14168
14169 // Set up the width and signedness manually, in case it can't be deduced
14170 // from the operation we're performing.
14171 // FIXME: Don't do this in the cases where we can deduce it.
14172 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
14174 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
14175 RHSVal.getInt(), Value))
14176 return false;
14177 return Success(Value, E, Result);
14178}
14179
14180void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
14181 Job &job = Queue.back();
14182
14183 switch (job.Kind) {
14184 case Job::AnyExprKind: {
14185 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
14186 if (shouldEnqueue(Bop)) {
14187 job.Kind = Job::BinOpKind;
14188 enqueue(Bop->getLHS());
14189 return;
14190 }
14191 }
14192
14193 EvaluateExpr(job.E, Result);
14194 Queue.pop_back();
14195 return;
14196 }
14197
14198 case Job::BinOpKind: {
14199 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14200 bool SuppressRHSDiags = false;
14201 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
14202 Queue.pop_back();
14203 return;
14204 }
14205 if (SuppressRHSDiags)
14206 job.startSpeculativeEval(Info);
14207 job.LHSResult.swap(Result);
14208 job.Kind = Job::BinOpVisitedLHSKind;
14209 enqueue(Bop->getRHS());
14210 return;
14211 }
14212
14213 case Job::BinOpVisitedLHSKind: {
14214 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
14215 EvalResult RHS;
14216 RHS.swap(Result);
14217 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
14218 Queue.pop_back();
14219 return;
14220 }
14221 }
14222
14223 llvm_unreachable("Invalid Job::Kind!");
14224}
14225
14226namespace {
14227enum class CmpResult {
14228 Unequal,
14229 Less,
14230 Equal,
14231 Greater,
14232 Unordered,
14233};
14234}
14235
14236template <class SuccessCB, class AfterCB>
14237static bool
14239 SuccessCB &&Success, AfterCB &&DoAfter) {
14240 assert(!E->isValueDependent());
14241 assert(E->isComparisonOp() && "expected comparison operator");
14242 assert((E->getOpcode() == BO_Cmp ||
14244 "unsupported binary expression evaluation");
14245 auto Error = [&](const Expr *E) {
14246 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14247 return false;
14248 };
14249
14250 bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
14251 bool IsEquality = E->isEqualityOp();
14252
14253 QualType LHSTy = E->getLHS()->getType();
14254 QualType RHSTy = E->getRHS()->getType();
14255
14256 if (LHSTy->isIntegralOrEnumerationType() &&
14257 RHSTy->isIntegralOrEnumerationType()) {
14258 APSInt LHS, RHS;
14259 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
14260 if (!LHSOK && !Info.noteFailure())
14261 return false;
14262 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
14263 return false;
14264 if (LHS < RHS)
14265 return Success(CmpResult::Less, E);
14266 if (LHS > RHS)
14267 return Success(CmpResult::Greater, E);
14268 return Success(CmpResult::Equal, E);
14269 }
14270
14271 if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
14272 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
14273 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
14274
14275 bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
14276 if (!LHSOK && !Info.noteFailure())
14277 return false;
14278 if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
14279 return false;
14280 if (LHSFX < RHSFX)
14281 return Success(CmpResult::Less, E);
14282 if (LHSFX > RHSFX)
14283 return Success(CmpResult::Greater, E);
14284 return Success(CmpResult::Equal, E);
14285 }
14286
14287 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
14288 ComplexValue LHS, RHS;
14289 bool LHSOK;
14290 if (E->isAssignmentOp()) {
14291 LValue LV;
14292 EvaluateLValue(E->getLHS(), LV, Info);
14293 LHSOK = false;
14294 } else if (LHSTy->isRealFloatingType()) {
14295 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
14296 if (LHSOK) {
14297 LHS.makeComplexFloat();
14298 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
14299 }
14300 } else {
14301 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
14302 }
14303 if (!LHSOK && !Info.noteFailure())
14304 return false;
14305
14306 if (E->getRHS()->getType()->isRealFloatingType()) {
14307 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
14308 return false;
14309 RHS.makeComplexFloat();
14310 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
14311 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14312 return false;
14313
14314 if (LHS.isComplexFloat()) {
14315 APFloat::cmpResult CR_r =
14316 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
14317 APFloat::cmpResult CR_i =
14318 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
14319 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
14320 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14321 } else {
14322 assert(IsEquality && "invalid complex comparison");
14323 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
14324 LHS.getComplexIntImag() == RHS.getComplexIntImag();
14325 return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
14326 }
14327 }
14328
14329 if (LHSTy->isRealFloatingType() &&
14330 RHSTy->isRealFloatingType()) {
14331 APFloat RHS(0.0), LHS(0.0);
14332
14333 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
14334 if (!LHSOK && !Info.noteFailure())
14335 return false;
14336
14337 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
14338 return false;
14339
14340 assert(E->isComparisonOp() && "Invalid binary operator!");
14341 llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
14342 if (!Info.InConstantContext &&
14343 APFloatCmpResult == APFloat::cmpUnordered &&
14344 E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
14345 // Note: Compares may raise invalid in some cases involving NaN or sNaN.
14346 Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
14347 return false;
14348 }
14349 auto GetCmpRes = [&]() {
14350 switch (APFloatCmpResult) {
14351 case APFloat::cmpEqual:
14352 return CmpResult::Equal;
14353 case APFloat::cmpLessThan:
14354 return CmpResult::Less;
14355 case APFloat::cmpGreaterThan:
14356 return CmpResult::Greater;
14357 case APFloat::cmpUnordered:
14358 return CmpResult::Unordered;
14359 }
14360 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
14361 };
14362 return Success(GetCmpRes(), E);
14363 }
14364
14365 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
14366 LValue LHSValue, RHSValue;
14367
14368 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14369 if (!LHSOK && !Info.noteFailure())
14370 return false;
14371
14372 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14373 return false;
14374
14375 // If we have Unknown pointers we should fail if they are not global values.
14376 if (!(IsGlobalLValue(LHSValue.getLValueBase()) &&
14377 IsGlobalLValue(RHSValue.getLValueBase())) &&
14378 (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
14379 return false;
14380
14381 // Reject differing bases from the normal codepath; we special-case
14382 // comparisons to null.
14383 if (!HasSameBase(LHSValue, RHSValue)) {
14384 auto DiagComparison = [&] (unsigned DiagID, bool Reversed = false) {
14385 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14386 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14387 Info.FFDiag(E, DiagID)
14388 << (Reversed ? RHS : LHS) << (Reversed ? LHS : RHS);
14389 return false;
14390 };
14391 // Inequalities and subtractions between unrelated pointers have
14392 // unspecified or undefined behavior.
14393 if (!IsEquality)
14394 return DiagComparison(
14395 diag::note_constexpr_pointer_comparison_unspecified);
14396 // A constant address may compare equal to the address of a symbol.
14397 // The one exception is that address of an object cannot compare equal
14398 // to a null pointer constant.
14399 // TODO: Should we restrict this to actual null pointers, and exclude the
14400 // case of zero cast to pointer type?
14401 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
14402 (!RHSValue.Base && !RHSValue.Offset.isZero()))
14403 return DiagComparison(diag::note_constexpr_pointer_constant_comparison,
14404 !RHSValue.Base);
14405 // C++2c [intro.object]/10:
14406 // Two objects [...] may have the same address if [...] they are both
14407 // potentially non-unique objects.
14408 // C++2c [intro.object]/9:
14409 // An object is potentially non-unique if it is a string literal object,
14410 // the backing array of an initializer list, or a subobject thereof.
14411 //
14412 // This makes the comparison result unspecified, so it's not a constant
14413 // expression.
14414 //
14415 // TODO: Do we need to handle the initializer list case here?
14416 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14417 return DiagComparison(diag::note_constexpr_literal_comparison);
14418 if (IsOpaqueConstantCall(LHSValue) || IsOpaqueConstantCall(RHSValue))
14419 return DiagComparison(diag::note_constexpr_opaque_call_comparison,
14420 !IsOpaqueConstantCall(LHSValue));
14421 // We can't tell whether weak symbols will end up pointing to the same
14422 // object.
14423 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
14424 return DiagComparison(diag::note_constexpr_pointer_weak_comparison,
14425 !IsWeakLValue(LHSValue));
14426 // We can't compare the address of the start of one object with the
14427 // past-the-end address of another object, per C++ DR1652.
14428 if (LHSValue.Base && LHSValue.Offset.isZero() &&
14429 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue))
14430 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14431 true);
14432 if (RHSValue.Base && RHSValue.Offset.isZero() &&
14433 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue))
14434 return DiagComparison(diag::note_constexpr_pointer_comparison_past_end,
14435 false);
14436 // We can't tell whether an object is at the same address as another
14437 // zero sized object.
14438 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
14439 (LHSValue.Base && isZeroSized(RHSValue)))
14440 return DiagComparison(
14441 diag::note_constexpr_pointer_comparison_zero_sized);
14442 return Success(CmpResult::Unequal, E);
14443 }
14444
14445 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14446 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14447
14448 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14449 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14450
14451 // C++11 [expr.rel]p2:
14452 // - If two pointers point to non-static data members of the same object,
14453 // or to subobjects or array elements fo such members, recursively, the
14454 // pointer to the later declared member compares greater provided the
14455 // two members have the same access control and provided their class is
14456 // not a union.
14457 // [...]
14458 // - Otherwise pointer comparisons are unspecified.
14459 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
14460 bool WasArrayIndex;
14461 unsigned Mismatch = FindDesignatorMismatch(
14462 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
14463 // At the point where the designators diverge, the comparison has a
14464 // specified value if:
14465 // - we are comparing array indices
14466 // - we are comparing fields of a union, or fields with the same access
14467 // Otherwise, the result is unspecified and thus the comparison is not a
14468 // constant expression.
14469 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
14470 Mismatch < RHSDesignator.Entries.size()) {
14471 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
14472 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
14473 if (!LF && !RF)
14474 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
14475 else if (!LF)
14476 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14477 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
14478 << RF->getParent() << RF;
14479 else if (!RF)
14480 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
14481 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
14482 << LF->getParent() << LF;
14483 else if (!LF->getParent()->isUnion() &&
14484 LF->getAccess() != RF->getAccess())
14485 Info.CCEDiag(E,
14486 diag::note_constexpr_pointer_comparison_differing_access)
14487 << LF << LF->getAccess() << RF << RF->getAccess()
14488 << LF->getParent();
14489 }
14490 }
14491
14492 // The comparison here must be unsigned, and performed with the same
14493 // width as the pointer.
14494 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
14495 uint64_t CompareLHS = LHSOffset.getQuantity();
14496 uint64_t CompareRHS = RHSOffset.getQuantity();
14497 assert(PtrSize <= 64 && "Unexpected pointer width");
14498 uint64_t Mask = ~0ULL >> (64 - PtrSize);
14499 CompareLHS &= Mask;
14500 CompareRHS &= Mask;
14501
14502 // If there is a base and this is a relational operator, we can only
14503 // compare pointers within the object in question; otherwise, the result
14504 // depends on where the object is located in memory.
14505 if (!LHSValue.Base.isNull() && IsRelational) {
14506 QualType BaseTy = getType(LHSValue.Base);
14507 if (BaseTy->isIncompleteType())
14508 return Error(E);
14509 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
14510 uint64_t OffsetLimit = Size.getQuantity();
14511 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
14512 return Error(E);
14513 }
14514
14515 if (CompareLHS < CompareRHS)
14516 return Success(CmpResult::Less, E);
14517 if (CompareLHS > CompareRHS)
14518 return Success(CmpResult::Greater, E);
14519 return Success(CmpResult::Equal, E);
14520 }
14521
14522 if (LHSTy->isMemberPointerType()) {
14523 assert(IsEquality && "unexpected member pointer operation");
14524 assert(RHSTy->isMemberPointerType() && "invalid comparison");
14525
14526 MemberPtr LHSValue, RHSValue;
14527
14528 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
14529 if (!LHSOK && !Info.noteFailure())
14530 return false;
14531
14532 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14533 return false;
14534
14535 // If either operand is a pointer to a weak function, the comparison is not
14536 // constant.
14537 if (LHSValue.getDecl() && LHSValue.getDecl()->isWeak()) {
14538 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14539 << LHSValue.getDecl();
14540 return false;
14541 }
14542 if (RHSValue.getDecl() && RHSValue.getDecl()->isWeak()) {
14543 Info.FFDiag(E, diag::note_constexpr_mem_pointer_weak_comparison)
14544 << RHSValue.getDecl();
14545 return false;
14546 }
14547
14548 // C++11 [expr.eq]p2:
14549 // If both operands are null, they compare equal. Otherwise if only one is
14550 // null, they compare unequal.
14551 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
14552 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
14553 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14554 }
14555
14556 // Otherwise if either is a pointer to a virtual member function, the
14557 // result is unspecified.
14558 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
14559 if (MD->isVirtual())
14560 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14561 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
14562 if (MD->isVirtual())
14563 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
14564
14565 // Otherwise they compare equal if and only if they would refer to the
14566 // same member of the same most derived object or the same subobject if
14567 // they were dereferenced with a hypothetical object of the associated
14568 // class type.
14569 bool Equal = LHSValue == RHSValue;
14570 return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
14571 }
14572
14573 if (LHSTy->isNullPtrType()) {
14574 assert(E->isComparisonOp() && "unexpected nullptr operation");
14575 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
14576 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
14577 // are compared, the result is true of the operator is <=, >= or ==, and
14578 // false otherwise.
14579 LValue Res;
14580 if (!EvaluatePointer(E->getLHS(), Res, Info) ||
14581 !EvaluatePointer(E->getRHS(), Res, Info))
14582 return false;
14583 return Success(CmpResult::Equal, E);
14584 }
14585
14586 return DoAfter();
14587}
14588
14589bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
14590 if (!CheckLiteralType(Info, E))
14591 return false;
14592
14593 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14595 switch (CR) {
14596 case CmpResult::Unequal:
14597 llvm_unreachable("should never produce Unequal for three-way comparison");
14598 case CmpResult::Less:
14599 CCR = ComparisonCategoryResult::Less;
14600 break;
14601 case CmpResult::Equal:
14602 CCR = ComparisonCategoryResult::Equal;
14603 break;
14604 case CmpResult::Greater:
14605 CCR = ComparisonCategoryResult::Greater;
14606 break;
14607 case CmpResult::Unordered:
14608 CCR = ComparisonCategoryResult::Unordered;
14609 break;
14610 }
14611 // Evaluation succeeded. Lookup the information for the comparison category
14612 // type and fetch the VarDecl for the result.
14613 const ComparisonCategoryInfo &CmpInfo =
14615 const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
14616 // Check and evaluate the result as a constant expression.
14617 LValue LV;
14618 LV.set(VD);
14619 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14620 return false;
14621 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14622 ConstantExprKind::Normal);
14623 };
14624 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14625 return ExprEvaluatorBaseTy::VisitBinCmp(E);
14626 });
14627}
14628
14629bool RecordExprEvaluator::VisitCXXParenListInitExpr(
14630 const CXXParenListInitExpr *E) {
14631 return VisitCXXParenListOrInitListExpr(E, E->getInitExprs());
14632}
14633
14634bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14635 // We don't support assignment in C. C++ assignments don't get here because
14636 // assignment is an lvalue in C++.
14637 if (E->isAssignmentOp()) {
14638 Error(E);
14639 if (!Info.noteFailure())
14640 return false;
14641 }
14642
14643 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
14644 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
14645
14646 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
14647 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
14648 "DataRecursiveIntBinOpEvaluator should have handled integral types");
14649
14650 if (E->isComparisonOp()) {
14651 // Evaluate builtin binary comparisons by evaluating them as three-way
14652 // comparisons and then translating the result.
14653 auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
14654 assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
14655 "should only produce Unequal for equality comparisons");
14656 bool IsEqual = CR == CmpResult::Equal,
14657 IsLess = CR == CmpResult::Less,
14658 IsGreater = CR == CmpResult::Greater;
14659 auto Op = E->getOpcode();
14660 switch (Op) {
14661 default:
14662 llvm_unreachable("unsupported binary operator");
14663 case BO_EQ:
14664 case BO_NE:
14665 return Success(IsEqual == (Op == BO_EQ), E);
14666 case BO_LT:
14667 return Success(IsLess, E);
14668 case BO_GT:
14669 return Success(IsGreater, E);
14670 case BO_LE:
14671 return Success(IsEqual || IsLess, E);
14672 case BO_GE:
14673 return Success(IsEqual || IsGreater, E);
14674 }
14675 };
14676 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
14677 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14678 });
14679 }
14680
14681 QualType LHSTy = E->getLHS()->getType();
14682 QualType RHSTy = E->getRHS()->getType();
14683
14684 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
14685 E->getOpcode() == BO_Sub) {
14686 LValue LHSValue, RHSValue;
14687
14688 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
14689 if (!LHSOK && !Info.noteFailure())
14690 return false;
14691
14692 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
14693 return false;
14694
14695 // Reject differing bases from the normal codepath; we special-case
14696 // comparisons to null.
14697 if (!HasSameBase(LHSValue, RHSValue)) {
14698 // Handle &&A - &&B.
14699 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
14700 return Error(E);
14701 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
14702 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
14703
14704 auto DiagArith = [&](unsigned DiagID) {
14705 std::string LHS = LHSValue.toString(Info.Ctx, E->getLHS()->getType());
14706 std::string RHS = RHSValue.toString(Info.Ctx, E->getRHS()->getType());
14707 Info.FFDiag(E, DiagID) << LHS << RHS;
14708 if (LHSExpr && LHSExpr == RHSExpr)
14709 Info.Note(LHSExpr->getExprLoc(),
14710 diag::note_constexpr_repeated_literal_eval)
14711 << LHSExpr->getSourceRange();
14712 return false;
14713 };
14714
14715 if (!LHSExpr || !RHSExpr)
14716 return DiagArith(diag::note_constexpr_pointer_arith_unspecified);
14717
14718 if (ArePotentiallyOverlappingStringLiterals(Info, LHSValue, RHSValue))
14719 return DiagArith(diag::note_constexpr_literal_arith);
14720
14721 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
14722 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
14723 if (!LHSAddrExpr || !RHSAddrExpr)
14724 return Error(E);
14725 // Make sure both labels come from the same function.
14726 if (LHSAddrExpr->getLabel()->getDeclContext() !=
14727 RHSAddrExpr->getLabel()->getDeclContext())
14728 return Error(E);
14729 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
14730 }
14731 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
14732 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
14733
14734 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
14735 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
14736
14737 // C++11 [expr.add]p6:
14738 // Unless both pointers point to elements of the same array object, or
14739 // one past the last element of the array object, the behavior is
14740 // undefined.
14741 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
14742 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
14743 RHSDesignator))
14744 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
14745
14746 QualType Type = E->getLHS()->getType();
14747 QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
14748
14749 CharUnits ElementSize;
14750 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
14751 return false;
14752
14753 // As an extension, a type may have zero size (empty struct or union in
14754 // C, array of zero length). Pointer subtraction in such cases has
14755 // undefined behavior, so is not constant.
14756 if (ElementSize.isZero()) {
14757 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
14758 << ElementType;
14759 return false;
14760 }
14761
14762 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
14763 // and produce incorrect results when it overflows. Such behavior
14764 // appears to be non-conforming, but is common, so perhaps we should
14765 // assume the standard intended for such cases to be undefined behavior
14766 // and check for them.
14767
14768 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
14769 // overflow in the final conversion to ptrdiff_t.
14770 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
14771 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
14772 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
14773 false);
14774 APSInt TrueResult = (LHS - RHS) / ElemSize;
14775 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
14776
14777 if (Result.extend(65) != TrueResult &&
14778 !HandleOverflow(Info, E, TrueResult, E->getType()))
14779 return false;
14780 return Success(Result, E);
14781 }
14782
14783 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14784}
14785
14786/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
14787/// a result as the expression's type.
14788bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
14789 const UnaryExprOrTypeTraitExpr *E) {
14790 switch(E->getKind()) {
14791 case UETT_PreferredAlignOf:
14792 case UETT_AlignOf: {
14793 if (E->isArgumentType())
14794 return Success(
14795 GetAlignOfType(Info.Ctx, E->getArgumentType(), E->getKind()), E);
14796 else
14797 return Success(
14798 GetAlignOfExpr(Info.Ctx, E->getArgumentExpr(), E->getKind()), E);
14799 }
14800
14801 case UETT_PtrAuthTypeDiscriminator: {
14802 if (E->getArgumentType()->isDependentType())
14803 return false;
14804 return Success(
14805 Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
14806 }
14807 case UETT_VecStep: {
14808 QualType Ty = E->getTypeOfArgument();
14809
14810 if (Ty->isVectorType()) {
14811 unsigned n = Ty->castAs<VectorType>()->getNumElements();
14812
14813 // The vec_step built-in functions that take a 3-component
14814 // vector return 4. (OpenCL 1.1 spec 6.11.12)
14815 if (n == 3)
14816 n = 4;
14817
14818 return Success(n, E);
14819 } else
14820 return Success(1, E);
14821 }
14822
14823 case UETT_DataSizeOf:
14824 case UETT_SizeOf: {
14825 QualType SrcTy = E->getTypeOfArgument();
14826 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
14827 // the result is the size of the referenced type."
14828 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
14829 SrcTy = Ref->getPointeeType();
14830
14831 CharUnits Sizeof;
14832 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof,
14833 E->getKind() == UETT_DataSizeOf ? SizeOfType::DataSizeOf
14834 : SizeOfType::SizeOf)) {
14835 return false;
14836 }
14837 return Success(Sizeof, E);
14838 }
14839 case UETT_OpenMPRequiredSimdAlign:
14840 assert(E->isArgumentType());
14841 return Success(
14842 Info.Ctx.toCharUnitsFromBits(
14843 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
14844 .getQuantity(),
14845 E);
14846 case UETT_VectorElements: {
14847 QualType Ty = E->getTypeOfArgument();
14848 // If the vector has a fixed size, we can determine the number of elements
14849 // at compile time.
14850 if (const auto *VT = Ty->getAs<VectorType>())
14851 return Success(VT->getNumElements(), E);
14852
14853 assert(Ty->isSizelessVectorType());
14854 if (Info.InConstantContext)
14855 Info.CCEDiag(E, diag::note_constexpr_non_const_vectorelements)
14856 << E->getSourceRange();
14857
14858 return false;
14859 }
14860 }
14861
14862 llvm_unreachable("unknown expr/type trait");
14863}
14864
14865bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
14866 CharUnits Result;
14867 unsigned n = OOE->getNumComponents();
14868 if (n == 0)
14869 return Error(OOE);
14870 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
14871 for (unsigned i = 0; i != n; ++i) {
14872 OffsetOfNode ON = OOE->getComponent(i);
14873 switch (ON.getKind()) {
14874 case OffsetOfNode::Array: {
14875 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
14876 APSInt IdxResult;
14877 if (!EvaluateInteger(Idx, IdxResult, Info))
14878 return false;
14879 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
14880 if (!AT)
14881 return Error(OOE);
14882 CurrentType = AT->getElementType();
14883 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
14884 Result += IdxResult.getSExtValue() * ElementSize;
14885 break;
14886 }
14887
14888 case OffsetOfNode::Field: {
14889 FieldDecl *MemberDecl = ON.getField();
14890 const RecordType *RT = CurrentType->getAs<RecordType>();
14891 if (!RT)
14892 return Error(OOE);
14893 RecordDecl *RD = RT->getDecl();
14894 if (RD->isInvalidDecl()) return false;
14895 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14896 unsigned i = MemberDecl->getFieldIndex();
14897 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
14898 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
14899 CurrentType = MemberDecl->getType().getNonReferenceType();
14900 break;
14901 }
14902
14904 llvm_unreachable("dependent __builtin_offsetof");
14905
14906 case OffsetOfNode::Base: {
14907 CXXBaseSpecifier *BaseSpec = ON.getBase();
14908 if (BaseSpec->isVirtual())
14909 return Error(OOE);
14910
14911 // Find the layout of the class whose base we are looking into.
14912 const RecordType *RT = CurrentType->getAs<RecordType>();
14913 if (!RT)
14914 return Error(OOE);
14915 RecordDecl *RD = RT->getDecl();
14916 if (RD->isInvalidDecl()) return false;
14917 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
14918
14919 // Find the base class itself.
14920 CurrentType = BaseSpec->getType();
14921 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
14922 if (!BaseRT)
14923 return Error(OOE);
14924
14925 // Add the offset to the base.
14926 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
14927 break;
14928 }
14929 }
14930 }
14931 return Success(Result, OOE);
14932}
14933
14934bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14935 switch (E->getOpcode()) {
14936 default:
14937 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
14938 // See C99 6.6p3.
14939 return Error(E);
14940 case UO_Extension:
14941 // FIXME: Should extension allow i-c-e extension expressions in its scope?
14942 // If so, we could clear the diagnostic ID.
14943 return Visit(E->getSubExpr());
14944 case UO_Plus:
14945 // The result is just the value.
14946 return Visit(E->getSubExpr());
14947 case UO_Minus: {
14948 if (!Visit(E->getSubExpr()))
14949 return false;
14950 if (!Result.isInt()) return Error(E);
14951 const APSInt &Value = Result.getInt();
14952 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14953 if (Info.checkingForUndefinedBehavior())
14954 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
14955 diag::warn_integer_constant_overflow)
14956 << toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,
14957 /*UpperCase=*/true, /*InsertSeparators=*/true)
14958 << E->getType() << E->getSourceRange();
14959
14960 if (!HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
14961 E->getType()))
14962 return false;
14963 }
14964 return Success(-Value, E);
14965 }
14966 case UO_Not: {
14967 if (!Visit(E->getSubExpr()))
14968 return false;
14969 if (!Result.isInt()) return Error(E);
14970 return Success(~Result.getInt(), E);
14971 }
14972 case UO_LNot: {
14973 bool bres;
14974 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
14975 return false;
14976 return Success(!bres, E);
14977 }
14978 }
14979}
14980
14981/// HandleCast - This is used to evaluate implicit or explicit casts where the
14982/// result type is integer.
14983bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
14984 const Expr *SubExpr = E->getSubExpr();
14985 QualType DestType = E->getType();
14986 QualType SrcType = SubExpr->getType();
14987
14988 switch (E->getCastKind()) {
14989 case CK_BaseToDerived:
14990 case CK_DerivedToBase:
14991 case CK_UncheckedDerivedToBase:
14992 case CK_Dynamic:
14993 case CK_ToUnion:
14994 case CK_ArrayToPointerDecay:
14995 case CK_FunctionToPointerDecay:
14996 case CK_NullToPointer:
14997 case CK_NullToMemberPointer:
14998 case CK_BaseToDerivedMemberPointer:
14999 case CK_DerivedToBaseMemberPointer:
15000 case CK_ReinterpretMemberPointer:
15001 case CK_ConstructorConversion:
15002 case CK_IntegralToPointer:
15003 case CK_ToVoid:
15004 case CK_VectorSplat:
15005 case CK_IntegralToFloating:
15006 case CK_FloatingCast:
15007 case CK_CPointerToObjCPointerCast:
15008 case CK_BlockPointerToObjCPointerCast:
15009 case CK_AnyPointerToBlockPointerCast:
15010 case CK_ObjCObjectLValueCast:
15011 case CK_FloatingRealToComplex:
15012 case CK_FloatingComplexToReal:
15013 case CK_FloatingComplexCast:
15014 case CK_FloatingComplexToIntegralComplex:
15015 case CK_IntegralRealToComplex:
15016 case CK_IntegralComplexCast:
15017 case CK_IntegralComplexToFloatingComplex:
15018 case CK_BuiltinFnToFnPtr:
15019 case CK_ZeroToOCLOpaqueType:
15020 case CK_NonAtomicToAtomic:
15021 case CK_AddressSpaceConversion:
15022 case CK_IntToOCLSampler:
15023 case CK_FloatingToFixedPoint:
15024 case CK_FixedPointToFloating:
15025 case CK_FixedPointCast:
15026 case CK_IntegralToFixedPoint:
15027 case CK_MatrixCast:
15028 llvm_unreachable("invalid cast kind for integral value");
15029
15030 case CK_BitCast:
15031 case CK_Dependent:
15032 case CK_LValueBitCast:
15033 case CK_ARCProduceObject:
15034 case CK_ARCConsumeObject:
15035 case CK_ARCReclaimReturnedObject:
15036 case CK_ARCExtendBlockObject:
15037 case CK_CopyAndAutoreleaseBlockObject:
15038 return Error(E);
15039
15040 case CK_UserDefinedConversion:
15041 case CK_LValueToRValue:
15042 case CK_AtomicToNonAtomic:
15043 case CK_NoOp:
15044 case CK_LValueToRValueBitCast:
15045 case CK_HLSLArrayRValue:
15046 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15047
15048 case CK_MemberPointerToBoolean:
15049 case CK_PointerToBoolean:
15050 case CK_IntegralToBoolean:
15051 case CK_FloatingToBoolean:
15052 case CK_BooleanToSignedIntegral:
15053 case CK_FloatingComplexToBoolean:
15054 case CK_IntegralComplexToBoolean: {
15055 bool BoolResult;
15056 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
15057 return false;
15058 uint64_t IntResult = BoolResult;
15059 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
15060 IntResult = (uint64_t)-1;
15061 return Success(IntResult, E);
15062 }
15063
15064 case CK_FixedPointToIntegral: {
15065 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
15066 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15067 return false;
15068 bool Overflowed;
15069 llvm::APSInt Result = Src.convertToInt(
15070 Info.Ctx.getIntWidth(DestType),
15071 DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
15072 if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
15073 return false;
15074 return Success(Result, E);
15075 }
15076
15077 case CK_FixedPointToBoolean: {
15078 // Unsigned padding does not affect this.
15079 APValue Val;
15080 if (!Evaluate(Val, Info, SubExpr))
15081 return false;
15082 return Success(Val.getFixedPoint().getBoolValue(), E);
15083 }
15084
15085 case CK_IntegralCast: {
15086 if (!Visit(SubExpr))
15087 return false;
15088
15089 if (!Result.isInt()) {
15090 // Allow casts of address-of-label differences if they are no-ops
15091 // or narrowing. (The narrowing case isn't actually guaranteed to
15092 // be constant-evaluatable except in some narrow cases which are hard
15093 // to detect here. We let it through on the assumption the user knows
15094 // what they are doing.)
15095 if (Result.isAddrLabelDiff())
15096 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
15097 // Only allow casts of lvalues if they are lossless.
15098 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
15099 }
15100
15101 if (Info.Ctx.getLangOpts().CPlusPlus && Info.InConstantContext &&
15102 Info.EvalMode == EvalInfo::EM_ConstantExpression &&
15103 DestType->isEnumeralType()) {
15104
15105 bool ConstexprVar = true;
15106
15107 // We know if we are here that we are in a context that we might require
15108 // a constant expression or a context that requires a constant
15109 // value. But if we are initializing a value we don't know if it is a
15110 // constexpr variable or not. We can check the EvaluatingDecl to determine
15111 // if it constexpr or not. If not then we don't want to emit a diagnostic.
15112 if (const auto *VD = dyn_cast_or_null<VarDecl>(
15113 Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()))
15114 ConstexprVar = VD->isConstexpr();
15115
15116 const EnumType *ET = dyn_cast<EnumType>(DestType.getCanonicalType());
15117 const EnumDecl *ED = ET->getDecl();
15118 // Check that the value is within the range of the enumeration values.
15119 //
15120 // This corressponds to [expr.static.cast]p10 which says:
15121 // A value of integral or enumeration type can be explicitly converted
15122 // to a complete enumeration type ... If the enumeration type does not
15123 // have a fixed underlying type, the value is unchanged if the original
15124 // value is within the range of the enumeration values ([dcl.enum]), and
15125 // otherwise, the behavior is undefined.
15126 //
15127 // This was resolved as part of DR2338 which has CD5 status.
15128 if (!ED->isFixed()) {
15129 llvm::APInt Min;
15130 llvm::APInt Max;
15131
15132 ED->getValueRange(Max, Min);
15133 --Max;
15134
15135 if (ED->getNumNegativeBits() && ConstexprVar &&
15136 (Max.slt(Result.getInt().getSExtValue()) ||
15137 Min.sgt(Result.getInt().getSExtValue())))
15138 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15139 << llvm::toString(Result.getInt(), 10) << Min.getSExtValue()
15140 << Max.getSExtValue() << ED;
15141 else if (!ED->getNumNegativeBits() && ConstexprVar &&
15142 Max.ult(Result.getInt().getZExtValue()))
15143 Info.CCEDiag(E, diag::note_constexpr_unscoped_enum_out_of_range)
15144 << llvm::toString(Result.getInt(), 10) << Min.getZExtValue()
15145 << Max.getZExtValue() << ED;
15146 }
15147 }
15148
15149 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
15150 Result.getInt()), E);
15151 }
15152
15153 case CK_PointerToIntegral: {
15154 CCEDiag(E, diag::note_constexpr_invalid_cast)
15155 << 2 << Info.Ctx.getLangOpts().CPlusPlus << E->getSourceRange();
15156
15157 LValue LV;
15158 if (!EvaluatePointer(SubExpr, LV, Info))
15159 return false;
15160
15161 if (LV.getLValueBase()) {
15162 // Only allow based lvalue casts if they are lossless.
15163 // FIXME: Allow a larger integer size than the pointer size, and allow
15164 // narrowing back down to pointer width in subsequent integral casts.
15165 // FIXME: Check integer type's active bits, not its type size.
15166 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
15167 return Error(E);
15168
15169 LV.Designator.setInvalid();
15170 LV.moveInto(Result);
15171 return true;
15172 }
15173
15174 APSInt AsInt;
15175 APValue V;
15176 LV.moveInto(V);
15177 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
15178 llvm_unreachable("Can't cast this!");
15179
15180 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
15181 }
15182
15183 case CK_IntegralComplexToReal: {
15184 ComplexValue C;
15185 if (!EvaluateComplex(SubExpr, C, Info))
15186 return false;
15187 return Success(C.getComplexIntReal(), E);
15188 }
15189
15190 case CK_FloatingToIntegral: {
15191 APFloat F(0.0);
15192 if (!EvaluateFloat(SubExpr, F, Info))
15193 return false;
15194
15195 APSInt Value;
15196 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
15197 return false;
15198 return Success(Value, E);
15199 }
15200 case CK_HLSLVectorTruncation: {
15201 APValue Val;
15202 if (!EvaluateVector(SubExpr, Val, Info))
15203 return Error(E);
15204 return Success(Val.getVectorElt(0), E);
15205 }
15206 }
15207
15208 llvm_unreachable("unknown cast resulting in integral value");
15209}
15210
15211bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15212 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15213 ComplexValue LV;
15214 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15215 return false;
15216 if (!LV.isComplexInt())
15217 return Error(E);
15218 return Success(LV.getComplexIntReal(), E);
15219 }
15220
15221 return Visit(E->getSubExpr());
15222}
15223
15224bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15225 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
15226 ComplexValue LV;
15227 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
15228 return false;
15229 if (!LV.isComplexInt())
15230 return Error(E);
15231 return Success(LV.getComplexIntImag(), E);
15232 }
15233
15234 VisitIgnoredValue(E->getSubExpr());
15235 return Success(0, E);
15236}
15237
15238bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
15239 return Success(E->getPackLength(), E);
15240}
15241
15242bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
15243 return Success(E->getValue(), E);
15244}
15245
15246bool IntExprEvaluator::VisitConceptSpecializationExpr(
15248 return Success(E->isSatisfied(), E);
15249}
15250
15251bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
15252 return Success(E->isSatisfied(), E);
15253}
15254
15255bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15256 switch (E->getOpcode()) {
15257 default:
15258 // Invalid unary operators
15259 return Error(E);
15260 case UO_Plus:
15261 // The result is just the value.
15262 return Visit(E->getSubExpr());
15263 case UO_Minus: {
15264 if (!Visit(E->getSubExpr())) return false;
15265 if (!Result.isFixedPoint())
15266 return Error(E);
15267 bool Overflowed;
15268 APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
15269 if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
15270 return false;
15271 return Success(Negated, E);
15272 }
15273 case UO_LNot: {
15274 bool bres;
15275 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
15276 return false;
15277 return Success(!bres, E);
15278 }
15279 }
15280}
15281
15282bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
15283 const Expr *SubExpr = E->getSubExpr();
15284 QualType DestType = E->getType();
15285 assert(DestType->isFixedPointType() &&
15286 "Expected destination type to be a fixed point type");
15287 auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
15288
15289 switch (E->getCastKind()) {
15290 case CK_FixedPointCast: {
15291 APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15292 if (!EvaluateFixedPoint(SubExpr, Src, Info))
15293 return false;
15294 bool Overflowed;
15295 APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
15296 if (Overflowed) {
15297 if (Info.checkingForUndefinedBehavior())
15298 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15299 diag::warn_fixedpoint_constant_overflow)
15300 << Result.toString() << E->getType();
15301 if (!HandleOverflow(Info, E, Result, E->getType()))
15302 return false;
15303 }
15304 return Success(Result, E);
15305 }
15306 case CK_IntegralToFixedPoint: {
15307 APSInt Src;
15308 if (!EvaluateInteger(SubExpr, Src, Info))
15309 return false;
15310
15311 bool Overflowed;
15312 APFixedPoint IntResult = APFixedPoint::getFromIntValue(
15313 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15314
15315 if (Overflowed) {
15316 if (Info.checkingForUndefinedBehavior())
15317 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15318 diag::warn_fixedpoint_constant_overflow)
15319 << IntResult.toString() << E->getType();
15320 if (!HandleOverflow(Info, E, IntResult, E->getType()))
15321 return false;
15322 }
15323
15324 return Success(IntResult, E);
15325 }
15326 case CK_FloatingToFixedPoint: {
15327 APFloat Src(0.0);
15328 if (!EvaluateFloat(SubExpr, Src, Info))
15329 return false;
15330
15331 bool Overflowed;
15332 APFixedPoint Result = APFixedPoint::getFromFloatValue(
15333 Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
15334
15335 if (Overflowed) {
15336 if (Info.checkingForUndefinedBehavior())
15337 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15338 diag::warn_fixedpoint_constant_overflow)
15339 << Result.toString() << E->getType();
15340 if (!HandleOverflow(Info, E, Result, E->getType()))
15341 return false;
15342 }
15343
15344 return Success(Result, E);
15345 }
15346 case CK_NoOp:
15347 case CK_LValueToRValue:
15348 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15349 default:
15350 return Error(E);
15351 }
15352}
15353
15354bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15355 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15356 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15357
15358 const Expr *LHS = E->getLHS();
15359 const Expr *RHS = E->getRHS();
15360 FixedPointSemantics ResultFXSema =
15361 Info.Ctx.getFixedPointSemantics(E->getType());
15362
15363 APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
15364 if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
15365 return false;
15366 APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
15367 if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
15368 return false;
15369
15370 bool OpOverflow = false, ConversionOverflow = false;
15371 APFixedPoint Result(LHSFX.getSemantics());
15372 switch (E->getOpcode()) {
15373 case BO_Add: {
15374 Result = LHSFX.add(RHSFX, &OpOverflow)
15375 .convert(ResultFXSema, &ConversionOverflow);
15376 break;
15377 }
15378 case BO_Sub: {
15379 Result = LHSFX.sub(RHSFX, &OpOverflow)
15380 .convert(ResultFXSema, &ConversionOverflow);
15381 break;
15382 }
15383 case BO_Mul: {
15384 Result = LHSFX.mul(RHSFX, &OpOverflow)
15385 .convert(ResultFXSema, &ConversionOverflow);
15386 break;
15387 }
15388 case BO_Div: {
15389 if (RHSFX.getValue() == 0) {
15390 Info.FFDiag(E, diag::note_expr_divide_by_zero);
15391 return false;
15392 }
15393 Result = LHSFX.div(RHSFX, &OpOverflow)
15394 .convert(ResultFXSema, &ConversionOverflow);
15395 break;
15396 }
15397 case BO_Shl:
15398 case BO_Shr: {
15399 FixedPointSemantics LHSSema = LHSFX.getSemantics();
15400 llvm::APSInt RHSVal = RHSFX.getValue();
15401
15402 unsigned ShiftBW =
15403 LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
15404 unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
15405 // Embedded-C 4.1.6.2.2:
15406 // The right operand must be nonnegative and less than the total number
15407 // of (nonpadding) bits of the fixed-point operand ...
15408 if (RHSVal.isNegative())
15409 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
15410 else if (Amt != RHSVal)
15411 Info.CCEDiag(E, diag::note_constexpr_large_shift)
15412 << RHSVal << E->getType() << ShiftBW;
15413
15414 if (E->getOpcode() == BO_Shl)
15415 Result = LHSFX.shl(Amt, &OpOverflow);
15416 else
15417 Result = LHSFX.shr(Amt, &OpOverflow);
15418 break;
15419 }
15420 default:
15421 return false;
15422 }
15423 if (OpOverflow || ConversionOverflow) {
15424 if (Info.checkingForUndefinedBehavior())
15425 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
15426 diag::warn_fixedpoint_constant_overflow)
15427 << Result.toString() << E->getType();
15428 if (!HandleOverflow(Info, E, Result, E->getType()))
15429 return false;
15430 }
15431 return Success(Result, E);
15432}
15433
15434//===----------------------------------------------------------------------===//
15435// Float Evaluation
15436//===----------------------------------------------------------------------===//
15437
15438namespace {
15439class FloatExprEvaluator
15440 : public ExprEvaluatorBase<FloatExprEvaluator> {
15441 APFloat &Result;
15442public:
15443 FloatExprEvaluator(EvalInfo &info, APFloat &result)
15444 : ExprEvaluatorBaseTy(info), Result(result) {}
15445
15446 bool Success(const APValue &V, const Expr *e) {
15447 Result = V.getFloat();
15448 return true;
15449 }
15450
15451 bool ZeroInitialization(const Expr *E) {
15452 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
15453 return true;
15454 }
15455
15456 bool VisitCallExpr(const CallExpr *E);
15457
15458 bool VisitUnaryOperator(const UnaryOperator *E);
15459 bool VisitBinaryOperator(const BinaryOperator *E);
15460 bool VisitFloatingLiteral(const FloatingLiteral *E);
15461 bool VisitCastExpr(const CastExpr *E);
15462
15463 bool VisitUnaryReal(const UnaryOperator *E);
15464 bool VisitUnaryImag(const UnaryOperator *E);
15465
15466 // FIXME: Missing: array subscript of vector, member of vector
15467};
15468} // end anonymous namespace
15469
15470static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
15471 assert(!E->isValueDependent());
15472 assert(E->isPRValue() && E->getType()->isRealFloatingType());
15473 return FloatExprEvaluator(Info, Result).Visit(E);
15474}
15475
15476static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
15477 QualType ResultTy,
15478 const Expr *Arg,
15479 bool SNaN,
15480 llvm::APFloat &Result) {
15481 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
15482 if (!S) return false;
15483
15484 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
15485
15486 llvm::APInt fill;
15487
15488 // Treat empty strings as if they were zero.
15489 if (S->getString().empty())
15490 fill = llvm::APInt(32, 0);
15491 else if (S->getString().getAsInteger(0, fill))
15492 return false;
15493
15494 if (Context.getTargetInfo().isNan2008()) {
15495 if (SNaN)
15496 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15497 else
15498 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15499 } else {
15500 // Prior to IEEE 754-2008, architectures were allowed to choose whether
15501 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
15502 // a different encoding to what became a standard in 2008, and for pre-
15503 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
15504 // sNaN. This is now known as "legacy NaN" encoding.
15505 if (SNaN)
15506 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
15507 else
15508 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
15509 }
15510
15511 return true;
15512}
15513
15514bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
15515 if (!IsConstantEvaluatedBuiltinCall(E))
15516 return ExprEvaluatorBaseTy::VisitCallExpr(E);
15517
15518 switch (E->getBuiltinCallee()) {
15519 default:
15520 return false;
15521
15522 case Builtin::BI__builtin_huge_val:
15523 case Builtin::BI__builtin_huge_valf:
15524 case Builtin::BI__builtin_huge_vall:
15525 case Builtin::BI__builtin_huge_valf16:
15526 case Builtin::BI__builtin_huge_valf128:
15527 case Builtin::BI__builtin_inf:
15528 case Builtin::BI__builtin_inff:
15529 case Builtin::BI__builtin_infl:
15530 case Builtin::BI__builtin_inff16:
15531 case Builtin::BI__builtin_inff128: {
15532 const llvm::fltSemantics &Sem =
15533 Info.Ctx.getFloatTypeSemantics(E->getType());
15534 Result = llvm::APFloat::getInf(Sem);
15535 return true;
15536 }
15537
15538 case Builtin::BI__builtin_nans:
15539 case Builtin::BI__builtin_nansf:
15540 case Builtin::BI__builtin_nansl:
15541 case Builtin::BI__builtin_nansf16:
15542 case Builtin::BI__builtin_nansf128:
15543 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15544 true, Result))
15545 return Error(E);
15546 return true;
15547
15548 case Builtin::BI__builtin_nan:
15549 case Builtin::BI__builtin_nanf:
15550 case Builtin::BI__builtin_nanl:
15551 case Builtin::BI__builtin_nanf16:
15552 case Builtin::BI__builtin_nanf128:
15553 // If this is __builtin_nan() turn this into a nan, otherwise we
15554 // can't constant fold it.
15555 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
15556 false, Result))
15557 return Error(E);
15558 return true;
15559
15560 case Builtin::BI__builtin_fabs:
15561 case Builtin::BI__builtin_fabsf:
15562 case Builtin::BI__builtin_fabsl:
15563 case Builtin::BI__builtin_fabsf128:
15564 // The C standard says "fabs raises no floating-point exceptions,
15565 // even if x is a signaling NaN. The returned value is independent of
15566 // the current rounding direction mode." Therefore constant folding can
15567 // proceed without regard to the floating point settings.
15568 // Reference, WG14 N2478 F.10.4.3
15569 if (!EvaluateFloat(E->getArg(0), Result, Info))
15570 return false;
15571
15572 if (Result.isNegative())
15573 Result.changeSign();
15574 return true;
15575
15576 case Builtin::BI__arithmetic_fence:
15577 return EvaluateFloat(E->getArg(0), Result, Info);
15578
15579 // FIXME: Builtin::BI__builtin_powi
15580 // FIXME: Builtin::BI__builtin_powif
15581 // FIXME: Builtin::BI__builtin_powil
15582
15583 case Builtin::BI__builtin_copysign:
15584 case Builtin::BI__builtin_copysignf:
15585 case Builtin::BI__builtin_copysignl:
15586 case Builtin::BI__builtin_copysignf128: {
15587 APFloat RHS(0.);
15588 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15589 !EvaluateFloat(E->getArg(1), RHS, Info))
15590 return false;
15591 Result.copySign(RHS);
15592 return true;
15593 }
15594
15595 case Builtin::BI__builtin_fmax:
15596 case Builtin::BI__builtin_fmaxf:
15597 case Builtin::BI__builtin_fmaxl:
15598 case Builtin::BI__builtin_fmaxf16:
15599 case Builtin::BI__builtin_fmaxf128: {
15600 // TODO: Handle sNaN.
15601 APFloat RHS(0.);
15602 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15603 !EvaluateFloat(E->getArg(1), RHS, Info))
15604 return false;
15605 // When comparing zeroes, return +0.0 if one of the zeroes is positive.
15606 if (Result.isZero() && RHS.isZero() && Result.isNegative())
15607 Result = RHS;
15608 else if (Result.isNaN() || RHS > Result)
15609 Result = RHS;
15610 return true;
15611 }
15612
15613 case Builtin::BI__builtin_fmin:
15614 case Builtin::BI__builtin_fminf:
15615 case Builtin::BI__builtin_fminl:
15616 case Builtin::BI__builtin_fminf16:
15617 case Builtin::BI__builtin_fminf128: {
15618 // TODO: Handle sNaN.
15619 APFloat RHS(0.);
15620 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15621 !EvaluateFloat(E->getArg(1), RHS, Info))
15622 return false;
15623 // When comparing zeroes, return -0.0 if one of the zeroes is negative.
15624 if (Result.isZero() && RHS.isZero() && RHS.isNegative())
15625 Result = RHS;
15626 else if (Result.isNaN() || RHS < Result)
15627 Result = RHS;
15628 return true;
15629 }
15630
15631 case Builtin::BI__builtin_fmaximum_num:
15632 case Builtin::BI__builtin_fmaximum_numf:
15633 case Builtin::BI__builtin_fmaximum_numl:
15634 case Builtin::BI__builtin_fmaximum_numf16:
15635 case Builtin::BI__builtin_fmaximum_numf128: {
15636 APFloat RHS(0.);
15637 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15638 !EvaluateFloat(E->getArg(1), RHS, Info))
15639 return false;
15640 Result = maximumnum(Result, RHS);
15641 return true;
15642 }
15643
15644 case Builtin::BI__builtin_fminimum_num:
15645 case Builtin::BI__builtin_fminimum_numf:
15646 case Builtin::BI__builtin_fminimum_numl:
15647 case Builtin::BI__builtin_fminimum_numf16:
15648 case Builtin::BI__builtin_fminimum_numf128: {
15649 APFloat RHS(0.);
15650 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
15651 !EvaluateFloat(E->getArg(1), RHS, Info))
15652 return false;
15653 Result = minimumnum(Result, RHS);
15654 return true;
15655 }
15656 }
15657}
15658
15659bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
15660 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15661 ComplexValue CV;
15662 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15663 return false;
15664 Result = CV.FloatReal;
15665 return true;
15666 }
15667
15668 return Visit(E->getSubExpr());
15669}
15670
15671bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
15672 if (E->getSubExpr()->getType()->isAnyComplexType()) {
15673 ComplexValue CV;
15674 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
15675 return false;
15676 Result = CV.FloatImag;
15677 return true;
15678 }
15679
15680 VisitIgnoredValue(E->getSubExpr());
15681 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
15682 Result = llvm::APFloat::getZero(Sem);
15683 return true;
15684}
15685
15686bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
15687 switch (E->getOpcode()) {
15688 default: return Error(E);
15689 case UO_Plus:
15690 return EvaluateFloat(E->getSubExpr(), Result, Info);
15691 case UO_Minus:
15692 // In C standard, WG14 N2478 F.3 p4
15693 // "the unary - raises no floating point exceptions,
15694 // even if the operand is signalling."
15695 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
15696 return false;
15697 Result.changeSign();
15698 return true;
15699 }
15700}
15701
15702bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
15703 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
15704 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
15705
15706 APFloat RHS(0.0);
15707 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
15708 if (!LHSOK && !Info.noteFailure())
15709 return false;
15710 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
15711 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
15712}
15713
15714bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
15715 Result = E->getValue();
15716 return true;
15717}
15718
15719bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
15720 const Expr* SubExpr = E->getSubExpr();
15721
15722 switch (E->getCastKind()) {
15723 default:
15724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15725
15726 case CK_IntegralToFloating: {
15727 APSInt IntResult;
15728 const FPOptions FPO = E->getFPFeaturesInEffect(
15729 Info.Ctx.getLangOpts());
15730 return EvaluateInteger(SubExpr, IntResult, Info) &&
15731 HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
15732 IntResult, E->getType(), Result);
15733 }
15734
15735 case CK_FixedPointToFloating: {
15736 APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
15737 if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
15738 return false;
15739 Result =
15740 FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
15741 return true;
15742 }
15743
15744 case CK_FloatingCast: {
15745 if (!Visit(SubExpr))
15746 return false;
15747 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
15748 Result);
15749 }
15750
15751 case CK_FloatingComplexToReal: {
15752 ComplexValue V;
15753 if (!EvaluateComplex(SubExpr, V, Info))
15754 return false;
15755 Result = V.getComplexFloatReal();
15756 return true;
15757 }
15758 case CK_HLSLVectorTruncation: {
15759 APValue Val;
15760 if (!EvaluateVector(SubExpr, Val, Info))
15761 return Error(E);
15762 return Success(Val.getVectorElt(0), E);
15763 }
15764 }
15765}
15766
15767//===----------------------------------------------------------------------===//
15768// Complex Evaluation (for float and integer)
15769//===----------------------------------------------------------------------===//
15770
15771namespace {
15772class ComplexExprEvaluator
15773 : public ExprEvaluatorBase<ComplexExprEvaluator> {
15774 ComplexValue &Result;
15775
15776public:
15777 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
15778 : ExprEvaluatorBaseTy(info), Result(Result) {}
15779
15780 bool Success(const APValue &V, const Expr *e) {
15781 Result.setFrom(V);
15782 return true;
15783 }
15784
15785 bool ZeroInitialization(const Expr *E);
15786
15787 //===--------------------------------------------------------------------===//
15788 // Visitor Methods
15789 //===--------------------------------------------------------------------===//
15790
15791 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
15792 bool VisitCastExpr(const CastExpr *E);
15793 bool VisitBinaryOperator(const BinaryOperator *E);
15794 bool VisitUnaryOperator(const UnaryOperator *E);
15795 bool VisitInitListExpr(const InitListExpr *E);
15796 bool VisitCallExpr(const CallExpr *E);
15797};
15798} // end anonymous namespace
15799
15800static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
15801 EvalInfo &Info) {
15802 assert(!E->isValueDependent());
15803 assert(E->isPRValue() && E->getType()->isAnyComplexType());
15804 return ComplexExprEvaluator(Info, Result).Visit(E);
15805}
15806
15807bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
15808 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
15809 if (ElemTy->isRealFloatingType()) {
15810 Result.makeComplexFloat();
15811 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
15812 Result.FloatReal = Zero;
15813 Result.FloatImag = Zero;
15814 } else {
15815 Result.makeComplexInt();
15816 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
15817 Result.IntReal = Zero;
15818 Result.IntImag = Zero;
15819 }
15820 return true;
15821}
15822
15823bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
15824 const Expr* SubExpr = E->getSubExpr();
15825
15826 if (SubExpr->getType()->isRealFloatingType()) {
15827 Result.makeComplexFloat();
15828 APFloat &Imag = Result.FloatImag;
15829 if (!EvaluateFloat(SubExpr, Imag, Info))
15830 return false;
15831
15832 Result.FloatReal = APFloat(Imag.getSemantics());
15833 return true;
15834 } else {
15835 assert(SubExpr->getType()->isIntegerType() &&
15836 "Unexpected imaginary literal.");
15837
15838 Result.makeComplexInt();
15839 APSInt &Imag = Result.IntImag;
15840 if (!EvaluateInteger(SubExpr, Imag, Info))
15841 return false;
15842
15843 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
15844 return true;
15845 }
15846}
15847
15848bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
15849
15850 switch (E->getCastKind()) {
15851 case CK_BitCast:
15852 case CK_BaseToDerived:
15853 case CK_DerivedToBase:
15854 case CK_UncheckedDerivedToBase:
15855 case CK_Dynamic:
15856 case CK_ToUnion:
15857 case CK_ArrayToPointerDecay:
15858 case CK_FunctionToPointerDecay:
15859 case CK_NullToPointer:
15860 case CK_NullToMemberPointer:
15861 case CK_BaseToDerivedMemberPointer:
15862 case CK_DerivedToBaseMemberPointer:
15863 case CK_MemberPointerToBoolean:
15864 case CK_ReinterpretMemberPointer:
15865 case CK_ConstructorConversion:
15866 case CK_IntegralToPointer:
15867 case CK_PointerToIntegral:
15868 case CK_PointerToBoolean:
15869 case CK_ToVoid:
15870 case CK_VectorSplat:
15871 case CK_IntegralCast:
15872 case CK_BooleanToSignedIntegral:
15873 case CK_IntegralToBoolean:
15874 case CK_IntegralToFloating:
15875 case CK_FloatingToIntegral:
15876 case CK_FloatingToBoolean:
15877 case CK_FloatingCast:
15878 case CK_CPointerToObjCPointerCast:
15879 case CK_BlockPointerToObjCPointerCast:
15880 case CK_AnyPointerToBlockPointerCast:
15881 case CK_ObjCObjectLValueCast:
15882 case CK_FloatingComplexToReal:
15883 case CK_FloatingComplexToBoolean:
15884 case CK_IntegralComplexToReal:
15885 case CK_IntegralComplexToBoolean:
15886 case CK_ARCProduceObject:
15887 case CK_ARCConsumeObject:
15888 case CK_ARCReclaimReturnedObject:
15889 case CK_ARCExtendBlockObject:
15890 case CK_CopyAndAutoreleaseBlockObject:
15891 case CK_BuiltinFnToFnPtr:
15892 case CK_ZeroToOCLOpaqueType:
15893 case CK_NonAtomicToAtomic:
15894 case CK_AddressSpaceConversion:
15895 case CK_IntToOCLSampler:
15896 case CK_FloatingToFixedPoint:
15897 case CK_FixedPointToFloating:
15898 case CK_FixedPointCast:
15899 case CK_FixedPointToBoolean:
15900 case CK_FixedPointToIntegral:
15901 case CK_IntegralToFixedPoint:
15902 case CK_MatrixCast:
15903 case CK_HLSLVectorTruncation:
15904 llvm_unreachable("invalid cast kind for complex value");
15905
15906 case CK_LValueToRValue:
15907 case CK_AtomicToNonAtomic:
15908 case CK_NoOp:
15909 case CK_LValueToRValueBitCast:
15910 case CK_HLSLArrayRValue:
15911 return ExprEvaluatorBaseTy::VisitCastExpr(E);
15912
15913 case CK_Dependent:
15914 case CK_LValueBitCast:
15915 case CK_UserDefinedConversion:
15916 return Error(E);
15917
15918 case CK_FloatingRealToComplex: {
15919 APFloat &Real = Result.FloatReal;
15920 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
15921 return false;
15922
15923 Result.makeComplexFloat();
15924 Result.FloatImag = APFloat(Real.getSemantics());
15925 return true;
15926 }
15927
15928 case CK_FloatingComplexCast: {
15929 if (!Visit(E->getSubExpr()))
15930 return false;
15931
15932 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15933 QualType From
15934 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15935
15936 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
15937 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
15938 }
15939
15940 case CK_FloatingComplexToIntegralComplex: {
15941 if (!Visit(E->getSubExpr()))
15942 return false;
15943
15944 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15945 QualType From
15946 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15947 Result.makeComplexInt();
15948 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
15949 To, Result.IntReal) &&
15950 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
15951 To, Result.IntImag);
15952 }
15953
15954 case CK_IntegralRealToComplex: {
15955 APSInt &Real = Result.IntReal;
15956 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
15957 return false;
15958
15959 Result.makeComplexInt();
15960 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
15961 return true;
15962 }
15963
15964 case CK_IntegralComplexCast: {
15965 if (!Visit(E->getSubExpr()))
15966 return false;
15967
15968 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15969 QualType From
15970 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15971
15972 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
15973 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
15974 return true;
15975 }
15976
15977 case CK_IntegralComplexToFloatingComplex: {
15978 if (!Visit(E->getSubExpr()))
15979 return false;
15980
15981 const FPOptions FPO = E->getFPFeaturesInEffect(
15982 Info.Ctx.getLangOpts());
15983 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
15984 QualType From
15985 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
15986 Result.makeComplexFloat();
15987 return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
15988 To, Result.FloatReal) &&
15989 HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
15990 To, Result.FloatImag);
15991 }
15992 }
15993
15994 llvm_unreachable("unknown cast resulting in complex value");
15995}
15996
15997void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D,
15998 APFloat &ResR, APFloat &ResI) {
15999 // This is an implementation of complex multiplication according to the
16000 // constraints laid out in C11 Annex G. The implementation uses the
16001 // following naming scheme:
16002 // (a + ib) * (c + id)
16003
16004 APFloat AC = A * C;
16005 APFloat BD = B * D;
16006 APFloat AD = A * D;
16007 APFloat BC = B * C;
16008 ResR = AC - BD;
16009 ResI = AD + BC;
16010 if (ResR.isNaN() && ResI.isNaN()) {
16011 bool Recalc = false;
16012 if (A.isInfinity() || B.isInfinity()) {
16013 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16014 A);
16015 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16016 B);
16017 if (C.isNaN())
16018 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16019 if (D.isNaN())
16020 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16021 Recalc = true;
16022 }
16023 if (C.isInfinity() || D.isInfinity()) {
16024 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16025 C);
16026 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16027 D);
16028 if (A.isNaN())
16029 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16030 if (B.isNaN())
16031 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16032 Recalc = true;
16033 }
16034 if (!Recalc && (AC.isInfinity() || BD.isInfinity() || AD.isInfinity() ||
16035 BC.isInfinity())) {
16036 if (A.isNaN())
16037 A = APFloat::copySign(APFloat(A.getSemantics()), A);
16038 if (B.isNaN())
16039 B = APFloat::copySign(APFloat(B.getSemantics()), B);
16040 if (C.isNaN())
16041 C = APFloat::copySign(APFloat(C.getSemantics()), C);
16042 if (D.isNaN())
16043 D = APFloat::copySign(APFloat(D.getSemantics()), D);
16044 Recalc = true;
16045 }
16046 if (Recalc) {
16047 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
16048 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
16049 }
16050 }
16051}
16052
16053void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D,
16054 APFloat &ResR, APFloat &ResI) {
16055 // This is an implementation of complex division according to the
16056 // constraints laid out in C11 Annex G. The implementation uses the
16057 // following naming scheme:
16058 // (a + ib) / (c + id)
16059
16060 int DenomLogB = 0;
16061 APFloat MaxCD = maxnum(abs(C), abs(D));
16062 if (MaxCD.isFinite()) {
16063 DenomLogB = ilogb(MaxCD);
16064 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
16065 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
16066 }
16067 APFloat Denom = C * C + D * D;
16068 ResR =
16069 scalbn((A * C + B * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16070 ResI =
16071 scalbn((B * C - A * D) / Denom, -DenomLogB, APFloat::rmNearestTiesToEven);
16072 if (ResR.isNaN() && ResI.isNaN()) {
16073 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
16074 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
16075 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
16076 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
16077 D.isFinite()) {
16078 A = APFloat::copySign(APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0),
16079 A);
16080 B = APFloat::copySign(APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0),
16081 B);
16082 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
16083 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
16084 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
16085 C = APFloat::copySign(APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0),
16086 C);
16087 D = APFloat::copySign(APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0),
16088 D);
16089 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
16090 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
16091 }
16092 }
16093}
16094
16095bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
16096 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
16097 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
16098
16099 // Track whether the LHS or RHS is real at the type system level. When this is
16100 // the case we can simplify our evaluation strategy.
16101 bool LHSReal = false, RHSReal = false;
16102
16103 bool LHSOK;
16104 if (E->getLHS()->getType()->isRealFloatingType()) {
16105 LHSReal = true;
16106 APFloat &Real = Result.FloatReal;
16107 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
16108 if (LHSOK) {
16109 Result.makeComplexFloat();
16110 Result.FloatImag = APFloat(Real.getSemantics());
16111 }
16112 } else {
16113 LHSOK = Visit(E->getLHS());
16114 }
16115 if (!LHSOK && !Info.noteFailure())
16116 return false;
16117
16118 ComplexValue RHS;
16119 if (E->getRHS()->getType()->isRealFloatingType()) {
16120 RHSReal = true;
16121 APFloat &Real = RHS.FloatReal;
16122 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
16123 return false;
16124 RHS.makeComplexFloat();
16125 RHS.FloatImag = APFloat(Real.getSemantics());
16126 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
16127 return false;
16128
16129 assert(!(LHSReal && RHSReal) &&
16130 "Cannot have both operands of a complex operation be real.");
16131 switch (E->getOpcode()) {
16132 default: return Error(E);
16133 case BO_Add:
16134 if (Result.isComplexFloat()) {
16135 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
16136 APFloat::rmNearestTiesToEven);
16137 if (LHSReal)
16138 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16139 else if (!RHSReal)
16140 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
16141 APFloat::rmNearestTiesToEven);
16142 } else {
16143 Result.getComplexIntReal() += RHS.getComplexIntReal();
16144 Result.getComplexIntImag() += RHS.getComplexIntImag();
16145 }
16146 break;
16147 case BO_Sub:
16148 if (Result.isComplexFloat()) {
16149 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
16150 APFloat::rmNearestTiesToEven);
16151 if (LHSReal) {
16152 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
16153 Result.getComplexFloatImag().changeSign();
16154 } else if (!RHSReal) {
16155 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
16156 APFloat::rmNearestTiesToEven);
16157 }
16158 } else {
16159 Result.getComplexIntReal() -= RHS.getComplexIntReal();
16160 Result.getComplexIntImag() -= RHS.getComplexIntImag();
16161 }
16162 break;
16163 case BO_Mul:
16164 if (Result.isComplexFloat()) {
16165 // This is an implementation of complex multiplication according to the
16166 // constraints laid out in C11 Annex G. The implementation uses the
16167 // following naming scheme:
16168 // (a + ib) * (c + id)
16169 ComplexValue LHS = Result;
16170 APFloat &A = LHS.getComplexFloatReal();
16171 APFloat &B = LHS.getComplexFloatImag();
16172 APFloat &C = RHS.getComplexFloatReal();
16173 APFloat &D = RHS.getComplexFloatImag();
16174 APFloat &ResR = Result.getComplexFloatReal();
16175 APFloat &ResI = Result.getComplexFloatImag();
16176 if (LHSReal) {
16177 assert(!RHSReal && "Cannot have two real operands for a complex op!");
16178 ResR = A;
16179 ResI = A;
16180 // ResR = A * C;
16181 // ResI = A * D;
16182 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, C) ||
16183 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, D))
16184 return false;
16185 } else if (RHSReal) {
16186 // ResR = C * A;
16187 // ResI = C * B;
16188 ResR = C;
16189 ResI = C;
16190 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Mul, A) ||
16191 !handleFloatFloatBinOp(Info, E, ResI, BO_Mul, B))
16192 return false;
16193 } else {
16194 HandleComplexComplexMul(A, B, C, D, ResR, ResI);
16195 }
16196 } else {
16197 ComplexValue LHS = Result;
16198 Result.getComplexIntReal() =
16199 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
16200 LHS.getComplexIntImag() * RHS.getComplexIntImag());
16201 Result.getComplexIntImag() =
16202 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
16203 LHS.getComplexIntImag() * RHS.getComplexIntReal());
16204 }
16205 break;
16206 case BO_Div:
16207 if (Result.isComplexFloat()) {
16208 // This is an implementation of complex division according to the
16209 // constraints laid out in C11 Annex G. The implementation uses the
16210 // following naming scheme:
16211 // (a + ib) / (c + id)
16212 ComplexValue LHS = Result;
16213 APFloat &A = LHS.getComplexFloatReal();
16214 APFloat &B = LHS.getComplexFloatImag();
16215 APFloat &C = RHS.getComplexFloatReal();
16216 APFloat &D = RHS.getComplexFloatImag();
16217 APFloat &ResR = Result.getComplexFloatReal();
16218 APFloat &ResI = Result.getComplexFloatImag();
16219 if (RHSReal) {
16220 ResR = A;
16221 ResI = B;
16222 // ResR = A / C;
16223 // ResI = B / C;
16224 if (!handleFloatFloatBinOp(Info, E, ResR, BO_Div, C) ||
16225 !handleFloatFloatBinOp(Info, E, ResI, BO_Div, C))
16226 return false;
16227 } else {
16228 if (LHSReal) {
16229 // No real optimizations we can do here, stub out with zero.
16230 B = APFloat::getZero(A.getSemantics());
16231 }
16232 HandleComplexComplexDiv(A, B, C, D, ResR, ResI);
16233 }
16234 } else {
16235 ComplexValue LHS = Result;
16236 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
16237 RHS.getComplexIntImag() * RHS.getComplexIntImag();
16238 if (Den.isZero())
16239 return Error(E, diag::note_expr_divide_by_zero);
16240
16241 Result.getComplexIntReal() =
16242 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
16243 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
16244 Result.getComplexIntImag() =
16245 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
16246 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
16247 }
16248 break;
16249 }
16250
16251 return true;
16252}
16253
16254bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
16255 // Get the operand value into 'Result'.
16256 if (!Visit(E->getSubExpr()))
16257 return false;
16258
16259 switch (E->getOpcode()) {
16260 default:
16261 return Error(E);
16262 case UO_Extension:
16263 return true;
16264 case UO_Plus:
16265 // The result is always just the subexpr.
16266 return true;
16267 case UO_Minus:
16268 if (Result.isComplexFloat()) {
16269 Result.getComplexFloatReal().changeSign();
16270 Result.getComplexFloatImag().changeSign();
16271 }
16272 else {
16273 Result.getComplexIntReal() = -Result.getComplexIntReal();
16274 Result.getComplexIntImag() = -Result.getComplexIntImag();
16275 }
16276 return true;
16277 case UO_Not:
16278 if (Result.isComplexFloat())
16279 Result.getComplexFloatImag().changeSign();
16280 else
16281 Result.getComplexIntImag() = -Result.getComplexIntImag();
16282 return true;
16283 }
16284}
16285
16286bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
16287 if (E->getNumInits() == 2) {
16288 if (E->getType()->isComplexType()) {
16289 Result.makeComplexFloat();
16290 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
16291 return false;
16292 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
16293 return false;
16294 } else {
16295 Result.makeComplexInt();
16296 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
16297 return false;
16298 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
16299 return false;
16300 }
16301 return true;
16302 }
16303 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
16304}
16305
16306bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
16307 if (!IsConstantEvaluatedBuiltinCall(E))
16308 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16309
16310 switch (E->getBuiltinCallee()) {
16311 case Builtin::BI__builtin_complex:
16312 Result.makeComplexFloat();
16313 if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
16314 return false;
16315 if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
16316 return false;
16317 return true;
16318
16319 default:
16320 return false;
16321 }
16322}
16323
16324//===----------------------------------------------------------------------===//
16325// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
16326// implicit conversion.
16327//===----------------------------------------------------------------------===//
16328
16329namespace {
16330class AtomicExprEvaluator :
16331 public ExprEvaluatorBase<AtomicExprEvaluator> {
16332 const LValue *This;
16333 APValue &Result;
16334public:
16335 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
16336 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
16337
16338 bool Success(const APValue &V, const Expr *E) {
16339 Result = V;
16340 return true;
16341 }
16342
16343 bool ZeroInitialization(const Expr *E) {
16346 // For atomic-qualified class (and array) types in C++, initialize the
16347 // _Atomic-wrapped subobject directly, in-place.
16348 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
16349 : Evaluate(Result, Info, &VIE);
16350 }
16351
16352 bool VisitCastExpr(const CastExpr *E) {
16353 switch (E->getCastKind()) {
16354 default:
16355 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16356 case CK_NullToPointer:
16357 VisitIgnoredValue(E->getSubExpr());
16358 return ZeroInitialization(E);
16359 case CK_NonAtomicToAtomic:
16360 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
16361 : Evaluate(Result, Info, E->getSubExpr());
16362 }
16363 }
16364};
16365} // end anonymous namespace
16366
16367static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
16368 EvalInfo &Info) {
16369 assert(!E->isValueDependent());
16370 assert(E->isPRValue() && E->getType()->isAtomicType());
16371 return AtomicExprEvaluator(Info, This, Result).Visit(E);
16372}
16373
16374//===----------------------------------------------------------------------===//
16375// Void expression evaluation, primarily for a cast to void on the LHS of a
16376// comma operator
16377//===----------------------------------------------------------------------===//
16378
16379namespace {
16380class VoidExprEvaluator
16381 : public ExprEvaluatorBase<VoidExprEvaluator> {
16382public:
16383 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
16384
16385 bool Success(const APValue &V, const Expr *e) { return true; }
16386
16387 bool ZeroInitialization(const Expr *E) { return true; }
16388
16389 bool VisitCastExpr(const CastExpr *E) {
16390 switch (E->getCastKind()) {
16391 default:
16392 return ExprEvaluatorBaseTy::VisitCastExpr(E);
16393 case CK_ToVoid:
16394 VisitIgnoredValue(E->getSubExpr());
16395 return true;
16396 }
16397 }
16398
16399 bool VisitCallExpr(const CallExpr *E) {
16400 if (!IsConstantEvaluatedBuiltinCall(E))
16401 return ExprEvaluatorBaseTy::VisitCallExpr(E);
16402
16403 switch (E->getBuiltinCallee()) {
16404 case Builtin::BI__assume:
16405 case Builtin::BI__builtin_assume:
16406 // The argument is not evaluated!
16407 return true;
16408
16409 case Builtin::BI__builtin_operator_delete:
16410 return HandleOperatorDeleteCall(Info, E);
16411
16412 default:
16413 return false;
16414 }
16415 }
16416
16417 bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
16418};
16419} // end anonymous namespace
16420
16421bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
16422 // We cannot speculatively evaluate a delete expression.
16423 if (Info.SpeculativeEvaluationDepth)
16424 return false;
16425
16426 FunctionDecl *OperatorDelete = E->getOperatorDelete();
16427 if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
16428 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16429 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
16430 return false;
16431 }
16432
16433 const Expr *Arg = E->getArgument();
16434
16435 LValue Pointer;
16436 if (!EvaluatePointer(Arg, Pointer, Info))
16437 return false;
16438 if (Pointer.Designator.Invalid)
16439 return false;
16440
16441 // Deleting a null pointer has no effect.
16442 if (Pointer.isNullPointer()) {
16443 // This is the only case where we need to produce an extension warning:
16444 // the only other way we can succeed is if we find a dynamic allocation,
16445 // and we will have warned when we allocated it in that case.
16446 if (!Info.getLangOpts().CPlusPlus20)
16447 Info.CCEDiag(E, diag::note_constexpr_new);
16448 return true;
16449 }
16450
16451 std::optional<DynAlloc *> Alloc = CheckDeleteKind(
16452 Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
16453 if (!Alloc)
16454 return false;
16455 QualType AllocType = Pointer.Base.getDynamicAllocType();
16456
16457 // For the non-array case, the designator must be empty if the static type
16458 // does not have a virtual destructor.
16459 if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
16461 Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
16462 << Arg->getType()->getPointeeType() << AllocType;
16463 return false;
16464 }
16465
16466 // For a class type with a virtual destructor, the selected operator delete
16467 // is the one looked up when building the destructor.
16468 if (!E->isArrayForm() && !E->isGlobalDelete()) {
16469 const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
16470 if (VirtualDelete &&
16471 !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
16472 Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
16473 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
16474 return false;
16475 }
16476 }
16477
16478 if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
16479 (*Alloc)->Value, AllocType))
16480 return false;
16481
16482 if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
16483 // The element was already erased. This means the destructor call also
16484 // deleted the object.
16485 // FIXME: This probably results in undefined behavior before we get this
16486 // far, and should be diagnosed elsewhere first.
16487 Info.FFDiag(E, diag::note_constexpr_double_delete);
16488 return false;
16489 }
16490
16491 return true;
16492}
16493
16494static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
16495 assert(!E->isValueDependent());
16496 assert(E->isPRValue() && E->getType()->isVoidType());
16497 return VoidExprEvaluator(Info).Visit(E);
16498}
16499
16500//===----------------------------------------------------------------------===//
16501// Top level Expr::EvaluateAsRValue method.
16502//===----------------------------------------------------------------------===//
16503
16504static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
16505 assert(!E->isValueDependent());
16506 // In C, function designators are not lvalues, but we evaluate them as if they
16507 // are.
16508 QualType T = E->getType();
16509 if (E->isGLValue() || T->isFunctionType()) {
16510 LValue LV;
16511 if (!EvaluateLValue(E, LV, Info))
16512 return false;
16513 LV.moveInto(Result);
16514 } else if (T->isVectorType()) {
16515 if (!EvaluateVector(E, Result, Info))
16516 return false;
16517 } else if (T->isIntegralOrEnumerationType()) {
16518 if (!IntExprEvaluator(Info, Result).Visit(E))
16519 return false;
16520 } else if (T->hasPointerRepresentation()) {
16521 LValue LV;
16522 if (!EvaluatePointer(E, LV, Info))
16523 return false;
16524 LV.moveInto(Result);
16525 } else if (T->isRealFloatingType()) {
16526 llvm::APFloat F(0.0);
16527 if (!EvaluateFloat(E, F, Info))
16528 return false;
16529 Result = APValue(F);
16530 } else if (T->isAnyComplexType()) {
16531 ComplexValue C;
16532 if (!EvaluateComplex(E, C, Info))
16533 return false;
16534 C.moveInto(Result);
16535 } else if (T->isFixedPointType()) {
16536 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
16537 } else if (T->isMemberPointerType()) {
16538 MemberPtr P;
16539 if (!EvaluateMemberPointer(E, P, Info))
16540 return false;
16541 P.moveInto(Result);
16542 return true;
16543 } else if (T->isArrayType()) {
16544 LValue LV;
16545 APValue &Value =
16546 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16547 if (!EvaluateArray(E, LV, Value, Info))
16548 return false;
16549 Result = Value;
16550 } else if (T->isRecordType()) {
16551 LValue LV;
16552 APValue &Value =
16553 Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
16554 if (!EvaluateRecord(E, LV, Value, Info))
16555 return false;
16556 Result = Value;
16557 } else if (T->isVoidType()) {
16558 if (!Info.getLangOpts().CPlusPlus11)
16559 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
16560 << E->getType();
16561 if (!EvaluateVoid(E, Info))
16562 return false;
16563 } else if (T->isAtomicType()) {
16564 QualType Unqual = T.getAtomicUnqualifiedType();
16565 if (Unqual->isArrayType() || Unqual->isRecordType()) {
16566 LValue LV;
16567 APValue &Value = Info.CurrentCall->createTemporary(
16568 E, Unqual, ScopeKind::FullExpression, LV);
16569 if (!EvaluateAtomic(E, &LV, Value, Info))
16570 return false;
16571 Result = Value;
16572 } else {
16573 if (!EvaluateAtomic(E, nullptr, Result, Info))
16574 return false;
16575 }
16576 } else if (Info.getLangOpts().CPlusPlus11) {
16577 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
16578 return false;
16579 } else {
16580 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
16581 return false;
16582 }
16583
16584 return true;
16585}
16586
16587/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
16588/// cases, the in-place evaluation is essential, since later initializers for
16589/// an object can indirectly refer to subobjects which were initialized earlier.
16590static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
16591 const Expr *E, bool AllowNonLiteralTypes) {
16592 assert(!E->isValueDependent());
16593
16594 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
16595 return false;
16596
16597 if (E->isPRValue()) {
16598 // Evaluate arrays and record types in-place, so that later initializers can
16599 // refer to earlier-initialized members of the object.
16600 QualType T = E->getType();
16601 if (T->isArrayType())
16602 return EvaluateArray(E, This, Result, Info);
16603 else if (T->isRecordType())
16604 return EvaluateRecord(E, This, Result, Info);
16605 else if (T->isAtomicType()) {
16606 QualType Unqual = T.getAtomicUnqualifiedType();
16607 if (Unqual->isArrayType() || Unqual->isRecordType())
16608 return EvaluateAtomic(E, &This, Result, Info);
16609 }
16610 }
16611
16612 // For any other type, in-place evaluation is unimportant.
16613 return Evaluate(Result, Info, E);
16614}
16615
16616/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
16617/// lvalue-to-rvalue cast if it is an lvalue.
16618static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
16619 assert(!E->isValueDependent());
16620
16621 if (E->getType().isNull())
16622 return false;
16623
16624 if (!CheckLiteralType(Info, E))
16625 return false;
16626
16627 if (Info.EnableNewConstInterp) {
16628 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
16629 return false;
16630 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16631 ConstantExprKind::Normal);
16632 }
16633
16634 if (!::Evaluate(Result, Info, E))
16635 return false;
16636
16637 // Implicit lvalue-to-rvalue cast.
16638 if (E->isGLValue()) {
16639 LValue LV;
16640 LV.setFrom(Info.Ctx, Result);
16641 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
16642 return false;
16643 }
16644
16645 // Check this core constant expression is a constant expression.
16646 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
16647 ConstantExprKind::Normal) &&
16648 CheckMemoryLeaks(Info);
16649}
16650
16651static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
16652 const ASTContext &Ctx, bool &IsConst) {
16653 // Fast-path evaluations of integer literals, since we sometimes see files
16654 // containing vast quantities of these.
16655 if (const auto *L = dyn_cast<IntegerLiteral>(Exp)) {
16656 Result.Val = APValue(APSInt(L->getValue(),
16657 L->getType()->isUnsignedIntegerType()));
16658 IsConst = true;
16659 return true;
16660 }
16661
16662 if (const auto *L = dyn_cast<CXXBoolLiteralExpr>(Exp)) {
16663 Result.Val = APValue(APSInt(APInt(1, L->getValue())));
16664 IsConst = true;
16665 return true;
16666 }
16667
16668 if (const auto *FL = dyn_cast<FloatingLiteral>(Exp)) {
16669 Result.Val = APValue(FL->getValue());
16670 IsConst = true;
16671 return true;
16672 }
16673
16674 if (const auto *L = dyn_cast<CharacterLiteral>(Exp)) {
16675 Result.Val = APValue(Ctx.MakeIntValue(L->getValue(), L->getType()));
16676 IsConst = true;
16677 return true;
16678 }
16679
16680 if (const auto *CE = dyn_cast<ConstantExpr>(Exp)) {
16681 if (CE->hasAPValueResult()) {
16682 APValue APV = CE->getAPValueResult();
16683 if (!APV.isLValue()) {
16684 Result.Val = std::move(APV);
16685 IsConst = true;
16686 return true;
16687 }
16688 }
16689
16690 // The SubExpr is usually just an IntegerLiteral.
16691 return FastEvaluateAsRValue(CE->getSubExpr(), Result, Ctx, IsConst);
16692 }
16693
16694 // This case should be rare, but we need to check it before we check on
16695 // the type below.
16696 if (Exp->getType().isNull()) {
16697 IsConst = false;
16698 return true;
16699 }
16700
16701 return false;
16702}
16703
16706 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
16707 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
16708}
16709
16710static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
16711 const ASTContext &Ctx, EvalInfo &Info) {
16712 assert(!E->isValueDependent());
16713 bool IsConst;
16714 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
16715 return IsConst;
16716
16717 return EvaluateAsRValue(Info, E, Result.Val);
16718}
16719
16721 const ASTContext &Ctx,
16722 Expr::SideEffectsKind AllowSideEffects,
16723 EvalInfo &Info) {
16724 assert(!E->isValueDependent());
16726 return false;
16727
16728 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
16729 !ExprResult.Val.isInt() ||
16730 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16731 return false;
16732
16733 return true;
16734}
16735
16737 const ASTContext &Ctx,
16738 Expr::SideEffectsKind AllowSideEffects,
16739 EvalInfo &Info) {
16740 assert(!E->isValueDependent());
16741 if (!E->getType()->isFixedPointType())
16742 return false;
16743
16744 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
16745 return false;
16746
16747 if (!ExprResult.Val.isFixedPoint() ||
16748 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16749 return false;
16750
16751 return true;
16752}
16753
16754/// EvaluateAsRValue - Return true if this is a constant which we can fold using
16755/// any crazy technique (that has nothing to do with language standards) that
16756/// we want to. If this function returns true, it returns the folded constant
16757/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
16758/// will be applied to the result.
16760 bool InConstantContext) const {
16761 assert(!isValueDependent() &&
16762 "Expression evaluator can't be called on a dependent expression.");
16763 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsRValue");
16764 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16765 Info.InConstantContext = InConstantContext;
16766 return ::EvaluateAsRValue(this, Result, Ctx, Info);
16767}
16768
16769bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
16770 bool InConstantContext) const {
16771 assert(!isValueDependent() &&
16772 "Expression evaluator can't be called on a dependent expression.");
16773 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsBooleanCondition");
16774 EvalResult Scratch;
16775 return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
16776 HandleConversionToBool(Scratch.Val, Result);
16777}
16778
16780 SideEffectsKind AllowSideEffects,
16781 bool InConstantContext) const {
16782 assert(!isValueDependent() &&
16783 "Expression evaluator can't be called on a dependent expression.");
16784 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsInt");
16785 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16786 Info.InConstantContext = InConstantContext;
16787 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
16788}
16789
16791 SideEffectsKind AllowSideEffects,
16792 bool InConstantContext) const {
16793 assert(!isValueDependent() &&
16794 "Expression evaluator can't be called on a dependent expression.");
16795 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFixedPoint");
16796 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
16797 Info.InConstantContext = InConstantContext;
16798 return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
16799}
16800
16801bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
16802 SideEffectsKind AllowSideEffects,
16803 bool InConstantContext) const {
16804 assert(!isValueDependent() &&
16805 "Expression evaluator can't be called on a dependent expression.");
16806
16807 if (!getType()->isRealFloatingType())
16808 return false;
16809
16810 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsFloat");
16812 if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
16813 !ExprResult.Val.isFloat() ||
16814 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
16815 return false;
16816
16817 Result = ExprResult.Val.getFloat();
16818 return true;
16819}
16820
16822 bool InConstantContext) const {
16823 assert(!isValueDependent() &&
16824 "Expression evaluator can't be called on a dependent expression.");
16825
16826 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsLValue");
16827 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
16828 Info.InConstantContext = InConstantContext;
16829 LValue LV;
16830 CheckedTemporaries CheckedTemps;
16831 if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
16832 Result.HasSideEffects ||
16833 !CheckLValueConstantExpression(Info, getExprLoc(),
16834 Ctx.getLValueReferenceType(getType()), LV,
16835 ConstantExprKind::Normal, CheckedTemps))
16836 return false;
16837
16838 LV.moveInto(Result.Val);
16839 return true;
16840}
16841
16843 APValue DestroyedValue, QualType Type,
16845 bool IsConstantDestruction) {
16846 EvalInfo Info(Ctx, EStatus,
16847 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
16848 : EvalInfo::EM_ConstantFold);
16849 Info.setEvaluatingDecl(Base, DestroyedValue,
16850 EvalInfo::EvaluatingDeclKind::Dtor);
16851 Info.InConstantContext = IsConstantDestruction;
16852
16853 LValue LVal;
16854 LVal.set(Base);
16855
16856 if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
16857 EStatus.HasSideEffects)
16858 return false;
16859
16860 if (!Info.discardCleanups())
16861 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16862
16863 return true;
16864}
16865
16867 ConstantExprKind Kind) const {
16868 assert(!isValueDependent() &&
16869 "Expression evaluator can't be called on a dependent expression.");
16870 bool IsConst;
16871 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst) && Result.Val.hasValue())
16872 return true;
16873
16874 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateAsConstantExpr");
16875 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
16876 EvalInfo Info(Ctx, Result, EM);
16877 Info.InConstantContext = true;
16878
16879 if (Info.EnableNewConstInterp) {
16880 if (!Info.Ctx.getInterpContext().evaluate(Info, this, Result.Val, Kind))
16881 return false;
16882 return CheckConstantExpression(Info, getExprLoc(),
16883 getStorageType(Ctx, this), Result.Val, Kind);
16884 }
16885
16886 // The type of the object we're initializing is 'const T' for a class NTTP.
16887 QualType T = getType();
16888 if (Kind == ConstantExprKind::ClassTemplateArgument)
16889 T.addConst();
16890
16891 // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
16892 // represent the result of the evaluation. CheckConstantExpression ensures
16893 // this doesn't escape.
16894 MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
16895 APValue::LValueBase Base(&BaseMTE);
16896 Info.setEvaluatingDecl(Base, Result.Val);
16897
16898 if (Info.EnableNewConstInterp) {
16899 if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, this, Result.Val))
16900 return false;
16901 } else {
16902 LValue LVal;
16903 LVal.set(Base);
16904 // C++23 [intro.execution]/p5
16905 // A full-expression is [...] a constant-expression
16906 // So we need to make sure temporary objects are destroyed after having
16907 // evaluating the expression (per C++23 [class.temporary]/p4).
16908 FullExpressionRAII Scope(Info);
16909 if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
16910 Result.HasSideEffects || !Scope.destroy())
16911 return false;
16912
16913 if (!Info.discardCleanups())
16914 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16915 }
16916
16917 if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
16918 Result.Val, Kind))
16919 return false;
16920 if (!CheckMemoryLeaks(Info))
16921 return false;
16922
16923 // If this is a class template argument, it's required to have constant
16924 // destruction too.
16925 if (Kind == ConstantExprKind::ClassTemplateArgument &&
16926 (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
16927 true) ||
16928 Result.HasSideEffects)) {
16929 // FIXME: Prefix a note to indicate that the problem is lack of constant
16930 // destruction.
16931 return false;
16932 }
16933
16934 return true;
16935}
16936
16938 const VarDecl *VD,
16940 bool IsConstantInitialization) const {
16941 assert(!isValueDependent() &&
16942 "Expression evaluator can't be called on a dependent expression.");
16943
16944 llvm::TimeTraceScope TimeScope("EvaluateAsInitializer", [&] {
16945 std::string Name;
16946 llvm::raw_string_ostream OS(Name);
16947 VD->printQualifiedName(OS);
16948 return Name;
16949 });
16950
16951 Expr::EvalStatus EStatus;
16952 EStatus.Diag = &Notes;
16953
16954 EvalInfo Info(Ctx, EStatus,
16955 (IsConstantInitialization &&
16956 (Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23))
16957 ? EvalInfo::EM_ConstantExpression
16958 : EvalInfo::EM_ConstantFold);
16959 Info.setEvaluatingDecl(VD, Value);
16960 Info.InConstantContext = IsConstantInitialization;
16961
16962 SourceLocation DeclLoc = VD->getLocation();
16963 QualType DeclTy = VD->getType();
16964
16965 if (Info.EnableNewConstInterp) {
16966 auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
16967 if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
16968 return false;
16969
16970 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
16971 ConstantExprKind::Normal);
16972 } else {
16973 LValue LVal;
16974 LVal.set(VD);
16975
16976 {
16977 // C++23 [intro.execution]/p5
16978 // A full-expression is ... an init-declarator ([dcl.decl]) or a
16979 // mem-initializer.
16980 // So we need to make sure temporary objects are destroyed after having
16981 // evaluated the expression (per C++23 [class.temporary]/p4).
16982 //
16983 // FIXME: Otherwise this may break test/Modules/pr68702.cpp because the
16984 // serialization code calls ParmVarDecl::getDefaultArg() which strips the
16985 // outermost FullExpr, such as ExprWithCleanups.
16986 FullExpressionRAII Scope(Info);
16987 if (!EvaluateInPlace(Value, Info, LVal, this,
16988 /*AllowNonLiteralTypes=*/true) ||
16989 EStatus.HasSideEffects)
16990 return false;
16991 }
16992
16993 // At this point, any lifetime-extended temporaries are completely
16994 // initialized.
16995 Info.performLifetimeExtension();
16996
16997 if (!Info.discardCleanups())
16998 llvm_unreachable("Unhandled cleanup; missing full expression marker?");
16999 }
17000
17001 return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
17002 ConstantExprKind::Normal) &&
17003 CheckMemoryLeaks(Info);
17004}
17005
17008 Expr::EvalStatus EStatus;
17009 EStatus.Diag = &Notes;
17010
17011 // Only treat the destruction as constant destruction if we formally have
17012 // constant initialization (or are usable in a constant expression).
17013 bool IsConstantDestruction = hasConstantInitialization();
17014
17015 // Make a copy of the value for the destructor to mutate, if we know it.
17016 // Otherwise, treat the value as default-initialized; if the destructor works
17017 // anyway, then the destruction is constant (and must be essentially empty).
17018 APValue DestroyedValue;
17019 if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
17020 DestroyedValue = *getEvaluatedValue();
17021 else if (!handleDefaultInitValue(getType(), DestroyedValue))
17022 return false;
17023
17024 if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
17025 getType(), getLocation(), EStatus,
17026 IsConstantDestruction) ||
17027 EStatus.HasSideEffects)
17028 return false;
17029
17030 ensureEvaluatedStmt()->HasConstantDestruction = true;
17031 return true;
17032}
17033
17034/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
17035/// constant folded, but discard the result.
17037 assert(!isValueDependent() &&
17038 "Expression evaluator can't be called on a dependent expression.");
17039
17040 EvalResult Result;
17041 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
17042 !hasUnacceptableSideEffect(Result, SEK);
17043}
17044
17047 assert(!isValueDependent() &&
17048 "Expression evaluator can't be called on a dependent expression.");
17049
17050 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstInt");
17051 EvalResult EVResult;
17052 EVResult.Diag = Diag;
17053 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17054 Info.InConstantContext = true;
17055
17056 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
17057 (void)Result;
17058 assert(Result && "Could not evaluate expression");
17059 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17060
17061 return EVResult.Val.getInt();
17062}
17063
17066 assert(!isValueDependent() &&
17067 "Expression evaluator can't be called on a dependent expression.");
17068
17069 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateKnownConstIntCheckOverflow");
17070 EvalResult EVResult;
17071 EVResult.Diag = Diag;
17072 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17073 Info.InConstantContext = true;
17074 Info.CheckingForUndefinedBehavior = true;
17075
17076 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
17077 (void)Result;
17078 assert(Result && "Could not evaluate expression");
17079 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
17080
17081 return EVResult.Val.getInt();
17082}
17083
17085 assert(!isValueDependent() &&
17086 "Expression evaluator can't be called on a dependent expression.");
17087
17088 ExprTimeTraceScope TimeScope(this, Ctx, "EvaluateForOverflow");
17089 bool IsConst;
17090 EvalResult EVResult;
17091 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
17092 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
17093 Info.CheckingForUndefinedBehavior = true;
17094 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
17095 }
17096}
17097
17099 assert(Val.isLValue());
17100 return IsGlobalLValue(Val.getLValueBase());
17101}
17102
17103/// isIntegerConstantExpr - this recursive routine will test if an expression is
17104/// an integer constant expression.
17105
17106/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
17107/// comma, etc
17108
17109// CheckICE - This function does the fundamental ICE checking: the returned
17110// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
17111// and a (possibly null) SourceLocation indicating the location of the problem.
17112//
17113// Note that to reduce code duplication, this helper does no evaluation
17114// itself; the caller checks whether the expression is evaluatable, and
17115// in the rare cases where CheckICE actually cares about the evaluated
17116// value, it calls into Evaluate.
17117
17118namespace {
17119
17120enum ICEKind {
17121 /// This expression is an ICE.
17122 IK_ICE,
17123 /// This expression is not an ICE, but if it isn't evaluated, it's
17124 /// a legal subexpression for an ICE. This return value is used to handle
17125 /// the comma operator in C99 mode, and non-constant subexpressions.
17126 IK_ICEIfUnevaluated,
17127 /// This expression is not an ICE, and is not a legal subexpression for one.
17128 IK_NotICE
17129};
17130
17131struct ICEDiag {
17132 ICEKind Kind;
17134
17135 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
17136};
17137
17138}
17139
17140static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
17141
17142static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
17143
17144static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
17145 Expr::EvalResult EVResult;
17146 Expr::EvalStatus Status;
17147 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17148
17149 Info.InConstantContext = true;
17150 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
17151 !EVResult.Val.isInt())
17152 return ICEDiag(IK_NotICE, E->getBeginLoc());
17153
17154 return NoDiag();
17155}
17156
17157static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
17158 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
17160 return ICEDiag(IK_NotICE, E->getBeginLoc());
17161
17162 switch (E->getStmtClass()) {
17163#define ABSTRACT_STMT(Node)
17164#define STMT(Node, Base) case Expr::Node##Class:
17165#define EXPR(Node, Base)
17166#include "clang/AST/StmtNodes.inc"
17167 case Expr::PredefinedExprClass:
17168 case Expr::FloatingLiteralClass:
17169 case Expr::ImaginaryLiteralClass:
17170 case Expr::StringLiteralClass:
17171 case Expr::ArraySubscriptExprClass:
17172 case Expr::MatrixSubscriptExprClass:
17173 case Expr::ArraySectionExprClass:
17174 case Expr::OMPArrayShapingExprClass:
17175 case Expr::OMPIteratorExprClass:
17176 case Expr::MemberExprClass:
17177 case Expr::CompoundAssignOperatorClass:
17178 case Expr::CompoundLiteralExprClass:
17179 case Expr::ExtVectorElementExprClass:
17180 case Expr::DesignatedInitExprClass:
17181 case Expr::ArrayInitLoopExprClass:
17182 case Expr::ArrayInitIndexExprClass:
17183 case Expr::NoInitExprClass:
17184 case Expr::DesignatedInitUpdateExprClass:
17185 case Expr::ImplicitValueInitExprClass:
17186 case Expr::ParenListExprClass:
17187 case Expr::VAArgExprClass:
17188 case Expr::AddrLabelExprClass:
17189 case Expr::StmtExprClass:
17190 case Expr::CXXMemberCallExprClass:
17191 case Expr::CUDAKernelCallExprClass:
17192 case Expr::CXXAddrspaceCastExprClass:
17193 case Expr::CXXDynamicCastExprClass:
17194 case Expr::CXXTypeidExprClass:
17195 case Expr::CXXUuidofExprClass:
17196 case Expr::MSPropertyRefExprClass:
17197 case Expr::MSPropertySubscriptExprClass:
17198 case Expr::CXXNullPtrLiteralExprClass:
17199 case Expr::UserDefinedLiteralClass:
17200 case Expr::CXXThisExprClass:
17201 case Expr::CXXThrowExprClass:
17202 case Expr::CXXNewExprClass:
17203 case Expr::CXXDeleteExprClass:
17204 case Expr::CXXPseudoDestructorExprClass:
17205 case Expr::UnresolvedLookupExprClass:
17206 case Expr::TypoExprClass:
17207 case Expr::RecoveryExprClass:
17208 case Expr::DependentScopeDeclRefExprClass:
17209 case Expr::CXXConstructExprClass:
17210 case Expr::CXXInheritedCtorInitExprClass:
17211 case Expr::CXXStdInitializerListExprClass:
17212 case Expr::CXXBindTemporaryExprClass:
17213 case Expr::ExprWithCleanupsClass:
17214 case Expr::CXXTemporaryObjectExprClass:
17215 case Expr::CXXUnresolvedConstructExprClass:
17216 case Expr::CXXDependentScopeMemberExprClass:
17217 case Expr::UnresolvedMemberExprClass:
17218 case Expr::ObjCStringLiteralClass:
17219 case Expr::ObjCBoxedExprClass:
17220 case Expr::ObjCArrayLiteralClass:
17221 case Expr::ObjCDictionaryLiteralClass:
17222 case Expr::ObjCEncodeExprClass:
17223 case Expr::ObjCMessageExprClass:
17224 case Expr::ObjCSelectorExprClass:
17225 case Expr::ObjCProtocolExprClass:
17226 case Expr::ObjCIvarRefExprClass:
17227 case Expr::ObjCPropertyRefExprClass:
17228 case Expr::ObjCSubscriptRefExprClass:
17229 case Expr::ObjCIsaExprClass:
17230 case Expr::ObjCAvailabilityCheckExprClass:
17231 case Expr::ShuffleVectorExprClass:
17232 case Expr::ConvertVectorExprClass:
17233 case Expr::BlockExprClass:
17234 case Expr::NoStmtClass:
17235 case Expr::OpaqueValueExprClass:
17236 case Expr::PackExpansionExprClass:
17237 case Expr::SubstNonTypeTemplateParmPackExprClass:
17238 case Expr::FunctionParmPackExprClass:
17239 case Expr::AsTypeExprClass:
17240 case Expr::ObjCIndirectCopyRestoreExprClass:
17241 case Expr::MaterializeTemporaryExprClass:
17242 case Expr::PseudoObjectExprClass:
17243 case Expr::AtomicExprClass:
17244 case Expr::LambdaExprClass:
17245 case Expr::CXXFoldExprClass:
17246 case Expr::CoawaitExprClass:
17247 case Expr::DependentCoawaitExprClass:
17248 case Expr::CoyieldExprClass:
17249 case Expr::SYCLUniqueStableNameExprClass:
17250 case Expr::CXXParenListInitExprClass:
17251 case Expr::HLSLOutArgExprClass:
17252 return ICEDiag(IK_NotICE, E->getBeginLoc());
17253
17254 case Expr::InitListExprClass: {
17255 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
17256 // form "T x = { a };" is equivalent to "T x = a;".
17257 // Unless we're initializing a reference, T is a scalar as it is known to be
17258 // of integral or enumeration type.
17259 if (E->isPRValue())
17260 if (cast<InitListExpr>(E)->getNumInits() == 1)
17261 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
17262 return ICEDiag(IK_NotICE, E->getBeginLoc());
17263 }
17264
17265 case Expr::SizeOfPackExprClass:
17266 case Expr::GNUNullExprClass:
17267 case Expr::SourceLocExprClass:
17268 case Expr::EmbedExprClass:
17269 case Expr::OpenACCAsteriskSizeExprClass:
17270 return NoDiag();
17271
17272 case Expr::PackIndexingExprClass:
17273 return CheckICE(cast<PackIndexingExpr>(E)->getSelectedExpr(), Ctx);
17274
17275 case Expr::SubstNonTypeTemplateParmExprClass:
17276 return
17277 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
17278
17279 case Expr::ConstantExprClass:
17280 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
17281
17282 case Expr::ParenExprClass:
17283 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
17284 case Expr::GenericSelectionExprClass:
17285 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
17286 case Expr::IntegerLiteralClass:
17287 case Expr::FixedPointLiteralClass:
17288 case Expr::CharacterLiteralClass:
17289 case Expr::ObjCBoolLiteralExprClass:
17290 case Expr::CXXBoolLiteralExprClass:
17291 case Expr::CXXScalarValueInitExprClass:
17292 case Expr::TypeTraitExprClass:
17293 case Expr::ConceptSpecializationExprClass:
17294 case Expr::RequiresExprClass:
17295 case Expr::ArrayTypeTraitExprClass:
17296 case Expr::ExpressionTraitExprClass:
17297 case Expr::CXXNoexceptExprClass:
17298 return NoDiag();
17299 case Expr::CallExprClass:
17300 case Expr::CXXOperatorCallExprClass: {
17301 // C99 6.6/3 allows function calls within unevaluated subexpressions of
17302 // constant expressions, but they can never be ICEs because an ICE cannot
17303 // contain an operand of (pointer to) function type.
17304 const CallExpr *CE = cast<CallExpr>(E);
17305 if (CE->getBuiltinCallee())
17306 return CheckEvalInICE(E, Ctx);
17307 return ICEDiag(IK_NotICE, E->getBeginLoc());
17308 }
17309 case Expr::CXXRewrittenBinaryOperatorClass:
17310 return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
17311 Ctx);
17312 case Expr::DeclRefExprClass: {
17313 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
17314 if (isa<EnumConstantDecl>(D))
17315 return NoDiag();
17316
17317 // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
17318 // integer variables in constant expressions:
17319 //
17320 // C++ 7.1.5.1p2
17321 // A variable of non-volatile const-qualified integral or enumeration
17322 // type initialized by an ICE can be used in ICEs.
17323 //
17324 // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
17325 // that mode, use of reference variables should not be allowed.
17326 const VarDecl *VD = dyn_cast<VarDecl>(D);
17327 if (VD && VD->isUsableInConstantExpressions(Ctx) &&
17328 !VD->getType()->isReferenceType())
17329 return NoDiag();
17330
17331 return ICEDiag(IK_NotICE, E->getBeginLoc());
17332 }
17333 case Expr::UnaryOperatorClass: {
17334 const UnaryOperator *Exp = cast<UnaryOperator>(E);
17335 switch (Exp->getOpcode()) {
17336 case UO_PostInc:
17337 case UO_PostDec:
17338 case UO_PreInc:
17339 case UO_PreDec:
17340 case UO_AddrOf:
17341 case UO_Deref:
17342 case UO_Coawait:
17343 // C99 6.6/3 allows increment and decrement within unevaluated
17344 // subexpressions of constant expressions, but they can never be ICEs
17345 // because an ICE cannot contain an lvalue operand.
17346 return ICEDiag(IK_NotICE, E->getBeginLoc());
17347 case UO_Extension:
17348 case UO_LNot:
17349 case UO_Plus:
17350 case UO_Minus:
17351 case UO_Not:
17352 case UO_Real:
17353 case UO_Imag:
17354 return CheckICE(Exp->getSubExpr(), Ctx);
17355 }
17356 llvm_unreachable("invalid unary operator class");
17357 }
17358 case Expr::OffsetOfExprClass: {
17359 // Note that per C99, offsetof must be an ICE. And AFAIK, using
17360 // EvaluateAsRValue matches the proposed gcc behavior for cases like
17361 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
17362 // compliance: we should warn earlier for offsetof expressions with
17363 // array subscripts that aren't ICEs, and if the array subscripts
17364 // are ICEs, the value of the offsetof must be an integer constant.
17365 return CheckEvalInICE(E, Ctx);
17366 }
17367 case Expr::UnaryExprOrTypeTraitExprClass: {
17368 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
17369 if ((Exp->getKind() == UETT_SizeOf) &&
17371 return ICEDiag(IK_NotICE, E->getBeginLoc());
17372 return NoDiag();
17373 }
17374 case Expr::BinaryOperatorClass: {
17375 const BinaryOperator *Exp = cast<BinaryOperator>(E);
17376 switch (Exp->getOpcode()) {
17377 case BO_PtrMemD:
17378 case BO_PtrMemI:
17379 case BO_Assign:
17380 case BO_MulAssign:
17381 case BO_DivAssign:
17382 case BO_RemAssign:
17383 case BO_AddAssign:
17384 case BO_SubAssign:
17385 case BO_ShlAssign:
17386 case BO_ShrAssign:
17387 case BO_AndAssign:
17388 case BO_XorAssign:
17389 case BO_OrAssign:
17390 // C99 6.6/3 allows assignments within unevaluated subexpressions of
17391 // constant expressions, but they can never be ICEs because an ICE cannot
17392 // contain an lvalue operand.
17393 return ICEDiag(IK_NotICE, E->getBeginLoc());
17394
17395 case BO_Mul:
17396 case BO_Div:
17397 case BO_Rem:
17398 case BO_Add:
17399 case BO_Sub:
17400 case BO_Shl:
17401 case BO_Shr:
17402 case BO_LT:
17403 case BO_GT:
17404 case BO_LE:
17405 case BO_GE:
17406 case BO_EQ:
17407 case BO_NE:
17408 case BO_And:
17409 case BO_Xor:
17410 case BO_Or:
17411 case BO_Comma:
17412 case BO_Cmp: {
17413 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17414 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17415 if (Exp->getOpcode() == BO_Div ||
17416 Exp->getOpcode() == BO_Rem) {
17417 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
17418 // we don't evaluate one.
17419 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
17420 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
17421 if (REval == 0)
17422 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17423 if (REval.isSigned() && REval.isAllOnes()) {
17424 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
17425 if (LEval.isMinSignedValue())
17426 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17427 }
17428 }
17429 }
17430 if (Exp->getOpcode() == BO_Comma) {
17431 if (Ctx.getLangOpts().C99) {
17432 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
17433 // if it isn't evaluated.
17434 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
17435 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
17436 } else {
17437 // In both C89 and C++, commas in ICEs are illegal.
17438 return ICEDiag(IK_NotICE, E->getBeginLoc());
17439 }
17440 }
17441 return Worst(LHSResult, RHSResult);
17442 }
17443 case BO_LAnd:
17444 case BO_LOr: {
17445 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
17446 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
17447 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
17448 // Rare case where the RHS has a comma "side-effect"; we need
17449 // to actually check the condition to see whether the side
17450 // with the comma is evaluated.
17451 if ((Exp->getOpcode() == BO_LAnd) !=
17452 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
17453 return RHSResult;
17454 return NoDiag();
17455 }
17456
17457 return Worst(LHSResult, RHSResult);
17458 }
17459 }
17460 llvm_unreachable("invalid binary operator kind");
17461 }
17462 case Expr::ImplicitCastExprClass:
17463 case Expr::CStyleCastExprClass:
17464 case Expr::CXXFunctionalCastExprClass:
17465 case Expr::CXXStaticCastExprClass:
17466 case Expr::CXXReinterpretCastExprClass:
17467 case Expr::CXXConstCastExprClass:
17468 case Expr::ObjCBridgedCastExprClass: {
17469 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
17470 if (isa<ExplicitCastExpr>(E)) {
17471 if (const FloatingLiteral *FL
17472 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
17473 unsigned DestWidth = Ctx.getIntWidth(E->getType());
17474 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
17475 APSInt IgnoredVal(DestWidth, !DestSigned);
17476 bool Ignored;
17477 // If the value does not fit in the destination type, the behavior is
17478 // undefined, so we are not required to treat it as a constant
17479 // expression.
17480 if (FL->getValue().convertToInteger(IgnoredVal,
17481 llvm::APFloat::rmTowardZero,
17482 &Ignored) & APFloat::opInvalidOp)
17483 return ICEDiag(IK_NotICE, E->getBeginLoc());
17484 return NoDiag();
17485 }
17486 }
17487 switch (cast<CastExpr>(E)->getCastKind()) {
17488 case CK_LValueToRValue:
17489 case CK_AtomicToNonAtomic:
17490 case CK_NonAtomicToAtomic:
17491 case CK_NoOp:
17492 case CK_IntegralToBoolean:
17493 case CK_IntegralCast:
17494 return CheckICE(SubExpr, Ctx);
17495 default:
17496 return ICEDiag(IK_NotICE, E->getBeginLoc());
17497 }
17498 }
17499 case Expr::BinaryConditionalOperatorClass: {
17500 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
17501 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
17502 if (CommonResult.Kind == IK_NotICE) return CommonResult;
17503 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17504 if (FalseResult.Kind == IK_NotICE) return FalseResult;
17505 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
17506 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
17507 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
17508 return FalseResult;
17509 }
17510 case Expr::ConditionalOperatorClass: {
17511 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
17512 // If the condition (ignoring parens) is a __builtin_constant_p call,
17513 // then only the true side is actually considered in an integer constant
17514 // expression, and it is fully evaluated. This is an important GNU
17515 // extension. See GCC PR38377 for discussion.
17516 if (const CallExpr *CallCE
17517 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
17518 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
17519 return CheckEvalInICE(E, Ctx);
17520 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
17521 if (CondResult.Kind == IK_NotICE)
17522 return CondResult;
17523
17524 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
17525 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
17526
17527 if (TrueResult.Kind == IK_NotICE)
17528 return TrueResult;
17529 if (FalseResult.Kind == IK_NotICE)
17530 return FalseResult;
17531 if (CondResult.Kind == IK_ICEIfUnevaluated)
17532 return CondResult;
17533 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
17534 return NoDiag();
17535 // Rare case where the diagnostics depend on which side is evaluated
17536 // Note that if we get here, CondResult is 0, and at least one of
17537 // TrueResult and FalseResult is non-zero.
17538 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
17539 return FalseResult;
17540 return TrueResult;
17541 }
17542 case Expr::CXXDefaultArgExprClass:
17543 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
17544 case Expr::CXXDefaultInitExprClass:
17545 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
17546 case Expr::ChooseExprClass: {
17547 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
17548 }
17549 case Expr::BuiltinBitCastExprClass: {
17550 if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
17551 return ICEDiag(IK_NotICE, E->getBeginLoc());
17552 return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
17553 }
17554 }
17555
17556 llvm_unreachable("Invalid StmtClass!");
17557}
17558
17559/// Evaluate an expression as a C++11 integral constant expression.
17561 const Expr *E,
17562 llvm::APSInt *Value,
17565 if (Loc) *Loc = E->getExprLoc();
17566 return false;
17567 }
17568
17569 APValue Result;
17570 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
17571 return false;
17572
17573 if (!Result.isInt()) {
17574 if (Loc) *Loc = E->getExprLoc();
17575 return false;
17576 }
17577
17578 if (Value) *Value = Result.getInt();
17579 return true;
17580}
17581
17583 SourceLocation *Loc) const {
17584 assert(!isValueDependent() &&
17585 "Expression evaluator can't be called on a dependent expression.");
17586
17587 ExprTimeTraceScope TimeScope(this, Ctx, "isIntegerConstantExpr");
17588
17589 if (Ctx.getLangOpts().CPlusPlus11)
17590 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
17591
17592 ICEDiag D = CheckICE(this, Ctx);
17593 if (D.Kind != IK_ICE) {
17594 if (Loc) *Loc = D.Loc;
17595 return false;
17596 }
17597 return true;
17598}
17599
17600std::optional<llvm::APSInt>
17602 if (isValueDependent()) {
17603 // Expression evaluator can't succeed on a dependent expression.
17604 return std::nullopt;
17605 }
17606
17607 APSInt Value;
17608
17609 if (Ctx.getLangOpts().CPlusPlus11) {
17611 return Value;
17612 return std::nullopt;
17613 }
17614
17615 if (!isIntegerConstantExpr(Ctx, Loc))
17616 return std::nullopt;
17617
17618 // The only possible side-effects here are due to UB discovered in the
17619 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
17620 // required to treat the expression as an ICE, so we produce the folded
17621 // value.
17623 Expr::EvalStatus Status;
17624 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
17625 Info.InConstantContext = true;
17626
17627 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
17628 llvm_unreachable("ICE cannot be evaluated!");
17629
17630 return ExprResult.Val.getInt();
17631}
17632
17634 assert(!isValueDependent() &&
17635 "Expression evaluator can't be called on a dependent expression.");
17636
17637 return CheckICE(this, Ctx).Kind == IK_ICE;
17638}
17639
17641 SourceLocation *Loc) const {
17642 assert(!isValueDependent() &&
17643 "Expression evaluator can't be called on a dependent expression.");
17644
17645 // We support this checking in C++98 mode in order to diagnose compatibility
17646 // issues.
17647 assert(Ctx.getLangOpts().CPlusPlus);
17648
17649 // Build evaluation settings.
17650 Expr::EvalStatus Status;
17652 Status.Diag = &Diags;
17653 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17654
17655 APValue Scratch;
17656 bool IsConstExpr =
17657 ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
17658 // FIXME: We don't produce a diagnostic for this, but the callers that
17659 // call us on arbitrary full-expressions should generally not care.
17660 Info.discardCleanups() && !Status.HasSideEffects;
17661
17662 if (!Diags.empty()) {
17663 IsConstExpr = false;
17664 if (Loc) *Loc = Diags[0].first;
17665 } else if (!IsConstExpr) {
17666 // FIXME: This shouldn't happen.
17667 if (Loc) *Loc = getExprLoc();
17668 }
17669
17670 return IsConstExpr;
17671}
17672
17674 const FunctionDecl *Callee,
17676 const Expr *This) const {
17677 assert(!isValueDependent() &&
17678 "Expression evaluator can't be called on a dependent expression.");
17679
17680 llvm::TimeTraceScope TimeScope("EvaluateWithSubstitution", [&] {
17681 std::string Name;
17682 llvm::raw_string_ostream OS(Name);
17683 Callee->getNameForDiagnostic(OS, Ctx.getPrintingPolicy(),
17684 /*Qualified=*/true);
17685 return Name;
17686 });
17687
17688 Expr::EvalStatus Status;
17689 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
17690 Info.InConstantContext = true;
17691
17692 LValue ThisVal;
17693 const LValue *ThisPtr = nullptr;
17694 if (This) {
17695#ifndef NDEBUG
17696 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
17697 assert(MD && "Don't provide `this` for non-methods.");
17698 assert(MD->isImplicitObjectMemberFunction() &&
17699 "Don't provide `this` for methods without an implicit object.");
17700#endif
17701 if (!This->isValueDependent() &&
17702 EvaluateObjectArgument(Info, This, ThisVal) &&
17703 !Info.EvalStatus.HasSideEffects)
17704 ThisPtr = &ThisVal;
17705
17706 // Ignore any side-effects from a failed evaluation. This is safe because
17707 // they can't interfere with any other argument evaluation.
17708 Info.EvalStatus.HasSideEffects = false;
17709 }
17710
17711 CallRef Call = Info.CurrentCall->createCall(Callee);
17712 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
17713 I != E; ++I) {
17714 unsigned Idx = I - Args.begin();
17715 if (Idx >= Callee->getNumParams())
17716 break;
17717 const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
17718 if ((*I)->isValueDependent() ||
17719 !EvaluateCallArg(PVD, *I, Call, Info) ||
17720 Info.EvalStatus.HasSideEffects) {
17721 // If evaluation fails, throw away the argument entirely.
17722 if (APValue *Slot = Info.getParamSlot(Call, PVD))
17723 *Slot = APValue();
17724 }
17725
17726 // Ignore any side-effects from a failed evaluation. This is safe because
17727 // they can't interfere with any other argument evaluation.
17728 Info.EvalStatus.HasSideEffects = false;
17729 }
17730
17731 // Parameter cleanups happen in the caller and are not part of this
17732 // evaluation.
17733 Info.discardCleanups();
17734 Info.EvalStatus.HasSideEffects = false;
17735
17736 // Build fake call to Callee.
17737 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, This,
17738 Call);
17739 // FIXME: Missing ExprWithCleanups in enable_if conditions?
17740 FullExpressionRAII Scope(Info);
17741 return Evaluate(Value, Info, this) && Scope.destroy() &&
17742 !Info.EvalStatus.HasSideEffects;
17743}
17744
17747 PartialDiagnosticAt> &Diags) {
17748 // FIXME: It would be useful to check constexpr function templates, but at the
17749 // moment the constant expression evaluator cannot cope with the non-rigorous
17750 // ASTs which we build for dependent expressions.
17751 if (FD->isDependentContext())
17752 return true;
17753
17754 llvm::TimeTraceScope TimeScope("isPotentialConstantExpr", [&] {
17755 std::string Name;
17756 llvm::raw_string_ostream OS(Name);
17758 /*Qualified=*/true);
17759 return Name;
17760 });
17761
17762 Expr::EvalStatus Status;
17763 Status.Diag = &Diags;
17764
17765 EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
17766 Info.InConstantContext = true;
17767 Info.CheckingPotentialConstantExpression = true;
17768
17769 // The constexpr VM attempts to compile all methods to bytecode here.
17770 if (Info.EnableNewConstInterp) {
17771 Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
17772 return Diags.empty();
17773 }
17774
17775 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
17776 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
17777
17778 // Fabricate an arbitrary expression on the stack and pretend that it
17779 // is a temporary being used as the 'this' pointer.
17780 LValue This;
17781 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
17782 This.set({&VIE, Info.CurrentCall->Index});
17783
17785
17786 APValue Scratch;
17787 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
17788 // Evaluate the call as a constant initializer, to allow the construction
17789 // of objects of non-literal types.
17790 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
17791 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
17792 } else {
17795 Loc, FD, (MD && MD->isImplicitObjectMemberFunction()) ? &This : nullptr,
17796 &VIE, Args, CallRef(), FD->getBody(), Info, Scratch,
17797 /*ResultSlot=*/nullptr);
17798 }
17799
17800 return Diags.empty();
17801}
17802
17804 const FunctionDecl *FD,
17806 PartialDiagnosticAt> &Diags) {
17807 assert(!E->isValueDependent() &&
17808 "Expression evaluator can't be called on a dependent expression.");
17809
17810 Expr::EvalStatus Status;
17811 Status.Diag = &Diags;
17812
17813 EvalInfo Info(FD->getASTContext(), Status,
17814 EvalInfo::EM_ConstantExpressionUnevaluated);
17815 Info.InConstantContext = true;
17816 Info.CheckingPotentialConstantExpression = true;
17817
17818 // Fabricate a call stack frame to give the arguments a plausible cover story.
17819 CallStackFrame Frame(Info, SourceLocation(), FD, /*This=*/nullptr,
17820 /*CallExpr=*/nullptr, CallRef());
17821
17822 APValue ResultScratch;
17823 Evaluate(ResultScratch, Info, E);
17824 return Diags.empty();
17825}
17826
17827bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
17828 unsigned Type) const {
17829 if (!getType()->isPointerType())
17830 return false;
17831
17832 Expr::EvalStatus Status;
17833 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17834 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
17835}
17836
17837static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
17838 EvalInfo &Info, std::string *StringResult) {
17839 if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
17840 return false;
17841
17842 LValue String;
17843
17844 if (!EvaluatePointer(E, String, Info))
17845 return false;
17846
17847 QualType CharTy = E->getType()->getPointeeType();
17848
17849 // Fast path: if it's a string literal, search the string value.
17850 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
17851 String.getLValueBase().dyn_cast<const Expr *>())) {
17852 StringRef Str = S->getBytes();
17853 int64_t Off = String.Offset.getQuantity();
17854 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
17855 S->getCharByteWidth() == 1 &&
17856 // FIXME: Add fast-path for wchar_t too.
17857 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
17858 Str = Str.substr(Off);
17859
17860 StringRef::size_type Pos = Str.find(0);
17861 if (Pos != StringRef::npos)
17862 Str = Str.substr(0, Pos);
17863
17864 Result = Str.size();
17865 if (StringResult)
17866 *StringResult = Str;
17867 return true;
17868 }
17869
17870 // Fall through to slow path.
17871 }
17872
17873 // Slow path: scan the bytes of the string looking for the terminating 0.
17874 for (uint64_t Strlen = 0; /**/; ++Strlen) {
17875 APValue Char;
17876 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
17877 !Char.isInt())
17878 return false;
17879 if (!Char.getInt()) {
17880 Result = Strlen;
17881 return true;
17882 } else if (StringResult)
17883 StringResult->push_back(Char.getInt().getExtValue());
17884 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
17885 return false;
17886 }
17887}
17888
17889std::optional<std::string> Expr::tryEvaluateString(ASTContext &Ctx) const {
17890 Expr::EvalStatus Status;
17891 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17892 uint64_t Result;
17893 std::string StringResult;
17894
17895 if (EvaluateBuiltinStrLen(this, Result, Info, &StringResult))
17896 return StringResult;
17897 return {};
17898}
17899
17900bool Expr::EvaluateCharRangeAsString(std::string &Result,
17901 const Expr *SizeExpression,
17902 const Expr *PtrExpression, ASTContext &Ctx,
17903 EvalResult &Status) const {
17904 LValue String;
17905 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
17906 Info.InConstantContext = true;
17907
17908 FullExpressionRAII Scope(Info);
17909 APSInt SizeValue;
17910 if (!::EvaluateInteger(SizeExpression, SizeValue, Info))
17911 return false;
17912
17913 uint64_t Size = SizeValue.getZExtValue();
17914
17915 if (!::EvaluatePointer(PtrExpression, String, Info))
17916 return false;
17917
17918 QualType CharTy = PtrExpression->getType()->getPointeeType();
17919 for (uint64_t I = 0; I < Size; ++I) {
17920 APValue Char;
17921 if (!handleLValueToRValueConversion(Info, PtrExpression, CharTy, String,
17922 Char))
17923 return false;
17924
17925 APSInt C = Char.getInt();
17926 Result.push_back(static_cast<char>(C.getExtValue()));
17927 if (!HandleLValueArrayAdjustment(Info, PtrExpression, String, CharTy, 1))
17928 return false;
17929 }
17930 if (!Scope.destroy())
17931 return false;
17932
17933 if (!CheckMemoryLeaks(Info))
17934 return false;
17935
17936 return true;
17937}
17938
17939bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
17940 Expr::EvalStatus Status;
17941 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
17942 return EvaluateBuiltinStrLen(this, Result, Info);
17943}
17944
17945namespace {
17946struct IsWithinLifetimeHandler {
17947 EvalInfo &Info;
17948 static constexpr AccessKinds AccessKind = AccessKinds::AK_IsWithinLifetime;
17949 using result_type = std::optional<bool>;
17950 std::optional<bool> failed() { return std::nullopt; }
17951 template <typename T>
17952 std::optional<bool> found(T &Subobj, QualType SubobjType) {
17953 return true;
17954 }
17955};
17956
17957std::optional<bool> EvaluateBuiltinIsWithinLifetime(IntExprEvaluator &IEE,
17958 const CallExpr *E) {
17959 EvalInfo &Info = IEE.Info;
17960 // Sometimes this is called during some sorts of constant folding / early
17961 // evaluation. These are meant for non-constant expressions and are not
17962 // necessary since this consteval builtin will never be evaluated at runtime.
17963 // Just fail to evaluate when not in a constant context.
17964 if (!Info.InConstantContext)
17965 return std::nullopt;
17966 assert(E->getBuiltinCallee() == Builtin::BI__builtin_is_within_lifetime);
17967 const Expr *Arg = E->getArg(0);
17968 if (Arg->isValueDependent())
17969 return std::nullopt;
17970 LValue Val;
17971 if (!EvaluatePointer(Arg, Val, Info))
17972 return std::nullopt;
17973
17974 if (Val.allowConstexprUnknown())
17975 return true;
17976
17977 auto Error = [&](int Diag) {
17978 bool CalledFromStd = false;
17979 const auto *Callee = Info.CurrentCall->getCallee();
17980 if (Callee && Callee->isInStdNamespace()) {
17981 const IdentifierInfo *Identifier = Callee->getIdentifier();
17982 CalledFromStd = Identifier && Identifier->isStr("is_within_lifetime");
17983 }
17984 Info.CCEDiag(CalledFromStd ? Info.CurrentCall->getCallRange().getBegin()
17985 : E->getExprLoc(),
17986 diag::err_invalid_is_within_lifetime)
17987 << (CalledFromStd ? "std::is_within_lifetime"
17988 : "__builtin_is_within_lifetime")
17989 << Diag;
17990 return std::nullopt;
17991 };
17992 // C++2c [meta.const.eval]p4:
17993 // During the evaluation of an expression E as a core constant expression, a
17994 // call to this function is ill-formed unless p points to an object that is
17995 // usable in constant expressions or whose complete object's lifetime began
17996 // within E.
17997
17998 // Make sure it points to an object
17999 // nullptr does not point to an object
18000 if (Val.isNullPointer() || Val.getLValueBase().isNull())
18001 return Error(0);
18002 QualType T = Val.getLValueBase().getType();
18003 assert(!T->isFunctionType() &&
18004 "Pointers to functions should have been typed as function pointers "
18005 "which would have been rejected earlier");
18006 assert(T->isObjectType());
18007 // Hypothetical array element is not an object
18008 if (Val.getLValueDesignator().isOnePastTheEnd())
18009 return Error(1);
18010 assert(Val.getLValueDesignator().isValidSubobject() &&
18011 "Unchecked case for valid subobject");
18012 // All other ill-formed values should have failed EvaluatePointer, so the
18013 // object should be a pointer to an object that is usable in a constant
18014 // expression or whose complete lifetime began within the expression
18015 CompleteObject CO =
18016 findCompleteObject(Info, E, AccessKinds::AK_IsWithinLifetime, Val, T);
18017 // The lifetime hasn't begun yet if we are still evaluating the
18018 // initializer ([basic.life]p(1.2))
18019 if (Info.EvaluatingDeclValue && CO.Value == Info.EvaluatingDeclValue)
18020 return Error(2);
18021
18022 if (!CO)
18023 return false;
18024 IsWithinLifetimeHandler handler{Info};
18025 return findSubobject(Info, E, CO, Val.getLValueDesignator(), handler);
18026}
18027} // namespace
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines enum values for all the target-independent builtin functions.
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, Address OriginalBaseAddress, llvm::Value *Addr)
const Decl * D
IndirectLocalPath & Path
enum clang::sema::@1727::IndirectLocalPathEntry::EntryKind Kind
Expr * E
llvm::APSInt APSInt
Definition: Compiler.cpp:23
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:1181
GCCTypeClass
Values returned by __builtin_classify_type, chosen to match the values produced by GCC's builtin.
static bool isRead(AccessKinds AK)
static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result, EvalInfo &Info, std::string *StringResult=nullptr)
static bool isValidIndeterminateAccess(AccessKinds AK)
Is this kind of axcess valid on an indeterminate object value?
static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result, EvalInfo &Info)
static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result, Expr::SideEffectsKind SEK)
static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK, const LValue &LVal, QualType LValType)
Find the complete object to which an LValue refers.
static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base, LValue &Result)
Attempts to evaluate the given LValueBase as the result of a call to a function with the alloc_size a...
static const CXXMethodDecl * HandleVirtualDispatch(EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found, llvm::SmallVectorImpl< QualType > &CovariantAdjustmentPath)
Perform virtual dispatch.
static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD)
static bool CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind, const FieldDecl *SubobjectDecl, CheckedTemporaries &CheckedTemps)
static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, bool Imag)
Update an lvalue to refer to a component of a complex number.
static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc, QualType Type, CharUnits &Size, SizeOfType SOT=SizeOfType::SizeOf)
Get the size of the given type in char units.
static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result, const ASTContext &Ctx, bool &IsConst)
static bool HandleConstructorCall(const Expr *E, const LValue &This, CallRef Call, const CXXConstructorDecl *Definition, EvalInfo &Info, APValue &Result)
Evaluate a constructor call.
static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info, const Stmt *Body, const SwitchCase *Case=nullptr)
Evaluate the body of a loop, and translate the result as appropriate.
static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc, const CXXConstructorDecl *CD, bool IsValueInitialization)
CheckTrivialDefaultConstructor - Check whether a constructor is a trivial default constructor.
static bool EvaluateVector(const Expr *E, APValue &Result, EvalInfo &Info)
static const ValueDecl * GetLValueBaseDecl(const LValue &LVal)
SizeOfType
static bool TryEvaluateBuiltinNaN(const ASTContext &Context, QualType ResultTy, const Expr *Arg, bool SNaN, llvm::APFloat &Result)
static const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize.
static bool isAnyAccess(AccessKinds AK)
static bool EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E, SuccessCB &&Success, AfterCB &&DoAfter)
static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E, const RecordDecl *RD, const LValue &This, APValue &Result)
Perform zero-initialization on an object of non-union class type.
static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info)
static bool CheckMemoryLeaks(EvalInfo &Info)
Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless "the allocated storage is dea...
static ICEDiag CheckEvalInICE(const Expr *E, const ASTContext &Ctx)
static bool HandleFunctionCall(SourceLocation CallLoc, const FunctionDecl *Callee, const LValue *This, const Expr *E, ArrayRef< const Expr * > Args, CallRef Call, const Stmt *Body, EvalInfo &Info, APValue &Result, const LValue *ResultSlot)
Evaluate a function call.
static bool isBaseClassPublic(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Determine whether Base, which is known to be a direct base class of Derived, is a public base class.
static bool hasVirtualDestructor(QualType T)
static bool HandleOverflow(EvalInfo &Info, const Expr *E, const T &SrcValue, QualType DestType)
static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value)
static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E, LValue &LVal, const IndirectFieldDecl *IFD)
Update LVal to refer to the given indirect field.
static ICEDiag Worst(ICEDiag A, ICEDiag B)
static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E, const VarDecl *VD, CallStackFrame *Frame, unsigned Version, APValue *&Result)
Try to evaluate the initializer for a variable declaration.
static bool handleDefaultInitValue(QualType T, APValue &Result)
Get the value to use for a default-initialized object of type T.
static bool HandleLValueVectorElement(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, uint64_t Size, uint64_t Idx)
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base)
static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const LValue &LVal, ConstantExprKind Kind, CheckedTemporaries &CheckedTemps)
Check that this reference or pointer core constant expression is a valid value for an address or refe...
static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E, const APSInt &LHS, const APSInt &RHS, unsigned BitWidth, Operation Op, APSInt &Result)
Perform the given integer operation, which is known to need at most BitWidth bits,...
static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info)
Evaluate an expression of record type as a temporary.
static bool EvaluateArray(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E, APValue &Value, const FieldDecl *FD)
static bool handleVectorShuffle(EvalInfo &Info, const ShuffleVectorExpr *E, QualType ElemType, APValue const &VecVal1, APValue const &VecVal2, unsigned EltNum, APValue &Result)
static bool handleVectorElementCast(EvalInfo &Info, const FPOptions FPO, const Expr *E, QualType SourceTy, QualType DestTy, APValue const &Original, APValue &Result)
static const ValueDecl * HandleMemberPointerAccess(EvalInfo &Info, QualType LVType, LValue &LV, const Expr *RHS, bool IncludeMember=true)
HandleMemberPointerAccess - Evaluate a member access operation and build an lvalue referring to the r...
static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E, LValue &Result)
HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on the provided lvalue,...
static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info)
static bool IsOpaqueConstantCall(const CallExpr *E)
Should this call expression be treated as forming an opaque constant?
static bool CheckMemberPointerConstantExpression(EvalInfo &Info, SourceLocation Loc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Member pointers are constant expressions unless they point to a non-virtual dllimport member function...
static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type, const LValue &LVal, APValue &RVal, bool WantObjectRepresentation=false)
Perform an lvalue-to-rvalue conversion on the given glvalue.
static bool refersToCompleteObject(const LValue &LVal)
Tests to see if the LValue has a user-specified designator (that isn't necessarily valid).
static bool AreElementsOfSameArray(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B)
Determine whether the given subobject designators refer to elements of the same array object.
static bool IsWeakLValue(const LValue &Value)
static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This, APValue &Result, const CXXConstructExpr *CCE, QualType AllocType)
static bool EvaluateRecord(const Expr *E, const LValue &This, APValue &Result, EvalInfo &Info)
static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, APValue &Val)
Perform an assignment of Val to LVal. Takes ownership of Val.
static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result, const RecordDecl *TruncatedType, unsigned TruncatedElements)
Cast an lvalue referring to a base subobject to a derived class, by truncating the lvalue's path to t...
static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E)
Evaluate an expression to see if it had side-effects, and discard its result.
static void addFlexibleArrayMemberInitSize(EvalInfo &Info, const QualType &T, const LValue &LV, CharUnits &Size)
If we're evaluating the object size of an instance of a struct that contains a flexible array member,...
static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E, QualType Type, LValue &Result)
static bool EvaluateArgs(ArrayRef< const Expr * > Args, CallRef Call, EvalInfo &Info, const FunctionDecl *Callee, bool RightToLeft=false)
Evaluate the arguments to a function call.
static QualType getSubobjectType(QualType ObjType, QualType SubobjType, bool IsMutable=false)
static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate an integer or fixed point expression into an APResult.
static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E, const FPOptions FPO, QualType SrcType, const APSInt &Value, QualType DestType, APFloat &Result)
static const CXXRecordDecl * getBaseClassType(SubobjectDesignator &Designator, unsigned PathLength)
static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result, const CXXRecordDecl *DerivedRD, const CXXRecordDecl *BaseRD)
Cast an lvalue referring to a derived class to a known base subobject.
static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *DerivedDecl, const CXXBaseSpecifier *Base)
static bool HandleConversionToBool(const APValue &Val, bool &Result)
CharUnits GetAlignOfExpr(const ASTContext &Ctx, const Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool isModification(AccessKinds AK)
static bool handleCompareOpForVector(const APValue &LHSValue, BinaryOperatorKind Opcode, const APValue &RHSValue, APInt &Result)
static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr)
static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object, LValue &This)
Build an lvalue for the object argument of a member function call.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E, const LValue *This=nullptr)
Check that this core constant expression is of literal type, and if not, produce an appropriate diagn...
static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx, const CallExpr *Call, llvm::APInt &Result)
Attempts to compute the number of bytes available at the pointer returned by a function with the allo...
static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info)
CheckEvaluationResultKind
static bool isZeroSized(const LValue &Value)
static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit, uint64_t Index)
Extract the value of a character from a string literal.
static bool modifySubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &NewVal)
Update the designated sub-object of an rvalue to the given value.
static CharUnits GetAlignOfType(const ASTContext &Ctx, QualType T, UnaryExprOrTypeTrait ExprKind)
static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info, APValue &Val, APSInt &Alignment)
static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E, LValue &LVal, QualType EltTy, APSInt Adjustment)
Update a pointer value to model pointer arithmetic.
static bool extractSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, APValue &Result, AccessKinds AK=AK_Read)
Extract the designated sub-object of an rvalue.
static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal, const FieldDecl *FD, const ASTRecordLayout *RL=nullptr)
Update LVal to refer to the given field, which must be a member of the type currently described by LV...
static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index, bool IsSub)
static bool IsDeclSourceLocationCurrent(const FunctionDecl *FD)
void HandleComplexComplexDiv(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param, const Expr *E, APValue &Result, bool CopyObjectRepresentation)
Perform a trivial copy from Param, which is the parameter of a copy or move constructor or assignment...
static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E, APFloat::opStatus St)
Check if the given evaluation result is allowed for constant evaluation.
static bool EvaluateBuiltinConstantPForLValue(const APValue &LV)
EvaluateBuiltinConstantPForLValue - Determine the result of __builtin_constant_p when applied to the ...
static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg)
EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to GCC as we can manage.
static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E, const LValue &This, const CXXMethodDecl *NamedMember)
Check that the pointee of the 'this' pointer in a member function call is either within its lifetime ...
static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value, ConstantExprKind Kind)
Check that this core constant expression value is a valid value for a constant expression.
static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result, EvalInfo &Info)
static std::optional< DynamicType > ComputeDynamicType(EvalInfo &Info, const Expr *E, LValue &This, AccessKinds AK)
Determine the dynamic type of an object.
static void expandArray(APValue &Array, unsigned Index)
static bool handleLogicalOpForVector(const APInt &LHSValue, BinaryOperatorKind Opcode, const APInt &RHSValue, APInt &Result)
static unsigned FindDesignatorMismatch(QualType ObjType, const SubobjectDesignator &A, const SubobjectDesignator &B, bool &WasArrayIndex)
Find the position where two subobject designators diverge, or equivalently the length of the common i...
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx, const LValue &LV)
Determine whether this is a pointer past the end of the complete object referred to by the lvalue.
static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx, const Expr *E, llvm::APSInt *Value, SourceLocation *Loc)
Evaluate an expression as a C++11 integral constant expression.
static unsigned getBaseIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *Base)
Get the base index of the given base class within an APValue representing the given derived class.
static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result, EvalInfo &Info)
Evaluate only a fixed point expression into an APResult.
void HandleComplexComplexMul(APFloat A, APFloat B, APFloat C, APFloat D, APFloat &ResR, APFloat &ResI)
static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type, EvalInfo &Info, uint64_t &Size)
Tries to evaluate the __builtin_object_size for E.
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result)
static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E, BinaryOperatorKind Opcode, APValue &LHSValue, const APValue &RHSValue)
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal)
Checks to see if the given LValue's Designator is at the end of the LValue's record layout.
static bool CheckArraySize(EvalInfo &Info, const ConstantArrayType *CAT, SourceLocation CallLoc={})
static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This, const Expr *E, bool AllowNonLiteralTypes=false)
EvaluateInPlace - Evaluate an expression in-place in an APValue.
static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E, APFloat &LHS, BinaryOperatorKind Opcode, const APFloat &RHS)
Perform the given binary floating-point operation, in-place, on LHS.
static std::optional< DynAlloc * > CheckDeleteKind(EvalInfo &Info, const Expr *E, const LValue &Pointer, DynAlloc::Kind DeallocKind)
Check that the given object is a suitable pointer to a heap allocation that still exists and is of th...
static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info, bool InvalidBaseOK=false)
Evaluate an expression as an lvalue.
static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg, CallRef Call, EvalInfo &Info, bool NonNull=false)
static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E, APValue &Result, ArrayRef< QualType > Path)
Perform the adjustment from a value returned by a virtual function to a value of the statically expec...
static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info, const SwitchStmt *SS)
Evaluate a switch statement.
static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S, APValue &Result, QualType AllocType=QualType())
static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result, EvalInfo &Info)
static bool handleIntIntBinOp(EvalInfo &Info, const BinaryOperator *E, const APSInt &LHS, BinaryOperatorKind Opcode, APSInt RHS, APSInt &Result)
Perform the given binary integer operation.
static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This, AccessKinds AK, bool Polymorphic)
Check that we can access the notional vptr of an object / determine its dynamic type.
static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E, QualType SrcType, const APFloat &Value, QualType DestType, APSInt &Result)
static bool getAlignmentArgument(const Expr *E, QualType ForType, EvalInfo &Info, APSInt &Alignment)
Evaluate the value of the alignment argument to __builtin_align_{up,down}, __builtin_is_aligned and _...
static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc, QualType Type, const APValue &Value)
Check that this evaluated value is fully-initialized and can be loaded by an lvalue-to-rvalue convers...
static SubobjectHandler::result_type findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj, const SubobjectDesignator &Sub, SubobjectHandler &handler)
Find the designated sub-object of an rvalue.
static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc, unsigned Type, const LValue &LVal, CharUnits &EndOffset)
Helper for tryEvaluateBuiltinObjectSize – Given an LValue, this will determine how many bytes exist f...
static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int, CharUnits &Result)
Converts the given APInt to CharUnits, assuming the APInt is unsigned.
GCCTypeClass EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts)
EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way as GCC.
static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info)
static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E, QualType DestType, QualType SrcType, const APSInt &Value)
static std::optional< APValue > handleVectorUnaryOperator(ASTContext &Ctx, QualType ResultTy, UnaryOperatorKind Op, APValue Elt)
static bool lifetimeStartedInEvaluation(EvalInfo &Info, APValue::LValueBase Base, bool MutableSubobject=false)
static bool isOneByteCharacterType(QualType T)
static bool HandleLambdaCapture(EvalInfo &Info, const Expr *E, LValue &Result, const CXXMethodDecl *MD, const FieldDecl *FD, bool LValueToRValueConversion)
Get an lvalue to a field of a lambda's closure type.
static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl, const Expr *Cond, bool &Result)
Evaluate a condition (either a variable declaration or an expression).
static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult, const ASTContext &Ctx, Expr::SideEffectsKind AllowSideEffects, EvalInfo &Info)
static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result)
EvaluateAsRValue - Try to evaluate this expression, performing an implicit lvalue-to-rvalue cast if i...
static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK, QualType T)
Diagnose an attempt to read from any unreadable field within the specified type, which might be a cla...
static ICEDiag CheckICE(const Expr *E, const ASTContext &Ctx)
static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc, const FunctionDecl *Declaration, const FunctionDecl *Definition, const Stmt *Body)
CheckConstexprFunction - Check that a function can be called in a constant expression.
static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base, APValue DestroyedValue, QualType Type, SourceLocation Loc, Expr::EvalStatus &EStatus, bool IsConstantDestruction)
static bool EvaluateDecl(EvalInfo &Info, const Decl *D)
static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info, const Stmt *S, const SwitchCase *SC=nullptr)
static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This, APValue &Result, const InitListExpr *ILE, QualType AllocType)
static bool HasSameBase(const LValue &A, const LValue &B)
static bool CheckLocalVariableDeclaration(EvalInfo &Info, const VarDecl *VD)
static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj, const CXXRecordDecl *Derived, const CXXRecordDecl *Base, const ASTRecordLayout *RL=nullptr)
static bool IsGlobalLValue(APValue::LValueBase B)
static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E)
Get rounding mode to use in evaluation of the specified expression.
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
static bool handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode, const APTy &RHSValue, APInt &Result)
static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E)
static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
static void negateAsSigned(APSInt &Int)
Negate an APSInt in place, converting it to a signed form if necessary, and preserving its value (by ...
static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal)
Attempts to detect a user writing into a piece of memory that's impossible to figure out the size of ...
static bool GetLValueBaseAsString(const EvalInfo &Info, const LValue &LVal, LValueBaseString &AsString)
static bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E)
static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info)
EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and produce either the intege...
static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E, LValue &Ptr)
Apply the given dynamic cast operation on the provided lvalue.
static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E, LValue &Result)
Perform a call to 'operator new' or to ‘__builtin_operator_new’.
static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E, QualType SrcType, QualType DestType, APFloat &Result)
static bool MaybeHandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr, const LValue &LHS)
Handle a builtin simple-assignment or a call to a trivial assignment operator whose left-hand side mi...
static bool isFormalAccess(AccessKinds AK)
Is this an access per the C++ definition?
static bool handleCompoundAssignment(EvalInfo &Info, const CompoundAssignOperator *E, const LValue &LVal, QualType LValType, QualType PromotedLValType, BinaryOperatorKind Opcode, const APValue &RVal)
Perform a compound assignment of LVal <op>= RVal.
static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal, QualType LValType, bool IsIncrement, APValue *Old)
Perform an increment or decrement on LVal.
static ICEDiag NoDiag()
static bool EvaluateVoid(const Expr *E, EvalInfo &Info)
static bool HandleDestruction(EvalInfo &Info, const Expr *E, const LValue &This, QualType ThisType)
Perform a destructor or pseudo-destructor call on the given object, which might in general not be a c...
static bool HandleDestructionImpl(EvalInfo &Info, SourceRange CallRange, const LValue &This, APValue &Value, QualType T)
static bool ArePotentiallyOverlappingStringLiterals(const EvalInfo &Info, const LValue &LHS, const LValue &RHS)
StringRef Identifier
Definition: Format.cpp:3061
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic which may not be emitted.
llvm::DenseMap< Stmt *, Stmt * > MapTy
Definition: ParentMap.cpp:21
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
SourceLocation Loc
Definition: SemaObjC.cpp:759
bool Indirect
Definition: SemaObjC.cpp:760
static QualType getPointeeType(const MemRegion *R)
Enumerates target-specific builtins in their own namespaces within namespace clang.
Defines the clang::TypeLoc interface and its subclasses.
__DEVICE__ long long abs(long long __n)
__device__ int
#define bool
Definition: amdgpuintrin.h:20
do v
Definition: arm_acle.h:91
QualType getType() const
Definition: APValue.cpp:63
QualType getDynamicAllocType() const
Definition: APValue.cpp:122
QualType getTypeInfoType() const
Definition: APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition: APValue.cpp:55
static LValueBase getDynamicAlloc(DynamicAllocLValue LV, QualType Type)
Definition: APValue.cpp:47
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:206
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:214
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
bool hasArrayFiller() const
Definition: APValue.h:583
const LValueBase getLValueBase() const
Definition: APValue.cpp:984
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:575
void swap(APValue &RHS)
Swaps the contents of this and the given APValue.
Definition: APValue.cpp:475
APSInt & getInt()
Definition: APValue.h:488
APValue & getStructField(unsigned i)
Definition: APValue.h:616
const FieldDecl * getUnionField() const
Definition: APValue.h:628
bool isVector() const
Definition: APValue.h:472
APSInt & getComplexIntImag()
Definition: APValue.h:526
bool isAbsent() const
Definition: APValue.h:462
bool isComplexInt() const
Definition: APValue.h:469
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition: APValue.h:203
ValueKind getKind() const
Definition: APValue.h:460
unsigned getArrayInitializedElts() const
Definition: APValue.h:594
static APValue IndeterminateValue()
Definition: APValue.h:431
bool isFloat() const
Definition: APValue.h:467
APFixedPoint & getFixedPoint()
Definition: APValue.h:510
bool hasValue() const
Definition: APValue.h:464
bool hasLValuePath() const
Definition: APValue.cpp:999
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1067
APValue & getUnionValue()
Definition: APValue.h:632
CharUnits & getLValueOffset()
Definition: APValue.cpp:994
void printPretty(raw_ostream &OS, const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:704
bool isComplexFloat() const
Definition: APValue.h:470
APValue & getVectorElt(unsigned I)
Definition: APValue.h:562
APValue & getArrayFiller()
Definition: APValue.h:586
unsigned getVectorLength() const
Definition: APValue.h:570
bool isLValue() const
Definition: APValue.h:471
void setUnion(const FieldDecl *Field, const APValue &Value)
Definition: APValue.cpp:1060
bool isIndeterminate() const
Definition: APValue.h:463
bool isInt() const
Definition: APValue.h:466
unsigned getArraySize() const
Definition: APValue.h:598
bool allowConstexprUnknown() const
Definition: APValue.h:317
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:957
bool isFixedPoint() const
Definition: APValue.h:468
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isStruct() const
Definition: APValue.h:474
APSInt & getComplexIntReal()
Definition: APValue.h:518
APFloat & getComplexFloatImag()
Definition: APValue.h:542
APFloat & getComplexFloatReal()
Definition: APValue.h:534
APFloat & getFloat()
Definition: APValue.h:502
APValue & getStructBase(unsigned i)
Definition: APValue.h:611
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
SourceManager & getSourceManager()
Definition: ASTContext.h:741
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getRecordType(const RecordDecl *Decl) const
uint64_t getTargetNullPointerValue(QualType QT) const
Get target-dependent integer value for null pointer which is used for constant folding.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2580
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
ComparisonCategories CompCategories
Types and expressions required to build C++2a three-way comparisons using operator<=>,...
Definition: ASTContext.h:2420
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2489
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const
Make an APSInt of the appropriate width and signedness for the given Value and integer Type.
Definition: ASTContext.h:3182
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2493
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
unsigned getFieldCount() const
getFieldCount - Get the number of fields in the layout.
Definition: RecordLayout.h:196
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
CharUnits getVBaseClassOffset(const CXXRecordDecl *VBase) const
getVBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:259
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4421
LabelDecl * getLabel() const
Definition: Expr.h:4444
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5805
Represents a loop initializing the elements of an array.
Definition: Expr.h:5752
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2853
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7766
Attr - This represents one attribute.
Definition: Attr.h:43
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condition evaluates to false; ...
Definition: Expr.h:4378
Expr * getCommon() const
getCommon - Return the common expression, written to the left of the condition.
Definition: Expr.h:4359
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
bool isComparisonOp() const
Definition: Expr.h:4010
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition: Expr.h:4056
bool isLogicalOp() const
Definition: Expr.h:4043
Expr * getRHS() const
Definition: Expr.h:3961
Opcode getOpcode() const
Definition: Expr.h:3954
A binding in a decomposition declaration.
Definition: DeclCXX.h:4130
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5298
This class is used for builtin types like 'int'.
Definition: Type.h:3034
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:194
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:249
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2884
CXXCtorInitializer *const * init_const_iterator
Iterates through the member/base initializer list.
Definition: DeclCXX.h:2638
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition: ExprCXX.h:478
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition: DeclCXX.cpp:2588
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition: DeclCXX.cpp:2595
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2696
bool isInstance() const
Definition: DeclCXX.h:2105
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2621
bool isStatic() const
Definition: DeclCXX.cpp:2319
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2599
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2732
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4126
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4960
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasMutableFields() const
Determine whether this class, or any of its class subobjects, contains a mutable field.
Definition: DeclCXX.h:1245
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition: DeclCXX.cpp:1641
base_class_iterator bases_end()
Definition: DeclCXX.h:629
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
base_class_range bases()
Definition: DeclCXX.h:620
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1119
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition: DeclCXX.cpp:1747
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
base_class_iterator bases_begin()
Definition: DeclCXX.h:627
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2081
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1113
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:635
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:523
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2182
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents the this expression in C++.
Definition: ExprCXX.h:1152
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1584
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Decl * getCalleeDecl()
Definition: Expr.h:3041
CaseStmt - Represent a case statement.
Definition: Stmt.h:1828
Expr * getLHS()
Definition: Stmt.h:1915
Expr * getRHS()
Definition: Stmt.h:1927
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3547
const CXXBaseSpecifier *const * path_const_iterator
Definition: Expr.h:3614
Expr * getSubExpr()
Definition: Expr.h:3597
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPowerOfTwo() const
isPowerOfTwo - Test whether the quantity is a power of two.
Definition: CharUnits.h:135
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition: CharUnits.h:207
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4641
const ComparisonCategoryInfo & getInfoForType(QualType Ty) const
Return the comparison category information as specified by getCategoryForType(Ty).
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
ComparisonCategoryResult makeWeakResult(ComparisonCategoryResult Res) const
Converts the specified result kind into the correct result kind for this category.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4171
QualType getComputationLHSType() const
Definition: Expr.h:4205
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
bool isFileScope() const
Definition: Expr.h:3504
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
bool body_empty() const
Definition: Stmt.h:1672
Stmt *const * const_body_iterator
Definition: Stmt.h:1700
body_iterator body_end()
Definition: Stmt.h:1693
body_range body()
Definition: Stmt.h:1691
body_iterator body_begin()
Definition: Stmt.h:1692
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition: Expr.h:4294
Expr * getCond() const
getCond - Return the expression representing the condition for the ?: operator.
Definition: Expr.h:4285
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition: Expr.h:4289
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:196
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
unsigned getSizeBitWidth() const
Return the bit width of the size type.
Definition: Type.h:3678
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:205
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:245
uint64_t getLimitedSize() const
Return the size zero-extended to uint64_t or UINT64_MAX if the value is larger than UINT64_MAX.
Definition: Type.h:3704
bool isZeroSize() const
Return true if the size is zero.
Definition: Type.h:3685
const Expr * getSizeExpr() const
Return a pointer to the size expression.
Definition: Type.h:3711
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4582
Represents the current source location and context used to determine the value of the source location...
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2384
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1519
decl_range decls()
Definition: Stmt.h:1567
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInStdNamespace() const
Definition: DeclBase.cpp:430
static void add(Kind k)
Definition: DeclBase.cpp:229
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:528
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
DeclContext * getDeclContext()
Definition: DeclBase.h:451
AccessSpecifier getAccess() const
Definition: DeclBase.h:510
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
A decomposition declaration.
Definition: DeclCXX.h:4189
Designator - A designator in a C99 designated initializer.
Definition: Designator.h:38
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2752
Stmt * getBody()
Definition: Stmt.h:2777
Expr * getCond()
Definition: Stmt.h:2770
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
static unsigned getMaxIndex()
Definition: APValue.h:85
Represents a reference to #emded data.
Definition: Expr.h:4916
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3291
Represents an enum.
Definition: Decl.h:3861
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4058
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4075
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4021
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition: Decl.cpp:5009
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6103
EnumDecl * getDecl() const
Definition: Type.h:6110
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3474
This represents one expression.
Definition: Expr.h:110
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:82
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
static bool isPotentialConstantExpr(const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExpr - Return true if this function's definition might be usable in a constant exp...
static bool isPotentialConstantExprUnevaluated(Expr *E, const FunctionDecl *FD, SmallVectorImpl< PartialDiagnosticAt > &Diags)
isPotentialConstantExprUnevaluated - Return true if this expression might be usable in a constant exp...
bool isGLValue() const
Definition: Expr.h:280
SideEffectsKind
Definition: Expr.h:667
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition: Expr.h:671
@ SE_AllowUndefinedBehavior
Allow UB that we can give a value, but not arbitrary unmodeled side effects.
Definition: Expr.h:669
bool EvaluateCharRangeAsString(std::string &Result, const Expr *SizeExpression, const Expr *PtrExpression, ASTContext &Ctx, EvalResult &Status) const
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3102
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Returns the set of floating point options that apply to this expression.
Definition: Expr.cpp:3893
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3097
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3093
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3594
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
std::optional< std::string > tryEvaluateString(ASTContext &Ctx) const
If the current Expr can be evaluated to a pointer to a null-terminated constant string,...
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3231
ConstantExprKind
Definition: Expr.h:748
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
QualType getType() const
Definition: Expr.h:142
bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const
isCXX98IntegralConstantExpr - Return true if this expression is an integral constant expression in C+...
bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This=nullptr) const
EvaluateWithSubstitution - Evaluate an expression as if from the context of a call to the given funct...
bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx, const VarDecl *VD, SmallVectorImpl< PartialDiagnosticAt > &Notes, bool IsConstantInitializer) const
EvaluateAsInitializer - Evaluate an expression as if it were the initializer of the given declaration...
void EvaluateForOverflow(const ASTContext &Ctx) const
bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result=nullptr, SourceLocation *Loc=nullptr) const
isCXX11ConstantExpr - Return true if this expression is a constant expression in C++11.
An expression trait intrinsic.
Definition: ExprCXX.h:2924
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6354
bool isFPConstrained() const
Definition: LangOptions.h:906
LangOptions::FPExceptionModeKind getExceptionMode() const
Definition: LangOptions.h:924
RoundingMode getRoundingMode() const
Definition: LangOptions.h:912
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3136
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4613
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.h:3118
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
FieldDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition: Decl.h:3275
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:101
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2808
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3243
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4075
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4063
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4199
ArrayRef< ParmVarDecl * >::const_iterator param_const_iterator
Definition: Decl.h:2658
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3383
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2313
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const override
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:3088
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4716
Represents a C11 generic selection.
Definition: Expr.h:5966
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2165
Stmt * getThen()
Definition: Stmt.h:2254
Stmt * getInit()
Definition: Stmt.h:2315
bool isNonNegatedConsteval() const
Definition: Stmt.h:2350
Expr * getCond()
Definition: Stmt.h:2242
Stmt * getElse()
Definition: Stmt.h:2263
bool isConsteval() const
Definition: Stmt.h:2345
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition: Stmt.cpp:990
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5841
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3335
ArrayRef< NamedDecl * > chain() const
Definition: Decl.h:3357
Describes an C or C++ initializer list.
Definition: Expr.h:5088
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:499
A global _GUID constant.
Definition: DeclCXX.h:4312
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4734
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1675
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2519
Expr * getIndexExpr(unsigned Idx)
Definition: Expr.h:2580
const OffsetOfNode & getComponent(unsigned Idx) const
Definition: Expr.h:2566
TypeSourceInfo * getTypeSourceInfo() const
Definition: Expr.h:2559
unsigned getNumComponents() const
Definition: Expr.h:2576
Helper class for OffsetOfExpr.
Definition: Expr.h:2413
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2471
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2477
@ Array
An index into an array.
Definition: Expr.h:2418
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2422
@ Field
A field.
Definition: Expr.h:2420
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2425
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2467
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2487
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
This expression type represents an asterisk in an OpenACC Size-Expr, used in the 'tile' and 'gang' cl...
Definition: Expr.h:2078
A partial diagnostic which we might know in advance that we are not going to emit.
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8020
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7936
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:1089
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
QualType getCanonicalType() const
Definition: Type.h:7988
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8030
void removeLocalVolatile()
Definition: Type.h:8052
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
void addVolatile()
Add the volatile type qualifier to this QualType.
Definition: Type.h:1159
void removeLocalConst()
Definition: Type.h:8044
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8009
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7982
Represents a struct/union/class.
Definition: Decl.h:4162
bool hasFlexibleArrayMember() const
Definition: Decl.h:4195
field_iterator field_end() const
Definition: Decl.h:4379
field_range fields() const
Definition: Decl.h:4376
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4214
bool field_empty() const
Definition: Decl.h:4384
field_iterator field_begin() const
Definition: Decl.cpp:5106
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
RecordDecl * getDecl() const
Definition: Type.h:6087
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4514
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4258
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4810
Encodes a location in the source.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1194
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
const SwitchCase * getNextSwitchCase() const
Definition: Stmt.h:1801
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2415
Expr * getCond()
Definition: Stmt.h:2478
Stmt * getBody()
Definition: Stmt.h:2490
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition: Stmt.cpp:1108
Stmt * getInit()
Definition: Stmt.h:2499
SwitchCase * getSwitchCaseList()
Definition: Stmt.h:2552
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:4762
bool isUnion() const
Definition: Decl.h:3784
virtual bool isNan2008() const
Returns true if NaN encoding is IEEE 754-2008.
Definition: TargetInfo.h:1257
A template argument list.
Definition: DeclTemplate.h:250
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:286
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
A template parameter object.
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:44
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2768
The base class of the type hierarchy.
Definition: Type.h:1828
bool isStructureType() const
Definition: Type.cpp:662
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isVoidType() const
Definition: Type.h:8515
bool isBooleanType() const
Definition: Type.h:8643
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2201
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8271
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:8814
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2251
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isConstantArrayType() const
Definition: Type.h:8267
bool isNothrowT() const
Definition: Type.cpp:3106
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2386
bool isArrayType() const
Definition: Type.h:8263
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8231
bool isPointerType() const
Definition: Type.h:8191
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8555
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8805
bool isReferenceType() const
Definition: Type.h:8209
bool isEnumeralType() const
Definition: Type.h:8295
bool isVariableArrayType() const
Definition: Type.h:8275
bool isChar8Type() const
Definition: Type.cpp:2139
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8630
bool isExtVectorBoolType() const
Definition: Type.h:8311
bool isMemberDataPointerType() const
Definition: Type.h:8256
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8484
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8299
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8568
const RecordType * getAsStructureType() const
Definition: Type.cpp:754
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8686
bool isMemberPointerType() const
Definition: Type.h:8245
bool isAtomicType() const
Definition: Type.h:8346
bool isComplexIntegerType() const
Definition: Type.cpp:716
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8791
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8187
bool isVectorType() const
Definition: Type.h:8303
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isFloatingType() const
Definition: Type.cpp:2283
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2230
bool isAnyPointerType() const
Definition: Type.h:8199
TypeClass getTypeClass() const
Definition: Type.h:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isNullPtrType() const
Definition: Type.h:8548
bool isRecordType() const
Definition: Type.h:8291
bool isUnionType() const
Definition: Type.cpp:704
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8677
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1920
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition: Expr.h:2691
UnaryExprOrTypeTrait getKind() const
Definition: Expr.h:2654
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
static bool isIncrementOp(Opcode Op)
Definition: Expr.h:2318
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4369
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5403
QualType getType() const
Definition: Value.cpp:234
bool hasValue() const
Definition: Value.h:135
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1513
bool hasInit() const
Definition: Decl.cpp:2387
bool hasICEInitializer(const ASTContext &Context) const
Determine whether the initializer of this variable is an integer constant expression.
Definition: Decl.cpp:2608
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2547
CharUnits getFlexibleArrayInitChars(const ASTContext &Ctx) const
If hasFlexibleArrayInit is true, compute the number of additional bytes necessary to store those elem...
Definition: Decl.cpp:2853
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition: Decl.cpp:2620
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2458
bool evaluateDestruction(SmallVectorImpl< PartialDiagnosticAt > &Notes) const
Evaluate the destruction of this variable to determine if it constitutes constant destruction.
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1159
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1128
const Expr * getInit() const
Definition: Decl.h:1319
APValue * getEvaluatedValue() const
Return the already-evaluated value of this variable's initializer, or NULL if the value is not yet kn...
Definition: Decl.cpp:2600
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1204
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2500
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1309
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
QualType getElementType() const
Definition: Type.h:4048
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2611
Expr * getCond()
Definition: Stmt.h:2663
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition: Stmt.cpp:1169
Stmt * getBody()
Definition: Stmt.h:2675
Base class for stack frames, shared between VM and walker.
Definition: Frame.h:25
Interface for the VM to interact with the AST walker's context.
Definition: State.h:57
Defines the clang::TargetInfo interface.
#define CHAR_BIT
Definition: limits.h:71
#define UINT_MAX
Definition: limits.h:64
bool computeOSLogBufferLayout(clang::ASTContext &Ctx, const clang::CallExpr *E, OSLogBufferLayout &layout)
Definition: OSLog.cpp:180
uint32_t Literal
Literals are represented as positive integers.
Definition: CNFFormula.h:35
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code, ArrayRef< tooling::Range > Ranges, StringRef FileName="<stdin>")
Clean up any erroneous/redundant code in the given Ranges in Code.
Definition: Format.cpp:3890
llvm::APFloat APFloat
Definition: Floating.h:23
llvm::APInt APInt
Definition: FixedPoint.h:19
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition: Interp.cpp:1276
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1157
llvm::FixedPointSemantics FixedPointSemantics
Definition: Interp.h:43
bool This(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2387
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:2350
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:2884
ASTEdit note(RangeSelector Anchor, TextGenerator Note)
Generates a single, no-op edit with the associated note anchored at the start location of the specifi...
The JSON file list parser is used to communicate input to InstallAPI.
@ NonNull
Values of this type can never be null.
BinaryOperatorKind
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
Definition: CallGraph.h:204
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ TSCS_unspecified
Definition: Specifiers.h:236
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition: State.h:41
@ CSK_ArrayToPointer
Definition: State.h:45
@ CSK_Derived
Definition: State.h:43
@ CSK_Base
Definition: State.h:42
@ CSK_Real
Definition: State.h:47
@ CSK_ArrayIndex
Definition: State.h:46
@ CSK_Imag
Definition: State.h:48
@ CSK_VectorElement
Definition: State.h:49
@ CSK_Field
Definition: State.h:44
@ SD_Static
Static storage duration.
Definition: Specifiers.h:331
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition: Specifiers.h:328
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition: State.h:26
@ AK_TypeId
Definition: State.h:34
@ AK_Construct
Definition: State.h:35
@ AK_Increment
Definition: State.h:30
@ AK_DynamicCast
Definition: State.h:33
@ AK_Read
Definition: State.h:27
@ AK_Assign
Definition: State.h:29
@ AK_IsWithinLifetime
Definition: State.h:37
@ AK_MemberCall
Definition: State.h:32
@ AK_ReadObjectRepresentation
Definition: State.h:28
@ AK_Destroy
Definition: State.h:36
@ AK_Decrement
Definition: State.h:31
UnaryOperatorKind
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
CastKind
CastKind - The kind of operation required for a conversion.
llvm::hash_code hash_value(const CustomizableOptional< T > &O)
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
const FunctionProtoType * T
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1278
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Success
Template argument deduction was successful.
@ None
The alignment was not explicit in code.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Other
Other implicit parameter.
@ AS_public
Definition: Specifiers.h:124
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition: Dominators.h:30
hash_code hash_value(const clang::tooling::dependencies::ModuleID &ID)
#define false
Definition: stdbool.h:26
unsigned PathLength
The corresponding path length in the lvalue.
const CXXRecordDecl * Type
The dynamic class type of the object.
std::string ObjCEncodeStorage
Represents an element in a path from a derived class to a base class.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition: Expr.h:606
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
static ObjectUnderConstruction getTombstoneKey()
DenseMapInfo< APValue::LValueBase > Base
static ObjectUnderConstruction getEmptyKey()
static unsigned getHashValue(const ObjectUnderConstruction &Object)
static bool isEqual(const ObjectUnderConstruction &LHS, const ObjectUnderConstruction &RHS)
#define ilogb(__x)
Definition: tgmath.h:851
#define scalbn(__x, __y)
Definition: tgmath.h:1165