1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr constant evaluator.
12 // Constant expression evaluation produces four main results:
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
19 // * An evaluated result, valid only if constant folding has not failed.
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
34 //===----------------------------------------------------------------------===//
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/OSLog.h"
43 #include "clang/AST/RecordLayout.h"
44 #include "clang/AST/StmtVisitor.h"
45 #include "clang/AST/TypeLoc.h"
46 #include "clang/Basic/Builtins.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "llvm/Support/SaveAndRestore.h"
49 #include "llvm/Support/raw_ostream.h"
53 #define DEBUG_TYPE "exprconstant"
55 using namespace clang;
59 static bool IsGlobalLValue(APValue::LValueBase B);
63 struct CallStackFrame;
66 static QualType getType(APValue::LValueBase B) {
67 if (!B) return QualType();
68 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
69 // FIXME: It's unclear where we're supposed to take the type from, and
70 // this actually matters for arrays of unknown bound. Eg:
72 // extern int arr[]; void f() { extern int arr[3]; };
73 // constexpr int *p = &arr[1]; // valid?
75 // For now, we take the array bound from the most recent declaration.
76 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78 QualType T = Redecl->getType();
79 if (!T->isIncompleteArrayType())
85 const Expr *Base = B.get<const Expr*>();
87 // For a materialized temporary, the type of the temporary we materialized
88 // may not be the type of the expression.
89 if (const MaterializeTemporaryExpr *MTE =
90 dyn_cast<MaterializeTemporaryExpr>(Base)) {
91 SmallVector<const Expr *, 2> CommaLHSs;
92 SmallVector<SubobjectAdjustment, 2> Adjustments;
93 const Expr *Temp = MTE->GetTemporaryExpr();
94 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
96 // Keep any cv-qualifiers from the reference if we generated a temporary
97 // for it directly. Otherwise use the type after adjustment.
98 if (!Adjustments.empty())
99 return Inner->getType();
102 return Base->getType();
105 /// Get an LValue path entry, which is known to not be an array index, as a
106 /// field or base class.
108 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
109 APValue::BaseOrMemberType Value;
110 Value.setFromOpaqueValue(E.BaseOrMember);
114 /// Get an LValue path entry, which is known to not be an array index, as a
115 /// field declaration.
116 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
117 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
119 /// Get an LValue path entry, which is known to not be an array index, as a
120 /// base class declaration.
121 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
122 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
124 /// Determine whether this LValue path entry for a base class names a virtual
126 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
127 return getAsBaseOrMember(E).getInt();
130 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132 const FunctionDecl *Callee = CE->getDirectCallee();
133 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
136 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137 /// This will look through a single cast.
139 /// Returns null if we couldn't unwrap a function with alloc_size.
140 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141 if (!E->getType()->isPointerType())
144 E = E->IgnoreParens();
145 // If we're doing a variable assignment from e.g. malloc(N), there will
146 // probably be a cast of some kind. In exotic cases, we might also see a
147 // top-level ExprWithCleanups. Ignore them either way.
148 if (const auto *FE = dyn_cast<FullExpr>(E))
149 E = FE->getSubExpr()->IgnoreParens();
151 if (const auto *Cast = dyn_cast<CastExpr>(E))
152 E = Cast->getSubExpr()->IgnoreParens();
154 if (const auto *CE = dyn_cast<CallExpr>(E))
155 return getAllocSizeAttr(CE) ? CE : nullptr;
159 /// Determines whether or not the given Base contains a call to a function
160 /// with the alloc_size attribute.
161 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162 const auto *E = Base.dyn_cast<const Expr *>();
163 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
166 /// The bound to claim that an array of unknown bound has.
167 /// The value in MostDerivedArraySize is undefined in this case. So, set it
168 /// to an arbitrary value that's likely to loudly break things if it's used.
169 static const uint64_t AssumedSizeForUnsizedArray =
170 std::numeric_limits<uint64_t>::max() / 2;
172 /// Determines if an LValue with the given LValueBase will have an unsized
173 /// array in its designator.
174 /// Find the path length and type of the most-derived subobject in the given
175 /// path, and find the size of the containing array, if any.
177 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
178 ArrayRef<APValue::LValuePathEntry> Path,
179 uint64_t &ArraySize, QualType &Type, bool &IsArray,
180 bool &FirstEntryIsUnsizedArray) {
181 // This only accepts LValueBases from APValues, and APValues don't support
182 // arrays that lack size info.
183 assert(!isBaseAnAllocSizeCall(Base) &&
184 "Unsized arrays shouldn't appear here");
185 unsigned MostDerivedLength = 0;
186 Type = getType(Base);
188 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
189 if (Type->isArrayType()) {
190 const ArrayType *AT = Ctx.getAsArrayType(Type);
191 Type = AT->getElementType();
192 MostDerivedLength = I + 1;
195 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196 ArraySize = CAT->getSize().getZExtValue();
198 assert(I == 0 && "unexpected unsized array designator");
199 FirstEntryIsUnsizedArray = true;
200 ArraySize = AssumedSizeForUnsizedArray;
202 } else if (Type->isAnyComplexType()) {
203 const ComplexType *CT = Type->castAs<ComplexType>();
204 Type = CT->getElementType();
206 MostDerivedLength = I + 1;
208 } else if (const FieldDecl *FD = getAsField(Path[I])) {
209 Type = FD->getType();
211 MostDerivedLength = I + 1;
214 // Path[I] describes a base class.
219 return MostDerivedLength;
222 // The order of this enum is important for diagnostics.
223 enum CheckSubobjectKind {
224 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
225 CSK_This, CSK_Real, CSK_Imag
228 /// A path from a glvalue to a subobject of that glvalue.
229 struct SubobjectDesignator {
230 /// True if the subobject was named in a manner not supported by C++11. Such
231 /// lvalues can still be folded, but they are not core constant expressions
232 /// and we cannot perform lvalue-to-rvalue conversions on them.
233 unsigned Invalid : 1;
235 /// Is this a pointer one past the end of an object?
236 unsigned IsOnePastTheEnd : 1;
238 /// Indicator of whether the first entry is an unsized array.
239 unsigned FirstEntryIsAnUnsizedArray : 1;
241 /// Indicator of whether the most-derived object is an array element.
242 unsigned MostDerivedIsArrayElement : 1;
244 /// The length of the path to the most-derived object of which this is a
246 unsigned MostDerivedPathLength : 28;
248 /// The size of the array of which the most-derived object is an element.
249 /// This will always be 0 if the most-derived object is not an array
250 /// element. 0 is not an indicator of whether or not the most-derived object
251 /// is an array, however, because 0-length arrays are allowed.
253 /// If the current array is an unsized array, the value of this is
255 uint64_t MostDerivedArraySize;
257 /// The type of the most derived object referred to by this address.
258 QualType MostDerivedType;
260 typedef APValue::LValuePathEntry PathEntry;
262 /// The entries on the path from the glvalue to the designated subobject.
263 SmallVector<PathEntry, 8> Entries;
265 SubobjectDesignator() : Invalid(true) {}
267 explicit SubobjectDesignator(QualType T)
268 : Invalid(false), IsOnePastTheEnd(false),
269 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
270 MostDerivedPathLength(0), MostDerivedArraySize(0),
271 MostDerivedType(T) {}
273 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
274 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
275 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
276 MostDerivedPathLength(0), MostDerivedArraySize(0) {
277 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
279 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
280 ArrayRef<PathEntry> VEntries = V.getLValuePath();
281 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
282 if (V.getLValueBase()) {
283 bool IsArray = false;
284 bool FirstIsUnsizedArray = false;
285 MostDerivedPathLength = findMostDerivedSubobject(
286 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
287 MostDerivedType, IsArray, FirstIsUnsizedArray);
288 MostDerivedIsArrayElement = IsArray;
289 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
299 /// Determine whether the most derived subobject is an array without a
301 bool isMostDerivedAnUnsizedArray() const {
302 assert(!Invalid && "Calling this makes no sense on invalid designators");
303 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
306 /// Determine what the most derived array's size is. Results in an assertion
307 /// failure if the most derived array lacks a size.
308 uint64_t getMostDerivedArraySize() const {
309 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310 return MostDerivedArraySize;
313 /// Determine whether this is a one-past-the-end pointer.
314 bool isOnePastTheEnd() const {
318 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
319 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
324 /// Get the range of valid index adjustments in the form
325 /// {maximum value that can be subtracted from this pointer,
326 /// maximum value that can be added to this pointer}
327 std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328 if (Invalid || isMostDerivedAnUnsizedArray())
331 // [expr.add]p4: For the purposes of these operators, a pointer to a
332 // nonarray object behaves the same as a pointer to the first element of
333 // an array of length one with the type of the object as its element type.
334 bool IsArray = MostDerivedPathLength == Entries.size() &&
335 MostDerivedIsArrayElement;
336 uint64_t ArrayIndex =
337 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
339 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340 return {ArrayIndex, ArraySize - ArrayIndex};
343 /// Check that this refers to a valid subobject.
344 bool isValidSubobject() const {
347 return !isOnePastTheEnd();
349 /// Check that this refers to a valid subobject, and if not, produce a
350 /// relevant diagnostic and set the designator as invalid.
351 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
353 /// Get the type of the designated object.
354 QualType getType(ASTContext &Ctx) const {
355 assert(!Invalid && "invalid designator has no subobject type");
356 return MostDerivedPathLength == Entries.size()
358 : Ctx.getRecordType(getAsBaseClass(Entries.back()));
361 /// Update this designator to refer to the first element within this array.
362 void addArrayUnchecked(const ConstantArrayType *CAT) {
364 Entry.ArrayIndex = 0;
365 Entries.push_back(Entry);
367 // This is a most-derived object.
368 MostDerivedType = CAT->getElementType();
369 MostDerivedIsArrayElement = true;
370 MostDerivedArraySize = CAT->getSize().getZExtValue();
371 MostDerivedPathLength = Entries.size();
373 /// Update this designator to refer to the first element within the array of
374 /// elements of type T. This is an array of unknown size.
375 void addUnsizedArrayUnchecked(QualType ElemTy) {
377 Entry.ArrayIndex = 0;
378 Entries.push_back(Entry);
380 MostDerivedType = ElemTy;
381 MostDerivedIsArrayElement = true;
382 // The value in MostDerivedArraySize is undefined in this case. So, set it
383 // to an arbitrary value that's likely to loudly break things if it's
385 MostDerivedArraySize = AssumedSizeForUnsizedArray;
386 MostDerivedPathLength = Entries.size();
388 /// Update this designator to refer to the given base or member of this
390 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
392 APValue::BaseOrMemberType Value(D, Virtual);
393 Entry.BaseOrMember = Value.getOpaqueValue();
394 Entries.push_back(Entry);
396 // If this isn't a base class, it's a new most-derived object.
397 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398 MostDerivedType = FD->getType();
399 MostDerivedIsArrayElement = false;
400 MostDerivedArraySize = 0;
401 MostDerivedPathLength = Entries.size();
404 /// Update this designator to refer to the given complex component.
405 void addComplexUnchecked(QualType EltTy, bool Imag) {
407 Entry.ArrayIndex = Imag;
408 Entries.push_back(Entry);
410 // This is technically a most-derived object, though in practice this
411 // is unlikely to matter.
412 MostDerivedType = EltTy;
413 MostDerivedIsArrayElement = true;
414 MostDerivedArraySize = 2;
415 MostDerivedPathLength = Entries.size();
417 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
418 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
420 /// Add N to the address of this subobject.
421 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422 if (Invalid || !N) return;
423 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424 if (isMostDerivedAnUnsizedArray()) {
425 diagnoseUnsizedArrayPointerArithmetic(Info, E);
426 // Can't verify -- trust that the user is doing the right thing (or if
427 // not, trust that the caller will catch the bad behavior).
428 // FIXME: Should we reject if this overflows, at least?
429 Entries.back().ArrayIndex += TruncatedN;
433 // [expr.add]p4: For the purposes of these operators, a pointer to a
434 // nonarray object behaves the same as a pointer to the first element of
435 // an array of length one with the type of the object as its element type.
436 bool IsArray = MostDerivedPathLength == Entries.size() &&
437 MostDerivedIsArrayElement;
438 uint64_t ArrayIndex =
439 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
441 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
443 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444 // Calculate the actual index in a wide enough type, so we can include
446 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447 (llvm::APInt&)N += ArrayIndex;
448 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449 diagnosePointerArithmetic(Info, E, N);
454 ArrayIndex += TruncatedN;
455 assert(ArrayIndex <= ArraySize &&
456 "bounds check succeeded for out-of-bounds index");
459 Entries.back().ArrayIndex = ArrayIndex;
461 IsOnePastTheEnd = (ArrayIndex != 0);
465 /// A stack frame in the constexpr call stack.
466 struct CallStackFrame {
469 /// Parent - The caller of this stack frame.
470 CallStackFrame *Caller;
472 /// Callee - The function which was called.
473 const FunctionDecl *Callee;
475 /// This - The binding for the this pointer in this call, if any.
478 /// Arguments - Parameter bindings for this function call, indexed by
479 /// parameters' function scope indices.
482 // Note that we intentionally use std::map here so that references to
483 // values are stable.
484 typedef std::pair<const void *, unsigned> MapKeyTy;
485 typedef std::map<MapKeyTy, APValue> MapTy;
486 /// Temporaries - Temporary lvalues materialized within this stack frame.
489 /// CallLoc - The location of the call expression for this call.
490 SourceLocation CallLoc;
492 /// Index - The call index of this call.
495 /// The stack of integers for tracking version numbers for temporaries.
496 SmallVector<unsigned, 2> TempVersionStack = {1};
497 unsigned CurTempVersion = TempVersionStack.back();
499 unsigned getTempVersion() const { return TempVersionStack.back(); }
501 void pushTempVersion() {
502 TempVersionStack.push_back(++CurTempVersion);
505 void popTempVersion() {
506 TempVersionStack.pop_back();
509 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
510 // on the overall stack usage of deeply-recursing constexpr evaluations.
511 // (We should cache this map rather than recomputing it repeatedly.)
512 // But let's try this and see how it goes; we can look into caching the map
513 // as a later change.
515 /// LambdaCaptureFields - Mapping from captured variables/this to
516 /// corresponding data members in the closure class.
517 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518 FieldDecl *LambdaThisCaptureField;
520 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521 const FunctionDecl *Callee, const LValue *This,
525 // Return the temporary for Key whose version number is Version.
526 APValue *getTemporary(const void *Key, unsigned Version) {
527 MapKeyTy KV(Key, Version);
528 auto LB = Temporaries.lower_bound(KV);
529 if (LB != Temporaries.end() && LB->first == KV)
531 // Pair (Key,Version) wasn't found in the map. Check that no elements
532 // in the map have 'Key' as their key.
533 assert((LB == Temporaries.end() || LB->first.first != Key) &&
534 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535 "Element with key 'Key' found in map");
539 // Return the current temporary for Key in the map.
540 APValue *getCurrentTemporary(const void *Key) {
541 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543 return &std::prev(UB)->second;
547 // Return the version number of the current temporary for Key.
548 unsigned getCurrentTemporaryVersion(const void *Key) const {
549 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551 return std::prev(UB)->first.second;
555 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
558 /// Temporarily override 'this'.
559 class ThisOverrideRAII {
561 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562 : Frame(Frame), OldThis(Frame.This) {
564 Frame.This = NewThis;
566 ~ThisOverrideRAII() {
567 Frame.This = OldThis;
570 CallStackFrame &Frame;
571 const LValue *OldThis;
574 /// A partial diagnostic which we might know in advance that we are not going
576 class OptionalDiagnostic {
577 PartialDiagnostic *Diag;
580 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
584 OptionalDiagnostic &operator<<(const T &v) {
590 OptionalDiagnostic &operator<<(const APSInt &I) {
592 SmallVector<char, 32> Buffer;
594 *Diag << StringRef(Buffer.data(), Buffer.size());
599 OptionalDiagnostic &operator<<(const APFloat &F) {
601 // FIXME: Force the precision of the source value down so we don't
602 // print digits which are usually useless (we don't really care here if
603 // we truncate a digit by accident in edge cases). Ideally,
604 // APFloat::toString would automatically print the shortest
605 // representation which rounds to the correct value, but it's a bit
606 // tricky to implement.
608 llvm::APFloat::semanticsPrecision(F.getSemantics());
609 precision = (precision * 59 + 195) / 196;
610 SmallVector<char, 32> Buffer;
611 F.toString(Buffer, precision);
612 *Diag << StringRef(Buffer.data(), Buffer.size());
618 /// A cleanup, and a flag indicating whether it is lifetime-extended.
620 llvm::PointerIntPair<APValue*, 1, bool> Value;
623 Cleanup(APValue *Val, bool IsLifetimeExtended)
624 : Value(Val, IsLifetimeExtended) {}
626 bool isLifetimeExtended() const { return Value.getInt(); }
628 *Value.getPointer() = APValue();
632 /// EvalInfo - This is a private struct used by the evaluator to capture
633 /// information about a subexpression as it is folded. It retains information
634 /// about the AST context, but also maintains information about the folded
637 /// If an expression could be evaluated, it is still possible it is not a C
638 /// "integer constant expression" or constant expression. If not, this struct
639 /// captures information about how and why not.
641 /// One bit of information passed *into* the request for constant folding
642 /// indicates whether the subexpression is "evaluated" or not according to C
643 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
644 /// evaluate the expression regardless of what the RHS is, but C only allows
645 /// certain things in certain situations.
649 /// EvalStatus - Contains information about the evaluation.
650 Expr::EvalStatus &EvalStatus;
652 /// CurrentCall - The top of the constexpr call stack.
653 CallStackFrame *CurrentCall;
655 /// CallStackDepth - The number of calls in the call stack right now.
656 unsigned CallStackDepth;
658 /// NextCallIndex - The next call index to assign.
659 unsigned NextCallIndex;
661 /// StepsLeft - The remaining number of evaluation steps we're permitted
662 /// to perform. This is essentially a limit for the number of statements
663 /// we will evaluate.
666 /// BottomFrame - The frame in which evaluation started. This must be
667 /// initialized after CurrentCall and CallStackDepth.
668 CallStackFrame BottomFrame;
670 /// A stack of values whose lifetimes end at the end of some surrounding
671 /// evaluation frame.
672 llvm::SmallVector<Cleanup, 16> CleanupStack;
674 /// EvaluatingDecl - This is the declaration whose initializer is being
675 /// evaluated, if any.
676 APValue::LValueBase EvaluatingDecl;
678 /// EvaluatingDeclValue - This is the value being constructed for the
679 /// declaration whose initializer is being evaluated, if any.
680 APValue *EvaluatingDeclValue;
682 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
683 /// the call index that that lvalue was allocated in.
684 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
687 /// EvaluatingConstructors - Set of objects that are currently being
689 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
691 struct EvaluatingConstructorRAII {
693 EvaluatingObject Object;
695 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
696 : EI(EI), Object(Object) {
697 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
699 ~EvaluatingConstructorRAII() {
700 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
704 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
706 return EvaluatingConstructors.count(
707 EvaluatingObject(Decl, {CallIndex, Version}));
710 /// The current array initialization index, if we're performing array
712 uint64_t ArrayInitIndex = -1;
714 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
715 /// notes attached to it will also be stored, otherwise they will not be.
716 bool HasActiveDiagnostic;
718 /// Have we emitted a diagnostic explaining why we couldn't constant
719 /// fold (not just why it's not strictly a constant expression)?
720 bool HasFoldFailureDiagnostic;
722 /// Whether or not we're currently speculatively evaluating.
723 bool IsSpeculativelyEvaluating;
725 /// Whether or not we're in a context where the front end requires a
727 bool InConstantContext;
729 enum EvaluationMode {
730 /// Evaluate as a constant expression. Stop if we find that the expression
731 /// is not a constant expression.
732 EM_ConstantExpression,
734 /// Evaluate as a potential constant expression. Keep going if we hit a
735 /// construct that we can't evaluate yet (because we don't yet know the
736 /// value of something) but stop if we hit something that could never be
737 /// a constant expression.
738 EM_PotentialConstantExpression,
740 /// Fold the expression to a constant. Stop if we hit a side-effect that
744 /// Evaluate the expression looking for integer overflow and similar
745 /// issues. Don't worry about side-effects, and try to visit all
747 EM_EvaluateForOverflow,
749 /// Evaluate in any way we know how. Don't worry about side-effects that
750 /// can't be modeled.
751 EM_IgnoreSideEffects,
753 /// Evaluate as a constant expression. Stop if we find that the expression
754 /// is not a constant expression. Some expressions can be retried in the
755 /// optimizer if we don't constant fold them here, but in an unevaluated
756 /// context we try to fold them immediately since the optimizer never
757 /// gets a chance to look at it.
758 EM_ConstantExpressionUnevaluated,
760 /// Evaluate as a potential constant expression. Keep going if we hit a
761 /// construct that we can't evaluate yet (because we don't yet know the
762 /// value of something) but stop if we hit something that could never be
763 /// a constant expression. Some expressions can be retried in the
764 /// optimizer if we don't constant fold them here, but in an unevaluated
765 /// context we try to fold them immediately since the optimizer never
766 /// gets a chance to look at it.
767 EM_PotentialConstantExpressionUnevaluated,
770 /// Are we checking whether the expression is a potential constant
772 bool checkingPotentialConstantExpression() const {
773 return EvalMode == EM_PotentialConstantExpression ||
774 EvalMode == EM_PotentialConstantExpressionUnevaluated;
777 /// Are we checking an expression for overflow?
778 // FIXME: We should check for any kind of undefined or suspicious behavior
779 // in such constructs, not just overflow.
780 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
782 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
783 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
784 CallStackDepth(0), NextCallIndex(1),
785 StepsLeft(getLangOpts().ConstexprStepLimit),
786 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
787 EvaluatingDecl((const ValueDecl *)nullptr),
788 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
789 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
790 InConstantContext(false), EvalMode(Mode) {}
792 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
793 EvaluatingDecl = Base;
794 EvaluatingDeclValue = &Value;
795 EvaluatingConstructors.insert({Base, {0, 0}});
798 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
800 bool CheckCallLimit(SourceLocation Loc) {
801 // Don't perform any constexpr calls (other than the call we're checking)
802 // when checking a potential constant expression.
803 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
805 if (NextCallIndex == 0) {
806 // NextCallIndex has wrapped around.
807 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
810 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
812 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
813 << getLangOpts().ConstexprCallDepth;
817 CallStackFrame *getCallFrame(unsigned CallIndex) {
818 assert(CallIndex && "no call index in getCallFrame");
819 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
820 // be null in this loop.
821 CallStackFrame *Frame = CurrentCall;
822 while (Frame->Index > CallIndex)
823 Frame = Frame->Caller;
824 return (Frame->Index == CallIndex) ? Frame : nullptr;
827 bool nextStep(const Stmt *S) {
829 FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
837 /// Add a diagnostic to the diagnostics list.
838 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
839 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
840 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
841 return EvalStatus.Diag->back().second;
844 /// Add notes containing a call stack to the current point of evaluation.
845 void addCallStack(unsigned Limit);
848 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
849 unsigned ExtraNotes, bool IsCCEDiag) {
851 if (EvalStatus.Diag) {
852 // If we have a prior diagnostic, it will be noting that the expression
853 // isn't a constant expression. This diagnostic is more important,
854 // unless we require this evaluation to produce a constant expression.
856 // FIXME: We might want to show both diagnostics to the user in
857 // EM_ConstantFold mode.
858 if (!EvalStatus.Diag->empty()) {
860 case EM_ConstantFold:
861 case EM_IgnoreSideEffects:
862 case EM_EvaluateForOverflow:
863 if (!HasFoldFailureDiagnostic)
865 // We've already failed to fold something. Keep that diagnostic.
867 case EM_ConstantExpression:
868 case EM_PotentialConstantExpression:
869 case EM_ConstantExpressionUnevaluated:
870 case EM_PotentialConstantExpressionUnevaluated:
871 HasActiveDiagnostic = false;
872 return OptionalDiagnostic();
876 unsigned CallStackNotes = CallStackDepth - 1;
877 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
879 CallStackNotes = std::min(CallStackNotes, Limit + 1);
880 if (checkingPotentialConstantExpression())
883 HasActiveDiagnostic = true;
884 HasFoldFailureDiagnostic = !IsCCEDiag;
885 EvalStatus.Diag->clear();
886 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
887 addDiag(Loc, DiagId);
888 if (!checkingPotentialConstantExpression())
890 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
892 HasActiveDiagnostic = false;
893 return OptionalDiagnostic();
896 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
898 FFDiag(SourceLocation Loc,
899 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
900 unsigned ExtraNotes = 0) {
901 return Diag(Loc, DiagId, ExtraNotes, false);
904 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
905 = diag::note_invalid_subexpr_in_const_expr,
906 unsigned ExtraNotes = 0) {
908 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
909 HasActiveDiagnostic = false;
910 return OptionalDiagnostic();
913 /// Diagnose that the evaluation does not produce a C++11 core constant
916 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
917 /// EM_PotentialConstantExpression mode and we produce one of these.
918 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
919 = diag::note_invalid_subexpr_in_const_expr,
920 unsigned ExtraNotes = 0) {
921 // Don't override a previous diagnostic. Don't bother collecting
922 // diagnostics if we're evaluating for overflow.
923 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
924 HasActiveDiagnostic = false;
925 return OptionalDiagnostic();
927 return Diag(Loc, DiagId, ExtraNotes, true);
929 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
930 = diag::note_invalid_subexpr_in_const_expr,
931 unsigned ExtraNotes = 0) {
932 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
934 /// Add a note to a prior diagnostic.
935 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
936 if (!HasActiveDiagnostic)
937 return OptionalDiagnostic();
938 return OptionalDiagnostic(&addDiag(Loc, DiagId));
941 /// Add a stack of notes to a prior diagnostic.
942 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
943 if (HasActiveDiagnostic) {
944 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
945 Diags.begin(), Diags.end());
949 /// Should we continue evaluation after encountering a side-effect that we
951 bool keepEvaluatingAfterSideEffect() {
953 case EM_PotentialConstantExpression:
954 case EM_PotentialConstantExpressionUnevaluated:
955 case EM_EvaluateForOverflow:
956 case EM_IgnoreSideEffects:
959 case EM_ConstantExpression:
960 case EM_ConstantExpressionUnevaluated:
961 case EM_ConstantFold:
964 llvm_unreachable("Missed EvalMode case");
967 /// Note that we have had a side-effect, and determine whether we should
969 bool noteSideEffect() {
970 EvalStatus.HasSideEffects = true;
971 return keepEvaluatingAfterSideEffect();
974 /// Should we continue evaluation after encountering undefined behavior?
975 bool keepEvaluatingAfterUndefinedBehavior() {
977 case EM_EvaluateForOverflow:
978 case EM_IgnoreSideEffects:
979 case EM_ConstantFold:
982 case EM_PotentialConstantExpression:
983 case EM_PotentialConstantExpressionUnevaluated:
984 case EM_ConstantExpression:
985 case EM_ConstantExpressionUnevaluated:
988 llvm_unreachable("Missed EvalMode case");
991 /// Note that we hit something that was technically undefined behavior, but
992 /// that we can evaluate past it (such as signed overflow or floating-point
993 /// division by zero.)
994 bool noteUndefinedBehavior() {
995 EvalStatus.HasUndefinedBehavior = true;
996 return keepEvaluatingAfterUndefinedBehavior();
999 /// Should we continue evaluation as much as possible after encountering a
1000 /// construct which can't be reduced to a value?
1001 bool keepEvaluatingAfterFailure() {
1006 case EM_PotentialConstantExpression:
1007 case EM_PotentialConstantExpressionUnevaluated:
1008 case EM_EvaluateForOverflow:
1011 case EM_ConstantExpression:
1012 case EM_ConstantExpressionUnevaluated:
1013 case EM_ConstantFold:
1014 case EM_IgnoreSideEffects:
1017 llvm_unreachable("Missed EvalMode case");
1020 /// Notes that we failed to evaluate an expression that other expressions
1021 /// directly depend on, and determine if we should keep evaluating. This
1022 /// should only be called if we actually intend to keep evaluating.
1024 /// Call noteSideEffect() instead if we may be able to ignore the value that
1025 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1027 /// (Foo(), 1) // use noteSideEffect
1028 /// (Foo() || true) // use noteSideEffect
1029 /// Foo() + 1 // use noteFailure
1030 LLVM_NODISCARD bool noteFailure() {
1031 // Failure when evaluating some expression often means there is some
1032 // subexpression whose evaluation was skipped. Therefore, (because we
1033 // don't track whether we skipped an expression when unwinding after an
1034 // evaluation failure) every evaluation failure that bubbles up from a
1035 // subexpression implies that a side-effect has potentially happened. We
1036 // skip setting the HasSideEffects flag to true until we decide to
1037 // continue evaluating after that point, which happens here.
1038 bool KeepGoing = keepEvaluatingAfterFailure();
1039 EvalStatus.HasSideEffects |= KeepGoing;
1043 class ArrayInitLoopIndex {
1045 uint64_t OuterIndex;
1048 ArrayInitLoopIndex(EvalInfo &Info)
1049 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1050 Info.ArrayInitIndex = 0;
1052 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1054 operator uint64_t&() { return Info.ArrayInitIndex; }
1058 /// Object used to treat all foldable expressions as constant expressions.
1059 struct FoldConstant {
1062 bool HadNoPriorDiags;
1063 EvalInfo::EvaluationMode OldMode;
1065 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1068 HadNoPriorDiags(Info.EvalStatus.Diag &&
1069 Info.EvalStatus.Diag->empty() &&
1070 !Info.EvalStatus.HasSideEffects),
1071 OldMode(Info.EvalMode) {
1073 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1074 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1075 Info.EvalMode = EvalInfo::EM_ConstantFold;
1077 void keepDiagnostics() { Enabled = false; }
1079 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1080 !Info.EvalStatus.HasSideEffects)
1081 Info.EvalStatus.Diag->clear();
1082 Info.EvalMode = OldMode;
1086 /// RAII object used to set the current evaluation mode to ignore
1088 struct IgnoreSideEffectsRAII {
1090 EvalInfo::EvaluationMode OldMode;
1091 explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1092 : Info(Info), OldMode(Info.EvalMode) {
1093 if (!Info.checkingPotentialConstantExpression())
1094 Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1097 ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1100 /// RAII object used to optionally suppress diagnostics and side-effects from
1101 /// a speculative evaluation.
1102 class SpeculativeEvaluationRAII {
1103 EvalInfo *Info = nullptr;
1104 Expr::EvalStatus OldStatus;
1105 bool OldIsSpeculativelyEvaluating;
1107 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1109 OldStatus = Other.OldStatus;
1110 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1111 Other.Info = nullptr;
1114 void maybeRestoreState() {
1118 Info->EvalStatus = OldStatus;
1119 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1123 SpeculativeEvaluationRAII() = default;
1125 SpeculativeEvaluationRAII(
1126 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1127 : Info(&Info), OldStatus(Info.EvalStatus),
1128 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1129 Info.EvalStatus.Diag = NewDiag;
1130 Info.IsSpeculativelyEvaluating = true;
1133 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1134 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1135 moveFromAndCancel(std::move(Other));
1138 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1139 maybeRestoreState();
1140 moveFromAndCancel(std::move(Other));
1144 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1147 /// RAII object wrapping a full-expression or block scope, and handling
1148 /// the ending of the lifetime of temporaries created within it.
1149 template<bool IsFullExpression>
1152 unsigned OldStackSize;
1154 ScopeRAII(EvalInfo &Info)
1155 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1156 // Push a new temporary version. This is needed to distinguish between
1157 // temporaries created in different iterations of a loop.
1158 Info.CurrentCall->pushTempVersion();
1161 // Body moved to a static method to encourage the compiler to inline away
1162 // instances of this class.
1163 cleanup(Info, OldStackSize);
1164 Info.CurrentCall->popTempVersion();
1167 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1168 unsigned NewEnd = OldStackSize;
1169 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1171 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1172 // Full-expression cleanup of a lifetime-extended temporary: nothing
1173 // to do, just move this cleanup to the right place in the stack.
1174 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1177 // End the lifetime of the object.
1178 Info.CleanupStack[I].endLifetime();
1181 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1182 Info.CleanupStack.end());
1185 typedef ScopeRAII<false> BlockScopeRAII;
1186 typedef ScopeRAII<true> FullExpressionRAII;
1189 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1190 CheckSubobjectKind CSK) {
1193 if (isOnePastTheEnd()) {
1194 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1199 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1200 // must actually be at least one array element; even a VLA cannot have a
1201 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1205 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1207 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1208 // Do not set the designator as invalid: we can represent this situation,
1209 // and correct handling of __builtin_object_size requires us to do so.
1212 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1215 // If we're complaining, we must be able to statically determine the size of
1216 // the most derived array.
1217 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1218 Info.CCEDiag(E, diag::note_constexpr_array_index)
1220 << static_cast<unsigned>(getMostDerivedArraySize());
1222 Info.CCEDiag(E, diag::note_constexpr_array_index)
1223 << N << /*non-array*/ 1;
1227 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1228 const FunctionDecl *Callee, const LValue *This,
1230 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1231 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1232 Info.CurrentCall = this;
1233 ++Info.CallStackDepth;
1236 CallStackFrame::~CallStackFrame() {
1237 assert(Info.CurrentCall == this && "calls retired out of order");
1238 --Info.CallStackDepth;
1239 Info.CurrentCall = Caller;
1242 APValue &CallStackFrame::createTemporary(const void *Key,
1243 bool IsLifetimeExtended) {
1244 unsigned Version = Info.CurrentCall->getTempVersion();
1245 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1246 assert(Result.isUninit() && "temporary created multiple times");
1247 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1251 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1253 void EvalInfo::addCallStack(unsigned Limit) {
1254 // Determine which calls to skip, if any.
1255 unsigned ActiveCalls = CallStackDepth - 1;
1256 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1257 if (Limit && Limit < ActiveCalls) {
1258 SkipStart = Limit / 2 + Limit % 2;
1259 SkipEnd = ActiveCalls - Limit / 2;
1262 // Walk the call stack and add the diagnostics.
1263 unsigned CallIdx = 0;
1264 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1265 Frame = Frame->Caller, ++CallIdx) {
1267 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1268 if (CallIdx == SkipStart) {
1269 // Note that we're skipping calls.
1270 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1271 << unsigned(ActiveCalls - Limit);
1276 // Use a different note for an inheriting constructor, because from the
1277 // user's perspective it's not really a function at all.
1278 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1279 if (CD->isInheritingConstructor()) {
1280 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1286 SmallVector<char, 128> Buffer;
1287 llvm::raw_svector_ostream Out(Buffer);
1288 describeCall(Frame, Out);
1289 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1293 /// Kinds of access we can perform on an object, for diagnostics.
1302 struct ComplexValue {
1307 APSInt IntReal, IntImag;
1308 APFloat FloatReal, FloatImag;
1310 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1312 void makeComplexFloat() { IsInt = false; }
1313 bool isComplexFloat() const { return !IsInt; }
1314 APFloat &getComplexFloatReal() { return FloatReal; }
1315 APFloat &getComplexFloatImag() { return FloatImag; }
1317 void makeComplexInt() { IsInt = true; }
1318 bool isComplexInt() const { return IsInt; }
1319 APSInt &getComplexIntReal() { return IntReal; }
1320 APSInt &getComplexIntImag() { return IntImag; }
1322 void moveInto(APValue &v) const {
1323 if (isComplexFloat())
1324 v = APValue(FloatReal, FloatImag);
1326 v = APValue(IntReal, IntImag);
1328 void setFrom(const APValue &v) {
1329 assert(v.isComplexFloat() || v.isComplexInt());
1330 if (v.isComplexFloat()) {
1332 FloatReal = v.getComplexFloatReal();
1333 FloatImag = v.getComplexFloatImag();
1336 IntReal = v.getComplexIntReal();
1337 IntImag = v.getComplexIntImag();
1343 APValue::LValueBase Base;
1345 SubobjectDesignator Designator;
1347 bool InvalidBase : 1;
1349 const APValue::LValueBase getLValueBase() const { return Base; }
1350 CharUnits &getLValueOffset() { return Offset; }
1351 const CharUnits &getLValueOffset() const { return Offset; }
1352 SubobjectDesignator &getLValueDesignator() { return Designator; }
1353 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1354 bool isNullPointer() const { return IsNullPtr;}
1356 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1357 unsigned getLValueVersion() const { return Base.getVersion(); }
1359 void moveInto(APValue &V) const {
1360 if (Designator.Invalid)
1361 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1363 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1364 V = APValue(Base, Offset, Designator.Entries,
1365 Designator.IsOnePastTheEnd, IsNullPtr);
1368 void setFrom(ASTContext &Ctx, const APValue &V) {
1369 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1370 Base = V.getLValueBase();
1371 Offset = V.getLValueOffset();
1372 InvalidBase = false;
1373 Designator = SubobjectDesignator(Ctx, V);
1374 IsNullPtr = V.isNullPointer();
1377 void set(APValue::LValueBase B, bool BInvalid = false) {
1379 // We only allow a few types of invalid bases. Enforce that here.
1381 const auto *E = B.get<const Expr *>();
1382 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1383 "Unexpected type of invalid base");
1388 Offset = CharUnits::fromQuantity(0);
1389 InvalidBase = BInvalid;
1390 Designator = SubobjectDesignator(getType(B));
1394 void setNull(QualType PointerTy, uint64_t TargetVal) {
1395 Base = (Expr *)nullptr;
1396 Offset = CharUnits::fromQuantity(TargetVal);
1397 InvalidBase = false;
1398 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1402 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1407 // Check that this LValue is not based on a null pointer. If it is, produce
1408 // a diagnostic and mark the designator as invalid.
1409 template <typename GenDiagType>
1410 bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1411 if (Designator.Invalid)
1415 Designator.setInvalid();
1422 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1423 CheckSubobjectKind CSK) {
1424 return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1425 Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1429 bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1431 return checkNullPointerDiagnosingWith([&Info, E, AK] {
1432 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1436 // Check this LValue refers to an object. If not, set the designator to be
1437 // invalid and emit a diagnostic.
1438 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1439 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1440 Designator.checkSubobject(Info, E, CSK);
1443 void addDecl(EvalInfo &Info, const Expr *E,
1444 const Decl *D, bool Virtual = false) {
1445 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1446 Designator.addDeclUnchecked(D, Virtual);
1448 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1449 if (!Designator.Entries.empty()) {
1450 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1451 Designator.setInvalid();
1454 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1455 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1456 Designator.FirstEntryIsAnUnsizedArray = true;
1457 Designator.addUnsizedArrayUnchecked(ElemTy);
1460 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1461 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1462 Designator.addArrayUnchecked(CAT);
1464 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1465 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1466 Designator.addComplexUnchecked(EltTy, Imag);
1468 void clearIsNullPointer() {
1471 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1472 const APSInt &Index, CharUnits ElementSize) {
1473 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1474 // but we're not required to diagnose it and it's valid in C++.)
1478 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1479 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1481 uint64_t Offset64 = Offset.getQuantity();
1482 uint64_t ElemSize64 = ElementSize.getQuantity();
1483 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1484 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1486 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1487 Designator.adjustIndex(Info, E, Index);
1488 clearIsNullPointer();
1490 void adjustOffset(CharUnits N) {
1492 if (N.getQuantity())
1493 clearIsNullPointer();
1499 explicit MemberPtr(const ValueDecl *Decl) :
1500 DeclAndIsDerivedMember(Decl, false), Path() {}
1502 /// The member or (direct or indirect) field referred to by this member
1503 /// pointer, or 0 if this is a null member pointer.
1504 const ValueDecl *getDecl() const {
1505 return DeclAndIsDerivedMember.getPointer();
1507 /// Is this actually a member of some type derived from the relevant class?
1508 bool isDerivedMember() const {
1509 return DeclAndIsDerivedMember.getInt();
1511 /// Get the class which the declaration actually lives in.
1512 const CXXRecordDecl *getContainingRecord() const {
1513 return cast<CXXRecordDecl>(
1514 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1517 void moveInto(APValue &V) const {
1518 V = APValue(getDecl(), isDerivedMember(), Path);
1520 void setFrom(const APValue &V) {
1521 assert(V.isMemberPointer());
1522 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1523 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1525 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1526 Path.insert(Path.end(), P.begin(), P.end());
1529 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1530 /// whether the member is a member of some class derived from the class type
1531 /// of the member pointer.
1532 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1533 /// Path - The path of base/derived classes from the member declaration's
1534 /// class (exclusive) to the class type of the member pointer (inclusive).
1535 SmallVector<const CXXRecordDecl*, 4> Path;
1537 /// Perform a cast towards the class of the Decl (either up or down the
1539 bool castBack(const CXXRecordDecl *Class) {
1540 assert(!Path.empty());
1541 const CXXRecordDecl *Expected;
1542 if (Path.size() >= 2)
1543 Expected = Path[Path.size() - 2];
1545 Expected = getContainingRecord();
1546 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1547 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1548 // if B does not contain the original member and is not a base or
1549 // derived class of the class containing the original member, the result
1550 // of the cast is undefined.
1551 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1552 // (D::*). We consider that to be a language defect.
1558 /// Perform a base-to-derived member pointer cast.
1559 bool castToDerived(const CXXRecordDecl *Derived) {
1562 if (!isDerivedMember()) {
1563 Path.push_back(Derived);
1566 if (!castBack(Derived))
1569 DeclAndIsDerivedMember.setInt(false);
1572 /// Perform a derived-to-base member pointer cast.
1573 bool castToBase(const CXXRecordDecl *Base) {
1577 DeclAndIsDerivedMember.setInt(true);
1578 if (isDerivedMember()) {
1579 Path.push_back(Base);
1582 return castBack(Base);
1586 /// Compare two member pointers, which are assumed to be of the same type.
1587 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1588 if (!LHS.getDecl() || !RHS.getDecl())
1589 return !LHS.getDecl() && !RHS.getDecl();
1590 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1592 return LHS.Path == RHS.Path;
1596 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1597 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1598 const LValue &This, const Expr *E,
1599 bool AllowNonLiteralTypes = false);
1600 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1601 bool InvalidBaseOK = false);
1602 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1603 bool InvalidBaseOK = false);
1604 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1606 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1607 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1608 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1610 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1611 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1612 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1614 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1616 //===----------------------------------------------------------------------===//
1618 //===----------------------------------------------------------------------===//
1620 /// A helper function to create a temporary and set an LValue.
1621 template <class KeyTy>
1622 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1623 LValue &LV, CallStackFrame &Frame) {
1624 LV.set({Key, Frame.Info.CurrentCall->Index,
1625 Frame.Info.CurrentCall->getTempVersion()});
1626 return Frame.createTemporary(Key, IsLifetimeExtended);
1629 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1630 /// preserving its value (by extending by up to one bit as needed).
1631 static void negateAsSigned(APSInt &Int) {
1632 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1633 Int = Int.extend(Int.getBitWidth() + 1);
1634 Int.setIsSigned(true);
1639 /// Produce a string describing the given constexpr call.
1640 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1641 unsigned ArgIndex = 0;
1642 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1643 !isa<CXXConstructorDecl>(Frame->Callee) &&
1644 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1647 Out << *Frame->Callee << '(';
1649 if (Frame->This && IsMemberCall) {
1651 Frame->This->moveInto(Val);
1652 Val.printPretty(Out, Frame->Info.Ctx,
1653 Frame->This->Designator.MostDerivedType);
1654 // FIXME: Add parens around Val if needed.
1655 Out << "->" << *Frame->Callee << '(';
1656 IsMemberCall = false;
1659 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1660 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1661 if (ArgIndex > (unsigned)IsMemberCall)
1664 const ParmVarDecl *Param = *I;
1665 const APValue &Arg = Frame->Arguments[ArgIndex];
1666 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1668 if (ArgIndex == 0 && IsMemberCall)
1669 Out << "->" << *Frame->Callee << '(';
1675 /// Evaluate an expression to see if it had side-effects, and discard its
1677 /// \return \c true if the caller should keep evaluating.
1678 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1680 if (!Evaluate(Scratch, Info, E))
1681 // We don't need the value, but we might have skipped a side effect here.
1682 return Info.noteSideEffect();
1686 /// Should this call expression be treated as a string literal?
1687 static bool IsStringLiteralCall(const CallExpr *E) {
1688 unsigned Builtin = E->getBuiltinCallee();
1689 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1690 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1693 static bool IsGlobalLValue(APValue::LValueBase B) {
1694 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1695 // constant expression of pointer type that evaluates to...
1697 // ... a null pointer value, or a prvalue core constant expression of type
1699 if (!B) return true;
1701 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1702 // ... the address of an object with static storage duration,
1703 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1704 return VD->hasGlobalStorage();
1705 // ... the address of a function,
1706 return isa<FunctionDecl>(D);
1709 const Expr *E = B.get<const Expr*>();
1710 switch (E->getStmtClass()) {
1713 case Expr::CompoundLiteralExprClass: {
1714 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1715 return CLE->isFileScope() && CLE->isLValue();
1717 case Expr::MaterializeTemporaryExprClass:
1718 // A materialized temporary might have been lifetime-extended to static
1719 // storage duration.
1720 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1721 // A string literal has static storage duration.
1722 case Expr::StringLiteralClass:
1723 case Expr::PredefinedExprClass:
1724 case Expr::ObjCStringLiteralClass:
1725 case Expr::ObjCEncodeExprClass:
1726 case Expr::CXXTypeidExprClass:
1727 case Expr::CXXUuidofExprClass:
1729 case Expr::CallExprClass:
1730 return IsStringLiteralCall(cast<CallExpr>(E));
1731 // For GCC compatibility, &&label has static storage duration.
1732 case Expr::AddrLabelExprClass:
1734 // A Block literal expression may be used as the initialization value for
1735 // Block variables at global or local static scope.
1736 case Expr::BlockExprClass:
1737 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1738 case Expr::ImplicitValueInitExprClass:
1740 // We can never form an lvalue with an implicit value initialization as its
1741 // base through expression evaluation, so these only appear in one case: the
1742 // implicit variable declaration we invent when checking whether a constexpr
1743 // constructor can produce a constant expression. We must assume that such
1744 // an expression might be a global lvalue.
1749 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1750 return LVal.Base.dyn_cast<const ValueDecl*>();
1753 static bool IsLiteralLValue(const LValue &Value) {
1754 if (Value.getLValueCallIndex())
1756 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1757 return E && !isa<MaterializeTemporaryExpr>(E);
1760 static bool IsWeakLValue(const LValue &Value) {
1761 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1762 return Decl && Decl->isWeak();
1765 static bool isZeroSized(const LValue &Value) {
1766 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1767 if (Decl && isa<VarDecl>(Decl)) {
1768 QualType Ty = Decl->getType();
1769 if (Ty->isArrayType())
1770 return Ty->isIncompleteType() ||
1771 Decl->getASTContext().getTypeSize(Ty) == 0;
1776 static bool HasSameBase(const LValue &A, const LValue &B) {
1777 if (!A.getLValueBase())
1778 return !B.getLValueBase();
1779 if (!B.getLValueBase())
1782 if (A.getLValueBase().getOpaqueValue() !=
1783 B.getLValueBase().getOpaqueValue()) {
1784 const Decl *ADecl = GetLValueBaseDecl(A);
1787 const Decl *BDecl = GetLValueBaseDecl(B);
1788 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1792 return IsGlobalLValue(A.getLValueBase()) ||
1793 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1794 A.getLValueVersion() == B.getLValueVersion());
1797 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1798 assert(Base && "no location for a null lvalue");
1799 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1801 Info.Note(VD->getLocation(), diag::note_declared_at);
1803 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1804 diag::note_constexpr_temporary_here);
1807 /// Check that this reference or pointer core constant expression is a valid
1808 /// value for an address or reference constant expression. Return true if we
1809 /// can fold this expression, whether or not it's a constant expression.
1810 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1811 QualType Type, const LValue &LVal,
1812 Expr::ConstExprUsage Usage) {
1813 bool IsReferenceType = Type->isReferenceType();
1815 APValue::LValueBase Base = LVal.getLValueBase();
1816 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1818 // Check that the object is a global. Note that the fake 'this' object we
1819 // manufacture when checking potential constant expressions is conservatively
1820 // assumed to be global here.
1821 if (!IsGlobalLValue(Base)) {
1822 if (Info.getLangOpts().CPlusPlus11) {
1823 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1824 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1825 << IsReferenceType << !Designator.Entries.empty()
1827 NoteLValueLocation(Info, Base);
1831 // Don't allow references to temporaries to escape.
1834 assert((Info.checkingPotentialConstantExpression() ||
1835 LVal.getLValueCallIndex() == 0) &&
1836 "have call index for global lvalue");
1838 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1839 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1840 // Check if this is a thread-local variable.
1841 if (Var->getTLSKind())
1844 // A dllimport variable never acts like a constant.
1845 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1848 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1849 // __declspec(dllimport) must be handled very carefully:
1850 // We must never initialize an expression with the thunk in C++.
1851 // Doing otherwise would allow the same id-expression to yield
1852 // different addresses for the same function in different translation
1853 // units. However, this means that we must dynamically initialize the
1854 // expression with the contents of the import address table at runtime.
1856 // The C language has no notion of ODR; furthermore, it has no notion of
1857 // dynamic initialization. This means that we are permitted to
1858 // perform initialization with the address of the thunk.
1859 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1860 FD->hasAttr<DLLImportAttr>())
1865 // Allow address constant expressions to be past-the-end pointers. This is
1866 // an extension: the standard requires them to point to an object.
1867 if (!IsReferenceType)
1870 // A reference constant expression must refer to an object.
1872 // FIXME: diagnostic
1877 // Does this refer one past the end of some object?
1878 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1879 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1880 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1881 << !Designator.Entries.empty() << !!VD << VD;
1882 NoteLValueLocation(Info, Base);
1888 /// Member pointers are constant expressions unless they point to a
1889 /// non-virtual dllimport member function.
1890 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1893 const APValue &Value,
1894 Expr::ConstExprUsage Usage) {
1895 const ValueDecl *Member = Value.getMemberPointerDecl();
1896 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1899 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1900 !FD->hasAttr<DLLImportAttr>();
1903 /// Check that this core constant expression is of literal type, and if not,
1904 /// produce an appropriate diagnostic.
1905 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1906 const LValue *This = nullptr) {
1907 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1910 // C++1y: A constant initializer for an object o [...] may also invoke
1911 // constexpr constructors for o and its subobjects even if those objects
1912 // are of non-literal class types.
1914 // C++11 missed this detail for aggregates, so classes like this:
1915 // struct foo_t { union { int i; volatile int j; } u; };
1916 // are not (obviously) initializable like so:
1917 // __attribute__((__require_constant_initialization__))
1918 // static const foo_t x = {{0}};
1919 // because "i" is a subobject with non-literal initialization (due to the
1920 // volatile member of the union). See:
1921 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1922 // Therefore, we use the C++1y behavior.
1923 if (This && Info.EvaluatingDecl == This->getLValueBase())
1926 // Prvalue constant expressions must be of literal types.
1927 if (Info.getLangOpts().CPlusPlus11)
1928 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1931 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1935 /// Check that this core constant expression value is a valid value for a
1936 /// constant expression. If not, report an appropriate diagnostic. Does not
1937 /// check that the expression is of literal type.
1939 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1940 const APValue &Value,
1941 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1942 if (Value.isUninit()) {
1943 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1948 // We allow _Atomic(T) to be initialized from anything that T can be
1949 // initialized from.
1950 if (const AtomicType *AT = Type->getAs<AtomicType>())
1951 Type = AT->getValueType();
1953 // Core issue 1454: For a literal constant expression of array or class type,
1954 // each subobject of its value shall have been initialized by a constant
1956 if (Value.isArray()) {
1957 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1958 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1959 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1960 Value.getArrayInitializedElt(I), Usage))
1963 if (!Value.hasArrayFiller())
1965 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1968 if (Value.isUnion() && Value.getUnionField()) {
1969 return CheckConstantExpression(Info, DiagLoc,
1970 Value.getUnionField()->getType(),
1971 Value.getUnionValue(), Usage);
1973 if (Value.isStruct()) {
1974 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1975 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1976 unsigned BaseIndex = 0;
1977 for (const CXXBaseSpecifier &BS : CD->bases()) {
1978 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1979 Value.getStructBase(BaseIndex), Usage))
1984 for (const auto *I : RD->fields()) {
1985 if (I->isUnnamedBitfield())
1988 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1989 Value.getStructField(I->getFieldIndex()),
1995 if (Value.isLValue()) {
1997 LVal.setFrom(Info.Ctx, Value);
1998 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2001 if (Value.isMemberPointer())
2002 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2004 // Everything else is fine.
2008 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2009 // A null base expression indicates a null pointer. These are always
2010 // evaluatable, and they are false unless the offset is zero.
2011 if (!Value.getLValueBase()) {
2012 Result = !Value.getLValueOffset().isZero();
2016 // We have a non-null base. These are generally known to be true, but if it's
2017 // a weak declaration it can be null at runtime.
2019 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2020 return !Decl || !Decl->isWeak();
2023 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2024 switch (Val.getKind()) {
2025 case APValue::Uninitialized:
2028 Result = Val.getInt().getBoolValue();
2030 case APValue::Float:
2031 Result = !Val.getFloat().isZero();
2033 case APValue::ComplexInt:
2034 Result = Val.getComplexIntReal().getBoolValue() ||
2035 Val.getComplexIntImag().getBoolValue();
2037 case APValue::ComplexFloat:
2038 Result = !Val.getComplexFloatReal().isZero() ||
2039 !Val.getComplexFloatImag().isZero();
2041 case APValue::LValue:
2042 return EvalPointerValueAsBool(Val, Result);
2043 case APValue::MemberPointer:
2044 Result = Val.getMemberPointerDecl();
2046 case APValue::Vector:
2047 case APValue::Array:
2048 case APValue::Struct:
2049 case APValue::Union:
2050 case APValue::AddrLabelDiff:
2054 llvm_unreachable("unknown APValue kind");
2057 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2059 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2061 if (!Evaluate(Val, Info, E))
2063 return HandleConversionToBool(Val, Result);
2066 template<typename T>
2067 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2068 const T &SrcValue, QualType DestType) {
2069 Info.CCEDiag(E, diag::note_constexpr_overflow)
2070 << SrcValue << DestType;
2071 return Info.noteUndefinedBehavior();
2074 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2075 QualType SrcType, const APFloat &Value,
2076 QualType DestType, APSInt &Result) {
2077 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2078 // Determine whether we are converting to unsigned or signed.
2079 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2081 Result = APSInt(DestWidth, !DestSigned);
2083 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2084 & APFloat::opInvalidOp)
2085 return HandleOverflow(Info, E, Value, DestType);
2089 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2090 QualType SrcType, QualType DestType,
2092 APFloat Value = Result;
2094 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2095 APFloat::rmNearestTiesToEven, &ignored)
2096 & APFloat::opOverflow)
2097 return HandleOverflow(Info, E, Value, DestType);
2101 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2102 QualType DestType, QualType SrcType,
2103 const APSInt &Value) {
2104 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2105 // Figure out if this is a truncate, extend or noop cast.
2106 // If the input is signed, do a sign extend, noop, or truncate.
2107 APSInt Result = Value.extOrTrunc(DestWidth);
2108 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2109 if (DestType->isBooleanType())
2110 Result = Value.getBoolValue();
2114 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2115 QualType SrcType, const APSInt &Value,
2116 QualType DestType, APFloat &Result) {
2117 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2118 if (Result.convertFromAPInt(Value, Value.isSigned(),
2119 APFloat::rmNearestTiesToEven)
2120 & APFloat::opOverflow)
2121 return HandleOverflow(Info, E, Value, DestType);
2125 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2126 APValue &Value, const FieldDecl *FD) {
2127 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2129 if (!Value.isInt()) {
2130 // Trying to store a pointer-cast-to-integer into a bitfield.
2131 // FIXME: In this case, we should provide the diagnostic for casting
2132 // a pointer to an integer.
2133 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2138 APSInt &Int = Value.getInt();
2139 unsigned OldBitWidth = Int.getBitWidth();
2140 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2141 if (NewBitWidth < OldBitWidth)
2142 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2146 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2149 if (!Evaluate(SVal, Info, E))
2152 Res = SVal.getInt();
2155 if (SVal.isFloat()) {
2156 Res = SVal.getFloat().bitcastToAPInt();
2159 if (SVal.isVector()) {
2160 QualType VecTy = E->getType();
2161 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2162 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2163 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2164 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2165 Res = llvm::APInt::getNullValue(VecSize);
2166 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2167 APValue &Elt = SVal.getVectorElt(i);
2168 llvm::APInt EltAsInt;
2170 EltAsInt = Elt.getInt();
2171 } else if (Elt.isFloat()) {
2172 EltAsInt = Elt.getFloat().bitcastToAPInt();
2174 // Don't try to handle vectors of anything other than int or float
2175 // (not sure if it's possible to hit this case).
2176 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2179 unsigned BaseEltSize = EltAsInt.getBitWidth();
2181 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2183 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2187 // Give up if the input isn't an int, float, or vector. For example, we
2188 // reject "(v4i16)(intptr_t)&a".
2189 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2193 /// Perform the given integer operation, which is known to need at most BitWidth
2194 /// bits, and check for overflow in the original type (if that type was not an
2196 template<typename Operation>
2197 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2198 const APSInt &LHS, const APSInt &RHS,
2199 unsigned BitWidth, Operation Op,
2201 if (LHS.isUnsigned()) {
2202 Result = Op(LHS, RHS);
2206 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2207 Result = Value.trunc(LHS.getBitWidth());
2208 if (Result.extend(BitWidth) != Value) {
2209 if (Info.checkingForOverflow())
2210 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2211 diag::warn_integer_constant_overflow)
2212 << Result.toString(10) << E->getType();
2214 return HandleOverflow(Info, E, Value, E->getType());
2219 /// Perform the given binary integer operation.
2220 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2221 BinaryOperatorKind Opcode, APSInt RHS,
2228 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2229 std::multiplies<APSInt>(), Result);
2231 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2232 std::plus<APSInt>(), Result);
2234 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2235 std::minus<APSInt>(), Result);
2236 case BO_And: Result = LHS & RHS; return true;
2237 case BO_Xor: Result = LHS ^ RHS; return true;
2238 case BO_Or: Result = LHS | RHS; return true;
2242 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2245 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2246 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2247 // this operation and gives the two's complement result.
2248 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2249 LHS.isSigned() && LHS.isMinSignedValue())
2250 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2254 if (Info.getLangOpts().OpenCL)
2255 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2256 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2257 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2259 else if (RHS.isSigned() && RHS.isNegative()) {
2260 // During constant-folding, a negative shift is an opposite shift. Such
2261 // a shift is not a constant expression.
2262 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2267 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2268 // the shifted type.
2269 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2271 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2272 << RHS << E->getType() << LHS.getBitWidth();
2273 } else if (LHS.isSigned()) {
2274 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2275 // operand, and must not overflow the corresponding unsigned type.
2276 if (LHS.isNegative())
2277 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2278 else if (LHS.countLeadingZeros() < SA)
2279 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2285 if (Info.getLangOpts().OpenCL)
2286 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2287 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2288 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2290 else if (RHS.isSigned() && RHS.isNegative()) {
2291 // During constant-folding, a negative shift is an opposite shift. Such a
2292 // shift is not a constant expression.
2293 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2298 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2300 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2302 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2303 << RHS << E->getType() << LHS.getBitWidth();
2308 case BO_LT: Result = LHS < RHS; return true;
2309 case BO_GT: Result = LHS > RHS; return true;
2310 case BO_LE: Result = LHS <= RHS; return true;
2311 case BO_GE: Result = LHS >= RHS; return true;
2312 case BO_EQ: Result = LHS == RHS; return true;
2313 case BO_NE: Result = LHS != RHS; return true;
2315 llvm_unreachable("BO_Cmp should be handled elsewhere");
2319 /// Perform the given binary floating-point operation, in-place, on LHS.
2320 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2321 APFloat &LHS, BinaryOperatorKind Opcode,
2322 const APFloat &RHS) {
2328 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2331 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2334 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2337 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2341 if (LHS.isInfinity() || LHS.isNaN()) {
2342 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2343 return Info.noteUndefinedBehavior();
2348 /// Cast an lvalue referring to a base subobject to a derived class, by
2349 /// truncating the lvalue's path to the given length.
2350 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2351 const RecordDecl *TruncatedType,
2352 unsigned TruncatedElements) {
2353 SubobjectDesignator &D = Result.Designator;
2355 // Check we actually point to a derived class object.
2356 if (TruncatedElements == D.Entries.size())
2358 assert(TruncatedElements >= D.MostDerivedPathLength &&
2359 "not casting to a derived class");
2360 if (!Result.checkSubobject(Info, E, CSK_Derived))
2363 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2364 const RecordDecl *RD = TruncatedType;
2365 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2366 if (RD->isInvalidDecl()) return false;
2367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2368 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2369 if (isVirtualBaseClass(D.Entries[I]))
2370 Result.Offset -= Layout.getVBaseClassOffset(Base);
2372 Result.Offset -= Layout.getBaseClassOffset(Base);
2375 D.Entries.resize(TruncatedElements);
2379 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2380 const CXXRecordDecl *Derived,
2381 const CXXRecordDecl *Base,
2382 const ASTRecordLayout *RL = nullptr) {
2384 if (Derived->isInvalidDecl()) return false;
2385 RL = &Info.Ctx.getASTRecordLayout(Derived);
2388 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2389 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2393 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2394 const CXXRecordDecl *DerivedDecl,
2395 const CXXBaseSpecifier *Base) {
2396 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2398 if (!Base->isVirtual())
2399 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2401 SubobjectDesignator &D = Obj.Designator;
2405 // Extract most-derived object and corresponding type.
2406 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2407 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2410 // Find the virtual base class.
2411 if (DerivedDecl->isInvalidDecl()) return false;
2412 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2413 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2414 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2418 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2419 QualType Type, LValue &Result) {
2420 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2421 PathE = E->path_end();
2422 PathI != PathE; ++PathI) {
2423 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2426 Type = (*PathI)->getType();
2431 /// Update LVal to refer to the given field, which must be a member of the type
2432 /// currently described by LVal.
2433 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2434 const FieldDecl *FD,
2435 const ASTRecordLayout *RL = nullptr) {
2437 if (FD->getParent()->isInvalidDecl()) return false;
2438 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2441 unsigned I = FD->getFieldIndex();
2442 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2443 LVal.addDecl(Info, E, FD);
2447 /// Update LVal to refer to the given indirect field.
2448 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2450 const IndirectFieldDecl *IFD) {
2451 for (const auto *C : IFD->chain())
2452 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2457 /// Get the size of the given type in char units.
2458 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2459 QualType Type, CharUnits &Size) {
2460 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2462 if (Type->isVoidType() || Type->isFunctionType()) {
2463 Size = CharUnits::One();
2467 if (Type->isDependentType()) {
2472 if (!Type->isConstantSizeType()) {
2473 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2474 // FIXME: Better diagnostic.
2479 Size = Info.Ctx.getTypeSizeInChars(Type);
2483 /// Update a pointer value to model pointer arithmetic.
2484 /// \param Info - Information about the ongoing evaluation.
2485 /// \param E - The expression being evaluated, for diagnostic purposes.
2486 /// \param LVal - The pointer value to be updated.
2487 /// \param EltTy - The pointee type represented by LVal.
2488 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2489 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2490 LValue &LVal, QualType EltTy,
2491 APSInt Adjustment) {
2492 CharUnits SizeOfPointee;
2493 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2496 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2500 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2501 LValue &LVal, QualType EltTy,
2502 int64_t Adjustment) {
2503 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2504 APSInt::get(Adjustment));
2507 /// Update an lvalue to refer to a component of a complex number.
2508 /// \param Info - Information about the ongoing evaluation.
2509 /// \param LVal - The lvalue to be updated.
2510 /// \param EltTy - The complex number's component type.
2511 /// \param Imag - False for the real component, true for the imaginary.
2512 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2513 LValue &LVal, QualType EltTy,
2516 CharUnits SizeOfComponent;
2517 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2519 LVal.Offset += SizeOfComponent;
2521 LVal.addComplex(Info, E, EltTy, Imag);
2525 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2526 QualType Type, const LValue &LVal,
2529 /// Try to evaluate the initializer for a variable declaration.
2531 /// \param Info Information about the ongoing evaluation.
2532 /// \param E An expression to be used when printing diagnostics.
2533 /// \param VD The variable whose initializer should be obtained.
2534 /// \param Frame The frame in which the variable was created. Must be null
2535 /// if this variable is not local to the evaluation.
2536 /// \param Result Filled in with a pointer to the value of the variable.
2537 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2538 const VarDecl *VD, CallStackFrame *Frame,
2539 APValue *&Result, const LValue *LVal) {
2541 // If this is a parameter to an active constexpr function call, perform
2542 // argument substitution.
2543 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2544 // Assume arguments of a potential constant expression are unknown
2545 // constant expressions.
2546 if (Info.checkingPotentialConstantExpression())
2548 if (!Frame || !Frame->Arguments) {
2549 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2552 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2556 // If this is a local variable, dig out its value.
2558 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2559 : Frame->getCurrentTemporary(VD);
2561 // Assume variables referenced within a lambda's call operator that were
2562 // not declared within the call operator are captures and during checking
2563 // of a potential constant expression, assume they are unknown constant
2565 assert(isLambdaCallOperator(Frame->Callee) &&
2566 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2567 "missing value for local variable");
2568 if (Info.checkingPotentialConstantExpression())
2570 // FIXME: implement capture evaluation during constant expr evaluation.
2571 Info.FFDiag(E->getBeginLoc(),
2572 diag::note_unimplemented_constexpr_lambda_feature_ast)
2573 << "captures not currently allowed";
2579 // Dig out the initializer, and use the declaration which it's attached to.
2580 const Expr *Init = VD->getAnyInitializer(VD);
2581 if (!Init || Init->isValueDependent()) {
2582 // If we're checking a potential constant expression, the variable could be
2583 // initialized later.
2584 if (!Info.checkingPotentialConstantExpression())
2585 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2589 // If we're currently evaluating the initializer of this declaration, use that
2591 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2592 Result = Info.EvaluatingDeclValue;
2596 // Never evaluate the initializer of a weak variable. We can't be sure that
2597 // this is the definition which will be used.
2599 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2603 // Check that we can fold the initializer. In C++, we will have already done
2604 // this in the cases where it matters for conformance.
2605 SmallVector<PartialDiagnosticAt, 8> Notes;
2606 if (!VD->evaluateValue(Notes)) {
2607 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2608 Notes.size() + 1) << VD;
2609 Info.Note(VD->getLocation(), diag::note_declared_at);
2610 Info.addNotes(Notes);
2612 } else if (!VD->checkInitIsICE()) {
2613 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2614 Notes.size() + 1) << VD;
2615 Info.Note(VD->getLocation(), diag::note_declared_at);
2616 Info.addNotes(Notes);
2619 Result = VD->getEvaluatedValue();
2623 static bool IsConstNonVolatile(QualType T) {
2624 Qualifiers Quals = T.getQualifiers();
2625 return Quals.hasConst() && !Quals.hasVolatile();
2628 /// Get the base index of the given base class within an APValue representing
2629 /// the given derived class.
2630 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2631 const CXXRecordDecl *Base) {
2632 Base = Base->getCanonicalDecl();
2634 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2635 E = Derived->bases_end(); I != E; ++I, ++Index) {
2636 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2640 llvm_unreachable("base class missing from derived class's bases list");
2643 /// Extract the value of a character from a string literal.
2644 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2646 // FIXME: Support MakeStringConstant
2647 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2649 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2650 assert(Index <= Str.size() && "Index too large");
2651 return APSInt::getUnsigned(Str.c_str()[Index]);
2654 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2655 Lit = PE->getFunctionName();
2656 const StringLiteral *S = cast<StringLiteral>(Lit);
2657 const ConstantArrayType *CAT =
2658 Info.Ctx.getAsConstantArrayType(S->getType());
2659 assert(CAT && "string literal isn't an array");
2660 QualType CharType = CAT->getElementType();
2661 assert(CharType->isIntegerType() && "unexpected character type");
2663 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2664 CharType->isUnsignedIntegerType());
2665 if (Index < S->getLength())
2666 Value = S->getCodeUnit(Index);
2670 // Expand a string literal into an array of characters.
2671 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2673 const StringLiteral *S = cast<StringLiteral>(Lit);
2674 const ConstantArrayType *CAT =
2675 Info.Ctx.getAsConstantArrayType(S->getType());
2676 assert(CAT && "string literal isn't an array");
2677 QualType CharType = CAT->getElementType();
2678 assert(CharType->isIntegerType() && "unexpected character type");
2680 unsigned Elts = CAT->getSize().getZExtValue();
2681 Result = APValue(APValue::UninitArray(),
2682 std::min(S->getLength(), Elts), Elts);
2683 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2684 CharType->isUnsignedIntegerType());
2685 if (Result.hasArrayFiller())
2686 Result.getArrayFiller() = APValue(Value);
2687 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2688 Value = S->getCodeUnit(I);
2689 Result.getArrayInitializedElt(I) = APValue(Value);
2693 // Expand an array so that it has more than Index filled elements.
2694 static void expandArray(APValue &Array, unsigned Index) {
2695 unsigned Size = Array.getArraySize();
2696 assert(Index < Size);
2698 // Always at least double the number of elements for which we store a value.
2699 unsigned OldElts = Array.getArrayInitializedElts();
2700 unsigned NewElts = std::max(Index+1, OldElts * 2);
2701 NewElts = std::min(Size, std::max(NewElts, 8u));
2703 // Copy the data across.
2704 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2705 for (unsigned I = 0; I != OldElts; ++I)
2706 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2707 for (unsigned I = OldElts; I != NewElts; ++I)
2708 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2709 if (NewValue.hasArrayFiller())
2710 NewValue.getArrayFiller() = Array.getArrayFiller();
2711 Array.swap(NewValue);
2714 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2715 /// conversion. If it's of class type, we may assume that the copy operation
2716 /// is trivial. Note that this is never true for a union type with fields
2717 /// (because the copy always "reads" the active member) and always true for
2718 /// a non-class type.
2719 static bool isReadByLvalueToRvalueConversion(QualType T) {
2720 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2721 if (!RD || (RD->isUnion() && !RD->field_empty()))
2726 for (auto *Field : RD->fields())
2727 if (isReadByLvalueToRvalueConversion(Field->getType()))
2730 for (auto &BaseSpec : RD->bases())
2731 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2737 /// Diagnose an attempt to read from any unreadable field within the specified
2738 /// type, which might be a class type.
2739 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2741 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2745 if (!RD->hasMutableFields())
2748 for (auto *Field : RD->fields()) {
2749 // If we're actually going to read this field in some way, then it can't
2750 // be mutable. If we're in a union, then assigning to a mutable field
2751 // (even an empty one) can change the active member, so that's not OK.
2752 // FIXME: Add core issue number for the union case.
2753 if (Field->isMutable() &&
2754 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2755 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2756 Info.Note(Field->getLocation(), diag::note_declared_at);
2760 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2764 for (auto &BaseSpec : RD->bases())
2765 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2768 // All mutable fields were empty, and thus not actually read.
2773 /// A handle to a complete object (an object that is not a subobject of
2774 /// another object).
2775 struct CompleteObject {
2776 /// The value of the complete object.
2778 /// The type of the complete object.
2780 bool LifetimeStartedInEvaluation;
2782 CompleteObject() : Value(nullptr) {}
2783 CompleteObject(APValue *Value, QualType Type,
2784 bool LifetimeStartedInEvaluation)
2785 : Value(Value), Type(Type),
2786 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2787 assert(Value && "missing value for complete object");
2790 explicit operator bool() const { return Value; }
2792 } // end anonymous namespace
2794 /// Find the designated sub-object of an rvalue.
2795 template<typename SubobjectHandler>
2796 typename SubobjectHandler::result_type
2797 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2798 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2800 // A diagnostic will have already been produced.
2801 return handler.failed();
2802 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2803 if (Info.getLangOpts().CPlusPlus11)
2804 Info.FFDiag(E, Sub.isOnePastTheEnd()
2805 ? diag::note_constexpr_access_past_end
2806 : diag::note_constexpr_access_unsized_array)
2807 << handler.AccessKind;
2810 return handler.failed();
2813 APValue *O = Obj.Value;
2814 QualType ObjType = Obj.Type;
2815 const FieldDecl *LastField = nullptr;
2816 const bool MayReadMutableMembers =
2817 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2819 // Walk the designator's path to find the subobject.
2820 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2821 if (O->isUninit()) {
2822 if (!Info.checkingPotentialConstantExpression())
2823 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2824 return handler.failed();
2828 // If we are reading an object of class type, there may still be more
2829 // things we need to check: if there are any mutable subobjects, we
2830 // cannot perform this read. (This only happens when performing a trivial
2831 // copy or assignment.)
2832 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2833 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2834 return handler.failed();
2836 if (!handler.found(*O, ObjType))
2839 // If we modified a bit-field, truncate it to the right width.
2840 if (handler.AccessKind != AK_Read &&
2841 LastField && LastField->isBitField() &&
2842 !truncateBitfieldValue(Info, E, *O, LastField))
2848 LastField = nullptr;
2849 if (ObjType->isArrayType()) {
2850 // Next subobject is an array element.
2851 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2852 assert(CAT && "vla in literal type?");
2853 uint64_t Index = Sub.Entries[I].ArrayIndex;
2854 if (CAT->getSize().ule(Index)) {
2855 // Note, it should not be possible to form a pointer with a valid
2856 // designator which points more than one past the end of the array.
2857 if (Info.getLangOpts().CPlusPlus11)
2858 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2859 << handler.AccessKind;
2862 return handler.failed();
2865 ObjType = CAT->getElementType();
2867 // An array object is represented as either an Array APValue or as an
2868 // LValue which refers to a string literal.
2869 if (O->isLValue()) {
2870 assert(I == N - 1 && "extracting subobject of character?");
2871 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2872 if (handler.AccessKind != AK_Read)
2873 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2876 return handler.foundString(*O, ObjType, Index);
2879 if (O->getArrayInitializedElts() > Index)
2880 O = &O->getArrayInitializedElt(Index);
2881 else if (handler.AccessKind != AK_Read) {
2882 expandArray(*O, Index);
2883 O = &O->getArrayInitializedElt(Index);
2885 O = &O->getArrayFiller();
2886 } else if (ObjType->isAnyComplexType()) {
2887 // Next subobject is a complex number.
2888 uint64_t Index = Sub.Entries[I].ArrayIndex;
2890 if (Info.getLangOpts().CPlusPlus11)
2891 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2892 << handler.AccessKind;
2895 return handler.failed();
2898 bool WasConstQualified = ObjType.isConstQualified();
2899 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2900 if (WasConstQualified)
2903 assert(I == N - 1 && "extracting subobject of scalar?");
2904 if (O->isComplexInt()) {
2905 return handler.found(Index ? O->getComplexIntImag()
2906 : O->getComplexIntReal(), ObjType);
2908 assert(O->isComplexFloat());
2909 return handler.found(Index ? O->getComplexFloatImag()
2910 : O->getComplexFloatReal(), ObjType);
2912 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2913 // In C++14 onwards, it is permitted to read a mutable member whose
2914 // lifetime began within the evaluation.
2915 // FIXME: Should we also allow this in C++11?
2916 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2917 !MayReadMutableMembers) {
2918 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2920 Info.Note(Field->getLocation(), diag::note_declared_at);
2921 return handler.failed();
2924 // Next subobject is a class, struct or union field.
2925 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2926 if (RD->isUnion()) {
2927 const FieldDecl *UnionField = O->getUnionField();
2929 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2930 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2931 << handler.AccessKind << Field << !UnionField << UnionField;
2932 return handler.failed();
2934 O = &O->getUnionValue();
2936 O = &O->getStructField(Field->getFieldIndex());
2938 bool WasConstQualified = ObjType.isConstQualified();
2939 ObjType = Field->getType();
2940 if (WasConstQualified && !Field->isMutable())
2943 if (ObjType.isVolatileQualified()) {
2944 if (Info.getLangOpts().CPlusPlus) {
2945 // FIXME: Include a description of the path to the volatile subobject.
2946 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2947 << handler.AccessKind << 2 << Field;
2948 Info.Note(Field->getLocation(), diag::note_declared_at);
2950 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2952 return handler.failed();
2957 // Next subobject is a base class.
2958 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2959 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2960 O = &O->getStructBase(getBaseIndex(Derived, Base));
2962 bool WasConstQualified = ObjType.isConstQualified();
2963 ObjType = Info.Ctx.getRecordType(Base);
2964 if (WasConstQualified)
2971 struct ExtractSubobjectHandler {
2975 static const AccessKinds AccessKind = AK_Read;
2977 typedef bool result_type;
2978 bool failed() { return false; }
2979 bool found(APValue &Subobj, QualType SubobjType) {
2983 bool found(APSInt &Value, QualType SubobjType) {
2984 Result = APValue(Value);
2987 bool found(APFloat &Value, QualType SubobjType) {
2988 Result = APValue(Value);
2991 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2992 Result = APValue(extractStringLiteralCharacter(
2993 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2997 } // end anonymous namespace
2999 const AccessKinds ExtractSubobjectHandler::AccessKind;
3001 /// Extract the designated sub-object of an rvalue.
3002 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3003 const CompleteObject &Obj,
3004 const SubobjectDesignator &Sub,
3006 ExtractSubobjectHandler Handler = { Info, Result };
3007 return findSubobject(Info, E, Obj, Sub, Handler);
3011 struct ModifySubobjectHandler {
3016 typedef bool result_type;
3017 static const AccessKinds AccessKind = AK_Assign;
3019 bool checkConst(QualType QT) {
3020 // Assigning to a const object has undefined behavior.
3021 if (QT.isConstQualified()) {
3022 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3028 bool failed() { return false; }
3029 bool found(APValue &Subobj, QualType SubobjType) {
3030 if (!checkConst(SubobjType))
3032 // We've been given ownership of NewVal, so just swap it in.
3033 Subobj.swap(NewVal);
3036 bool found(APSInt &Value, QualType SubobjType) {
3037 if (!checkConst(SubobjType))
3039 if (!NewVal.isInt()) {
3040 // Maybe trying to write a cast pointer value into a complex?
3044 Value = NewVal.getInt();
3047 bool found(APFloat &Value, QualType SubobjType) {
3048 if (!checkConst(SubobjType))
3050 Value = NewVal.getFloat();
3053 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3054 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3057 } // end anonymous namespace
3059 const AccessKinds ModifySubobjectHandler::AccessKind;
3061 /// Update the designated sub-object of an rvalue to the given value.
3062 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3063 const CompleteObject &Obj,
3064 const SubobjectDesignator &Sub,
3066 ModifySubobjectHandler Handler = { Info, NewVal, E };
3067 return findSubobject(Info, E, Obj, Sub, Handler);
3070 /// Find the position where two subobject designators diverge, or equivalently
3071 /// the length of the common initial subsequence.
3072 static unsigned FindDesignatorMismatch(QualType ObjType,
3073 const SubobjectDesignator &A,
3074 const SubobjectDesignator &B,
3075 bool &WasArrayIndex) {
3076 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3077 for (/**/; I != N; ++I) {
3078 if (!ObjType.isNull() &&
3079 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3080 // Next subobject is an array element.
3081 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3082 WasArrayIndex = true;
3085 if (ObjType->isAnyComplexType())
3086 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3088 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3090 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3091 WasArrayIndex = false;
3094 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3095 // Next subobject is a field.
3096 ObjType = FD->getType();
3098 // Next subobject is a base class.
3099 ObjType = QualType();
3102 WasArrayIndex = false;
3106 /// Determine whether the given subobject designators refer to elements of the
3107 /// same array object.
3108 static bool AreElementsOfSameArray(QualType ObjType,
3109 const SubobjectDesignator &A,
3110 const SubobjectDesignator &B) {
3111 if (A.Entries.size() != B.Entries.size())
3114 bool IsArray = A.MostDerivedIsArrayElement;
3115 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3116 // A is a subobject of the array element.
3119 // If A (and B) designates an array element, the last entry will be the array
3120 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3121 // of length 1' case, and the entire path must match.
3123 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3124 return CommonLength >= A.Entries.size() - IsArray;
3127 /// Find the complete object to which an LValue refers.
3128 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3129 AccessKinds AK, const LValue &LVal,
3130 QualType LValType) {
3132 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3133 return CompleteObject();
3136 CallStackFrame *Frame = nullptr;
3137 if (LVal.getLValueCallIndex()) {
3138 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3140 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3141 << AK << LVal.Base.is<const ValueDecl*>();
3142 NoteLValueLocation(Info, LVal.Base);
3143 return CompleteObject();
3147 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3148 // is not a constant expression (even if the object is non-volatile). We also
3149 // apply this rule to C++98, in order to conform to the expected 'volatile'
3151 if (LValType.isVolatileQualified()) {
3152 if (Info.getLangOpts().CPlusPlus)
3153 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3157 return CompleteObject();
3160 // Compute value storage location and type of base object.
3161 APValue *BaseVal = nullptr;
3162 QualType BaseType = getType(LVal.Base);
3163 bool LifetimeStartedInEvaluation = Frame;
3165 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3166 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3167 // In C++11, constexpr, non-volatile variables initialized with constant
3168 // expressions are constant expressions too. Inside constexpr functions,
3169 // parameters are constant expressions even if they're non-const.
3170 // In C++1y, objects local to a constant expression (those with a Frame) are
3171 // both readable and writable inside constant expressions.
3172 // In C, such things can also be folded, although they are not ICEs.
3173 const VarDecl *VD = dyn_cast<VarDecl>(D);
3175 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3178 if (!VD || VD->isInvalidDecl()) {
3180 return CompleteObject();
3183 // Accesses of volatile-qualified objects are not allowed.
3184 if (BaseType.isVolatileQualified()) {
3185 if (Info.getLangOpts().CPlusPlus) {
3186 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3188 Info.Note(VD->getLocation(), diag::note_declared_at);
3192 return CompleteObject();
3195 // Unless we're looking at a local variable or argument in a constexpr call,
3196 // the variable we're reading must be const.
3198 if (Info.getLangOpts().CPlusPlus14 &&
3199 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3200 // OK, we can read and modify an object if we're in the process of
3201 // evaluating its initializer, because its lifetime began in this
3203 } else if (AK != AK_Read) {
3204 // All the remaining cases only permit reading.
3205 Info.FFDiag(E, diag::note_constexpr_modify_global);
3206 return CompleteObject();
3207 } else if (VD->isConstexpr()) {
3208 // OK, we can read this variable.
3209 } else if (BaseType->isIntegralOrEnumerationType()) {
3210 // In OpenCL if a variable is in constant address space it is a const value.
3211 if (!(BaseType.isConstQualified() ||
3212 (Info.getLangOpts().OpenCL &&
3213 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3214 if (Info.getLangOpts().CPlusPlus) {
3215 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3216 Info.Note(VD->getLocation(), diag::note_declared_at);
3220 return CompleteObject();
3222 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3223 // We support folding of const floating-point types, in order to make
3224 // static const data members of such types (supported as an extension)
3226 if (Info.getLangOpts().CPlusPlus11) {
3227 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3228 Info.Note(VD->getLocation(), diag::note_declared_at);
3232 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3233 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3234 // Keep evaluating to see what we can do.
3236 // FIXME: Allow folding of values of any literal type in all languages.
3237 if (Info.checkingPotentialConstantExpression() &&
3238 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3239 // The definition of this variable could be constexpr. We can't
3240 // access it right now, but may be able to in future.
3241 } else if (Info.getLangOpts().CPlusPlus11) {
3242 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3243 Info.Note(VD->getLocation(), diag::note_declared_at);
3247 return CompleteObject();
3251 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3252 return CompleteObject();
3254 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3257 if (const MaterializeTemporaryExpr *MTE =
3258 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3259 assert(MTE->getStorageDuration() == SD_Static &&
3260 "should have a frame for a non-global materialized temporary");
3262 // Per C++1y [expr.const]p2:
3263 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3264 // - a [...] glvalue of integral or enumeration type that refers to
3265 // a non-volatile const object [...]
3267 // - a [...] glvalue of literal type that refers to a non-volatile
3268 // object whose lifetime began within the evaluation of e.
3270 // C++11 misses the 'began within the evaluation of e' check and
3271 // instead allows all temporaries, including things like:
3274 // constexpr int k = r;
3275 // Therefore we use the C++14 rules in C++11 too.
3276 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3277 const ValueDecl *ED = MTE->getExtendingDecl();
3278 if (!(BaseType.isConstQualified() &&
3279 BaseType->isIntegralOrEnumerationType()) &&
3280 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3281 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3282 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3283 return CompleteObject();
3286 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3287 assert(BaseVal && "got reference to unevaluated temporary");
3288 LifetimeStartedInEvaluation = true;
3291 return CompleteObject();
3294 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3295 assert(BaseVal && "missing value for temporary");
3298 // Volatile temporary objects cannot be accessed in constant expressions.
3299 if (BaseType.isVolatileQualified()) {
3300 if (Info.getLangOpts().CPlusPlus) {
3301 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3303 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3307 return CompleteObject();
3311 // During the construction of an object, it is not yet 'const'.
3312 // FIXME: This doesn't do quite the right thing for const subobjects of the
3313 // object under construction.
3314 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3315 LVal.getLValueCallIndex(),
3316 LVal.getLValueVersion())) {
3317 BaseType = Info.Ctx.getCanonicalType(BaseType);
3318 BaseType.removeLocalConst();
3319 LifetimeStartedInEvaluation = true;
3322 // In C++14, we can't safely access any mutable state when we might be
3323 // evaluating after an unmodeled side effect.
3325 // FIXME: Not all local state is mutable. Allow local constant subobjects
3326 // to be read here (but take care with 'mutable' fields).
3327 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3328 Info.EvalStatus.HasSideEffects) ||
3329 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3330 return CompleteObject();
3332 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3335 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3336 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3337 /// glvalue referred to by an entity of reference type.
3339 /// \param Info - Information about the ongoing evaluation.
3340 /// \param Conv - The expression for which we are performing the conversion.
3341 /// Used for diagnostics.
3342 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3343 /// case of a non-class type).
3344 /// \param LVal - The glvalue on which we are attempting to perform this action.
3345 /// \param RVal - The produced value will be placed here.
3346 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3348 const LValue &LVal, APValue &RVal) {
3349 if (LVal.Designator.Invalid)
3352 // Check for special cases where there is no existing APValue to look at.
3353 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3354 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3355 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3356 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3357 // initializer until now for such expressions. Such an expression can't be
3358 // an ICE in C, so this only matters for fold.
3359 if (Type.isVolatileQualified()) {
3364 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3366 CompleteObject LitObj(&Lit, Base->getType(), false);
3367 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3368 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3369 // We represent a string literal array as an lvalue pointing at the
3370 // corresponding expression, rather than building an array of chars.
3371 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3372 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3373 CompleteObject StrObj(&Str, Base->getType(), false);
3374 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3378 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3379 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3382 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3383 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3384 QualType LValType, APValue &Val) {
3385 if (LVal.Designator.Invalid)
3388 if (!Info.getLangOpts().CPlusPlus14) {
3393 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3394 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3398 struct CompoundAssignSubobjectHandler {
3401 QualType PromotedLHSType;
3402 BinaryOperatorKind Opcode;
3405 static const AccessKinds AccessKind = AK_Assign;
3407 typedef bool result_type;
3409 bool checkConst(QualType QT) {
3410 // Assigning to a const object has undefined behavior.
3411 if (QT.isConstQualified()) {
3412 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3418 bool failed() { return false; }
3419 bool found(APValue &Subobj, QualType SubobjType) {
3420 switch (Subobj.getKind()) {
3422 return found(Subobj.getInt(), SubobjType);
3423 case APValue::Float:
3424 return found(Subobj.getFloat(), SubobjType);
3425 case APValue::ComplexInt:
3426 case APValue::ComplexFloat:
3427 // FIXME: Implement complex compound assignment.
3430 case APValue::LValue:
3431 return foundPointer(Subobj, SubobjType);
3433 // FIXME: can this happen?
3438 bool found(APSInt &Value, QualType SubobjType) {
3439 if (!checkConst(SubobjType))
3442 if (!SubobjType->isIntegerType()) {
3443 // We don't support compound assignment on integer-cast-to-pointer
3451 HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3452 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3454 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3456 } else if (RHS.isFloat()) {
3457 APFloat FValue(0.0);
3458 return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3460 handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3461 HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3468 bool found(APFloat &Value, QualType SubobjType) {
3469 return checkConst(SubobjType) &&
3470 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3472 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3473 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3475 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3476 if (!checkConst(SubobjType))
3479 QualType PointeeType;
3480 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3481 PointeeType = PT->getPointeeType();
3483 if (PointeeType.isNull() || !RHS.isInt() ||
3484 (Opcode != BO_Add && Opcode != BO_Sub)) {
3489 APSInt Offset = RHS.getInt();
3490 if (Opcode == BO_Sub)
3491 negateAsSigned(Offset);
3494 LVal.setFrom(Info.Ctx, Subobj);
3495 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3497 LVal.moveInto(Subobj);
3500 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3501 llvm_unreachable("shouldn't encounter string elements here");
3504 } // end anonymous namespace
3506 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3508 /// Perform a compound assignment of LVal <op>= RVal.
3509 static bool handleCompoundAssignment(
3510 EvalInfo &Info, const Expr *E,
3511 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3512 BinaryOperatorKind Opcode, const APValue &RVal) {
3513 if (LVal.Designator.Invalid)
3516 if (!Info.getLangOpts().CPlusPlus14) {
3521 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3522 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3524 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3528 struct IncDecSubobjectHandler {
3530 const UnaryOperator *E;
3531 AccessKinds AccessKind;
3534 typedef bool result_type;
3536 bool checkConst(QualType QT) {
3537 // Assigning to a const object has undefined behavior.
3538 if (QT.isConstQualified()) {
3539 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3545 bool failed() { return false; }
3546 bool found(APValue &Subobj, QualType SubobjType) {
3547 // Stash the old value. Also clear Old, so we don't clobber it later
3548 // if we're post-incrementing a complex.
3554 switch (Subobj.getKind()) {
3556 return found(Subobj.getInt(), SubobjType);
3557 case APValue::Float:
3558 return found(Subobj.getFloat(), SubobjType);
3559 case APValue::ComplexInt:
3560 return found(Subobj.getComplexIntReal(),
3561 SubobjType->castAs<ComplexType>()->getElementType()
3562 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3563 case APValue::ComplexFloat:
3564 return found(Subobj.getComplexFloatReal(),
3565 SubobjType->castAs<ComplexType>()->getElementType()
3566 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3567 case APValue::LValue:
3568 return foundPointer(Subobj, SubobjType);
3570 // FIXME: can this happen?
3575 bool found(APSInt &Value, QualType SubobjType) {
3576 if (!checkConst(SubobjType))
3579 if (!SubobjType->isIntegerType()) {
3580 // We don't support increment / decrement on integer-cast-to-pointer
3586 if (Old) *Old = APValue(Value);
3588 // bool arithmetic promotes to int, and the conversion back to bool
3589 // doesn't reduce mod 2^n, so special-case it.
3590 if (SubobjType->isBooleanType()) {
3591 if (AccessKind == AK_Increment)
3598 bool WasNegative = Value.isNegative();
3599 if (AccessKind == AK_Increment) {
3602 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3603 APSInt ActualValue(Value, /*IsUnsigned*/true);
3604 return HandleOverflow(Info, E, ActualValue, SubobjType);
3609 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3610 unsigned BitWidth = Value.getBitWidth();
3611 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3612 ActualValue.setBit(BitWidth);
3613 return HandleOverflow(Info, E, ActualValue, SubobjType);
3618 bool found(APFloat &Value, QualType SubobjType) {
3619 if (!checkConst(SubobjType))
3622 if (Old) *Old = APValue(Value);
3624 APFloat One(Value.getSemantics(), 1);
3625 if (AccessKind == AK_Increment)
3626 Value.add(One, APFloat::rmNearestTiesToEven);
3628 Value.subtract(One, APFloat::rmNearestTiesToEven);
3631 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3632 if (!checkConst(SubobjType))
3635 QualType PointeeType;
3636 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3637 PointeeType = PT->getPointeeType();
3644 LVal.setFrom(Info.Ctx, Subobj);
3645 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3646 AccessKind == AK_Increment ? 1 : -1))
3648 LVal.moveInto(Subobj);
3651 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3652 llvm_unreachable("shouldn't encounter string elements here");
3655 } // end anonymous namespace
3657 /// Perform an increment or decrement on LVal.
3658 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3659 QualType LValType, bool IsIncrement, APValue *Old) {
3660 if (LVal.Designator.Invalid)
3663 if (!Info.getLangOpts().CPlusPlus14) {
3668 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3669 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3670 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3671 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3674 /// Build an lvalue for the object argument of a member function call.
3675 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3677 if (Object->getType()->isPointerType())
3678 return EvaluatePointer(Object, This, Info);
3680 if (Object->isGLValue())
3681 return EvaluateLValue(Object, This, Info);
3683 if (Object->getType()->isLiteralType(Info.Ctx))
3684 return EvaluateTemporary(Object, This, Info);
3686 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3690 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3691 /// lvalue referring to the result.
3693 /// \param Info - Information about the ongoing evaluation.
3694 /// \param LV - An lvalue referring to the base of the member pointer.
3695 /// \param RHS - The member pointer expression.
3696 /// \param IncludeMember - Specifies whether the member itself is included in
3697 /// the resulting LValue subobject designator. This is not possible when
3698 /// creating a bound member function.
3699 /// \return The field or method declaration to which the member pointer refers,
3700 /// or 0 if evaluation fails.
3701 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3705 bool IncludeMember = true) {
3707 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3710 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3711 // member value, the behavior is undefined.
3712 if (!MemPtr.getDecl()) {
3713 // FIXME: Specific diagnostic.
3718 if (MemPtr.isDerivedMember()) {
3719 // This is a member of some derived class. Truncate LV appropriately.
3720 // The end of the derived-to-base path for the base object must match the
3721 // derived-to-base path for the member pointer.
3722 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3723 LV.Designator.Entries.size()) {
3727 unsigned PathLengthToMember =
3728 LV.Designator.Entries.size() - MemPtr.Path.size();
3729 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3730 const CXXRecordDecl *LVDecl = getAsBaseClass(
3731 LV.Designator.Entries[PathLengthToMember + I]);
3732 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3733 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3739 // Truncate the lvalue to the appropriate derived class.
3740 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3741 PathLengthToMember))
3743 } else if (!MemPtr.Path.empty()) {
3744 // Extend the LValue path with the member pointer's path.
3745 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3746 MemPtr.Path.size() + IncludeMember);
3748 // Walk down to the appropriate base class.
3749 if (const PointerType *PT = LVType->getAs<PointerType>())
3750 LVType = PT->getPointeeType();
3751 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3752 assert(RD && "member pointer access on non-class-type expression");
3753 // The first class in the path is that of the lvalue.
3754 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3755 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3756 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3760 // Finally cast to the class containing the member.
3761 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3762 MemPtr.getContainingRecord()))
3766 // Add the member. Note that we cannot build bound member functions here.
3767 if (IncludeMember) {
3768 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3769 if (!HandleLValueMember(Info, RHS, LV, FD))
3771 } else if (const IndirectFieldDecl *IFD =
3772 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3773 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3776 llvm_unreachable("can't construct reference to bound member function");
3780 return MemPtr.getDecl();
3783 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3784 const BinaryOperator *BO,
3786 bool IncludeMember = true) {
3787 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3789 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3790 if (Info.noteFailure()) {
3792 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3797 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3798 BO->getRHS(), IncludeMember);
3801 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3802 /// the provided lvalue, which currently refers to the base object.
3803 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3805 SubobjectDesignator &D = Result.Designator;
3806 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3809 QualType TargetQT = E->getType();
3810 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3811 TargetQT = PT->getPointeeType();
3813 // Check this cast lands within the final derived-to-base subobject path.
3814 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3815 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3816 << D.MostDerivedType << TargetQT;
3820 // Check the type of the final cast. We don't need to check the path,
3821 // since a cast can only be formed if the path is unique.
3822 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3823 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3824 const CXXRecordDecl *FinalType;
3825 if (NewEntriesSize == D.MostDerivedPathLength)
3826 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3828 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3829 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3830 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3831 << D.MostDerivedType << TargetQT;
3835 // Truncate the lvalue to the appropriate derived class.
3836 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3840 enum EvalStmtResult {
3841 /// Evaluation failed.
3843 /// Hit a 'return' statement.
3845 /// Evaluation succeeded.
3847 /// Hit a 'continue' statement.
3849 /// Hit a 'break' statement.
3851 /// Still scanning for 'case' or 'default' statement.
3856 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3857 // We don't need to evaluate the initializer for a static local.
3858 if (!VD->hasLocalStorage())
3862 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3864 const Expr *InitE = VD->getInit();
3866 Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3867 << false << VD->getType();
3872 if (InitE->isValueDependent())
3875 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3876 // Wipe out any partially-computed value, to allow tracking that this
3877 // evaluation failed.
3885 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3888 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3889 OK &= EvaluateVarDecl(Info, VD);
3891 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3892 for (auto *BD : DD->bindings())
3893 if (auto *VD = BD->getHoldingVar())
3894 OK &= EvaluateDecl(Info, VD);
3900 /// Evaluate a condition (either a variable declaration or an expression).
3901 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3902 const Expr *Cond, bool &Result) {
3903 FullExpressionRAII Scope(Info);
3904 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3906 return EvaluateAsBooleanCondition(Cond, Result, Info);
3910 /// A location where the result (returned value) of evaluating a
3911 /// statement should be stored.
3913 /// The APValue that should be filled in with the returned value.
3915 /// The location containing the result, if any (used to support RVO).
3919 struct TempVersionRAII {
3920 CallStackFrame &Frame;
3922 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3923 Frame.pushTempVersion();
3926 ~TempVersionRAII() {
3927 Frame.popTempVersion();
3933 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3935 const SwitchCase *SC = nullptr);
3937 /// Evaluate the body of a loop, and translate the result as appropriate.
3938 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3940 const SwitchCase *Case = nullptr) {
3941 BlockScopeRAII Scope(Info);
3942 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3944 return ESR_Succeeded;
3947 return ESR_Continue;
3950 case ESR_CaseNotFound:
3953 llvm_unreachable("Invalid EvalStmtResult!");
3956 /// Evaluate a switch statement.
3957 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3958 const SwitchStmt *SS) {
3959 BlockScopeRAII Scope(Info);
3961 // Evaluate the switch condition.
3964 FullExpressionRAII Scope(Info);
3965 if (const Stmt *Init = SS->getInit()) {
3966 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3967 if (ESR != ESR_Succeeded)
3970 if (SS->getConditionVariable() &&
3971 !EvaluateDecl(Info, SS->getConditionVariable()))
3973 if (!EvaluateInteger(SS->getCond(), Value, Info))
3977 // Find the switch case corresponding to the value of the condition.
3978 // FIXME: Cache this lookup.
3979 const SwitchCase *Found = nullptr;
3980 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3981 SC = SC->getNextSwitchCase()) {
3982 if (isa<DefaultStmt>(SC)) {
3987 const CaseStmt *CS = cast<CaseStmt>(SC);
3988 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3989 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3991 if (LHS <= Value && Value <= RHS) {
3998 return ESR_Succeeded;
4000 // Search the switch body for the switch case and evaluate it from there.
4001 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4003 return ESR_Succeeded;
4009 case ESR_CaseNotFound:
4010 // This can only happen if the switch case is nested within a statement
4011 // expression. We have no intention of supporting that.
4012 Info.FFDiag(Found->getBeginLoc(),
4013 diag::note_constexpr_stmt_expr_unsupported);
4016 llvm_unreachable("Invalid EvalStmtResult!");
4019 // Evaluate a statement.
4020 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4021 const Stmt *S, const SwitchCase *Case) {
4022 if (!Info.nextStep(S))
4025 // If we're hunting down a 'case' or 'default' label, recurse through
4026 // substatements until we hit the label.
4028 // FIXME: We don't start the lifetime of objects whose initialization we
4029 // jump over. However, such objects must be of class type with a trivial
4030 // default constructor that initialize all subobjects, so must be empty,
4031 // so this almost never matters.
4032 switch (S->getStmtClass()) {
4033 case Stmt::CompoundStmtClass:
4034 // FIXME: Precompute which substatement of a compound statement we
4035 // would jump to, and go straight there rather than performing a
4036 // linear scan each time.
4037 case Stmt::LabelStmtClass:
4038 case Stmt::AttributedStmtClass:
4039 case Stmt::DoStmtClass:
4042 case Stmt::CaseStmtClass:
4043 case Stmt::DefaultStmtClass:
4048 case Stmt::IfStmtClass: {
4049 // FIXME: Precompute which side of an 'if' we would jump to, and go
4050 // straight there rather than scanning both sides.
4051 const IfStmt *IS = cast<IfStmt>(S);
4053 // Wrap the evaluation in a block scope, in case it's a DeclStmt
4054 // preceded by our switch label.
4055 BlockScopeRAII Scope(Info);
4057 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4058 if (ESR != ESR_CaseNotFound || !IS->getElse())
4060 return EvaluateStmt(Result, Info, IS->getElse(), Case);
4063 case Stmt::WhileStmtClass: {
4064 EvalStmtResult ESR =
4065 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4066 if (ESR != ESR_Continue)
4071 case Stmt::ForStmtClass: {
4072 const ForStmt *FS = cast<ForStmt>(S);
4073 EvalStmtResult ESR =
4074 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4075 if (ESR != ESR_Continue)
4078 FullExpressionRAII IncScope(Info);
4079 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4085 case Stmt::DeclStmtClass:
4086 // FIXME: If the variable has initialization that can't be jumped over,
4087 // bail out of any immediately-surrounding compound-statement too.
4089 return ESR_CaseNotFound;
4093 switch (S->getStmtClass()) {
4095 if (const Expr *E = dyn_cast<Expr>(S)) {
4096 // Don't bother evaluating beyond an expression-statement which couldn't
4098 FullExpressionRAII Scope(Info);
4099 if (!EvaluateIgnoredValue(Info, E))
4101 return ESR_Succeeded;
4104 Info.FFDiag(S->getBeginLoc());
4107 case Stmt::NullStmtClass:
4108 return ESR_Succeeded;
4110 case Stmt::DeclStmtClass: {
4111 const DeclStmt *DS = cast<DeclStmt>(S);
4112 for (const auto *DclIt : DS->decls()) {
4113 // Each declaration initialization is its own full-expression.
4114 // FIXME: This isn't quite right; if we're performing aggregate
4115 // initialization, each braced subexpression is its own full-expression.
4116 FullExpressionRAII Scope(Info);
4117 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4120 return ESR_Succeeded;
4123 case Stmt::ReturnStmtClass: {
4124 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4125 FullExpressionRAII Scope(Info);
4128 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4129 : Evaluate(Result.Value, Info, RetExpr)))
4131 return ESR_Returned;
4134 case Stmt::CompoundStmtClass: {
4135 BlockScopeRAII Scope(Info);
4137 const CompoundStmt *CS = cast<CompoundStmt>(S);
4138 for (const auto *BI : CS->body()) {
4139 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4140 if (ESR == ESR_Succeeded)
4142 else if (ESR != ESR_CaseNotFound)
4145 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4148 case Stmt::IfStmtClass: {
4149 const IfStmt *IS = cast<IfStmt>(S);
4151 // Evaluate the condition, as either a var decl or as an expression.
4152 BlockScopeRAII Scope(Info);
4153 if (const Stmt *Init = IS->getInit()) {
4154 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4155 if (ESR != ESR_Succeeded)
4159 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4162 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4163 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4164 if (ESR != ESR_Succeeded)
4167 return ESR_Succeeded;
4170 case Stmt::WhileStmtClass: {
4171 const WhileStmt *WS = cast<WhileStmt>(S);
4173 BlockScopeRAII Scope(Info);
4175 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4181 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4182 if (ESR != ESR_Continue)
4185 return ESR_Succeeded;
4188 case Stmt::DoStmtClass: {
4189 const DoStmt *DS = cast<DoStmt>(S);
4192 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4193 if (ESR != ESR_Continue)
4197 FullExpressionRAII CondScope(Info);
4198 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4201 return ESR_Succeeded;
4204 case Stmt::ForStmtClass: {
4205 const ForStmt *FS = cast<ForStmt>(S);
4206 BlockScopeRAII Scope(Info);
4207 if (FS->getInit()) {
4208 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4209 if (ESR != ESR_Succeeded)
4213 BlockScopeRAII Scope(Info);
4214 bool Continue = true;
4215 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4216 FS->getCond(), Continue))
4221 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4222 if (ESR != ESR_Continue)
4226 FullExpressionRAII IncScope(Info);
4227 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4231 return ESR_Succeeded;
4234 case Stmt::CXXForRangeStmtClass: {
4235 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4236 BlockScopeRAII Scope(Info);
4238 // Evaluate the init-statement if present.
4239 if (FS->getInit()) {
4240 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4241 if (ESR != ESR_Succeeded)
4245 // Initialize the __range variable.
4246 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4247 if (ESR != ESR_Succeeded)
4250 // Create the __begin and __end iterators.
4251 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4252 if (ESR != ESR_Succeeded)
4254 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4255 if (ESR != ESR_Succeeded)
4259 // Condition: __begin != __end.
4261 bool Continue = true;
4262 FullExpressionRAII CondExpr(Info);
4263 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4269 // User's variable declaration, initialized by *__begin.
4270 BlockScopeRAII InnerScope(Info);
4271 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4272 if (ESR != ESR_Succeeded)
4276 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4277 if (ESR != ESR_Continue)
4280 // Increment: ++__begin
4281 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4285 return ESR_Succeeded;
4288 case Stmt::SwitchStmtClass:
4289 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4291 case Stmt::ContinueStmtClass:
4292 return ESR_Continue;
4294 case Stmt::BreakStmtClass:
4297 case Stmt::LabelStmtClass:
4298 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4300 case Stmt::AttributedStmtClass:
4301 // As a general principle, C++11 attributes can be ignored without
4302 // any semantic impact.
4303 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4306 case Stmt::CaseStmtClass:
4307 case Stmt::DefaultStmtClass:
4308 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4309 case Stmt::CXXTryStmtClass:
4310 // Evaluate try blocks by evaluating all sub statements.
4311 return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4315 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4316 /// default constructor. If so, we'll fold it whether or not it's marked as
4317 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4318 /// so we need special handling.
4319 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4320 const CXXConstructorDecl *CD,
4321 bool IsValueInitialization) {
4322 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4325 // Value-initialization does not call a trivial default constructor, so such a
4326 // call is a core constant expression whether or not the constructor is
4328 if (!CD->isConstexpr() && !IsValueInitialization) {
4329 if (Info.getLangOpts().CPlusPlus11) {
4330 // FIXME: If DiagDecl is an implicitly-declared special member function,
4331 // we should be much more explicit about why it's not constexpr.
4332 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4333 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4334 Info.Note(CD->getLocation(), diag::note_declared_at);
4336 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4342 /// CheckConstexprFunction - Check that a function can be called in a constant
4344 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4345 const FunctionDecl *Declaration,
4346 const FunctionDecl *Definition,
4348 // Potential constant expressions can contain calls to declared, but not yet
4349 // defined, constexpr functions.
4350 if (Info.checkingPotentialConstantExpression() && !Definition &&
4351 Declaration->isConstexpr())
4354 // Bail out if the function declaration itself is invalid. We will
4355 // have produced a relevant diagnostic while parsing it, so just
4356 // note the problematic sub-expression.
4357 if (Declaration->isInvalidDecl()) {
4358 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4362 // Can we evaluate this function call?
4363 if (Definition && Definition->isConstexpr() &&
4364 !Definition->isInvalidDecl() && Body)
4367 if (Info.getLangOpts().CPlusPlus11) {
4368 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4370 // If this function is not constexpr because it is an inherited
4371 // non-constexpr constructor, diagnose that directly.
4372 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4373 if (CD && CD->isInheritingConstructor()) {
4374 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4375 if (!Inherited->isConstexpr())
4376 DiagDecl = CD = Inherited;
4379 // FIXME: If DiagDecl is an implicitly-declared special member function
4380 // or an inheriting constructor, we should be much more explicit about why
4381 // it's not constexpr.
4382 if (CD && CD->isInheritingConstructor())
4383 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4384 << CD->getInheritedConstructor().getConstructor()->getParent();
4386 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4387 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4388 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4390 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4395 /// Determine if a class has any fields that might need to be copied by a
4396 /// trivial copy or move operation.
4397 static bool hasFields(const CXXRecordDecl *RD) {
4398 if (!RD || RD->isEmpty())
4400 for (auto *FD : RD->fields()) {
4401 if (FD->isUnnamedBitfield())
4405 for (auto &Base : RD->bases())
4406 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4412 typedef SmallVector<APValue, 8> ArgVector;
4415 /// EvaluateArgs - Evaluate the arguments to a function call.
4416 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4418 bool Success = true;
4419 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4421 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4422 // If we're checking for a potential constant expression, evaluate all
4423 // initializers even if some of them fail.
4424 if (!Info.noteFailure())
4432 /// Evaluate a function call.
4433 static bool HandleFunctionCall(SourceLocation CallLoc,
4434 const FunctionDecl *Callee, const LValue *This,
4435 ArrayRef<const Expr*> Args, const Stmt *Body,
4436 EvalInfo &Info, APValue &Result,
4437 const LValue *ResultSlot) {
4438 ArgVector ArgValues(Args.size());
4439 if (!EvaluateArgs(Args, ArgValues, Info))
4442 if (!Info.CheckCallLimit(CallLoc))
4445 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4447 // For a trivial copy or move assignment, perform an APValue copy. This is
4448 // essential for unions, where the operations performed by the assignment
4449 // operator cannot be represented as statements.
4451 // Skip this for non-union classes with no fields; in that case, the defaulted
4452 // copy/move does not actually read the object.
4453 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4454 if (MD && MD->isDefaulted() &&
4455 (MD->getParent()->isUnion() ||
4456 (MD->isTrivial() && hasFields(MD->getParent())))) {
4458 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4460 RHS.setFrom(Info.Ctx, ArgValues[0]);
4462 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4465 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
4468 This->moveInto(Result);
4470 } else if (MD && isLambdaCallOperator(MD)) {
4471 // We're in a lambda; determine the lambda capture field maps unless we're
4472 // just constexpr checking a lambda's call operator. constexpr checking is
4473 // done before the captures have been added to the closure object (unless
4474 // we're inferring constexpr-ness), so we don't have access to them in this
4475 // case. But since we don't need the captures to constexpr check, we can
4476 // just ignore them.
4477 if (!Info.checkingPotentialConstantExpression())
4478 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4479 Frame.LambdaThisCaptureField);
4482 StmtResult Ret = {Result, ResultSlot};
4483 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4484 if (ESR == ESR_Succeeded) {
4485 if (Callee->getReturnType()->isVoidType())
4487 Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4489 return ESR == ESR_Returned;
4492 /// Evaluate a constructor call.
4493 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4495 const CXXConstructorDecl *Definition,
4496 EvalInfo &Info, APValue &Result) {
4497 SourceLocation CallLoc = E->getExprLoc();
4498 if (!Info.CheckCallLimit(CallLoc))
4501 const CXXRecordDecl *RD = Definition->getParent();
4502 if (RD->getNumVBases()) {
4503 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4507 EvalInfo::EvaluatingConstructorRAII EvalObj(
4508 Info, {This.getLValueBase(),
4509 {This.getLValueCallIndex(), This.getLValueVersion()}});
4510 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4512 // FIXME: Creating an APValue just to hold a nonexistent return value is
4515 StmtResult Ret = {RetVal, nullptr};
4517 // If it's a delegating constructor, delegate.
4518 if (Definition->isDelegatingConstructor()) {
4519 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4521 FullExpressionRAII InitScope(Info);
4522 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4525 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4528 // For a trivial copy or move constructor, perform an APValue copy. This is
4529 // essential for unions (or classes with anonymous union members), where the
4530 // operations performed by the constructor cannot be represented by
4531 // ctor-initializers.
4533 // Skip this for empty non-union classes; we should not perform an
4534 // lvalue-to-rvalue conversion on them because their copy constructor does not
4535 // actually read them.
4536 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4537 (Definition->getParent()->isUnion() ||
4538 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4540 RHS.setFrom(Info.Ctx, ArgValues[0]);
4541 return handleLValueToRValueConversion(
4542 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4546 // Reserve space for the struct members.
4547 if (!RD->isUnion() && Result.isUninit())
4548 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4549 std::distance(RD->field_begin(), RD->field_end()));
4551 if (RD->isInvalidDecl()) return false;
4552 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4554 // A scope for temporaries lifetime-extended by reference members.
4555 BlockScopeRAII LifetimeExtendedScope(Info);
4557 bool Success = true;
4558 unsigned BasesSeen = 0;
4560 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4562 for (const auto *I : Definition->inits()) {
4563 LValue Subobject = This;
4564 LValue SubobjectParent = This;
4565 APValue *Value = &Result;
4567 // Determine the subobject to initialize.
4568 FieldDecl *FD = nullptr;
4569 if (I->isBaseInitializer()) {
4570 QualType BaseType(I->getBaseClass(), 0);
4572 // Non-virtual base classes are initialized in the order in the class
4573 // definition. We have already checked for virtual base classes.
4574 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4575 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4576 "base class initializers not in expected order");
4579 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4580 BaseType->getAsCXXRecordDecl(), &Layout))
4582 Value = &Result.getStructBase(BasesSeen++);
4583 } else if ((FD = I->getMember())) {
4584 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4586 if (RD->isUnion()) {
4587 Result = APValue(FD);
4588 Value = &Result.getUnionValue();
4590 Value = &Result.getStructField(FD->getFieldIndex());
4592 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4593 // Walk the indirect field decl's chain to find the object to initialize,
4594 // and make sure we've initialized every step along it.
4595 auto IndirectFieldChain = IFD->chain();
4596 for (auto *C : IndirectFieldChain) {
4597 FD = cast<FieldDecl>(C);
4598 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4599 // Switch the union field if it differs. This happens if we had
4600 // preceding zero-initialization, and we're now initializing a union
4601 // subobject other than the first.
4602 // FIXME: In this case, the values of the other subobjects are
4603 // specified, since zero-initialization sets all padding bits to zero.
4604 if (Value->isUninit() ||
4605 (Value->isUnion() && Value->getUnionField() != FD)) {
4607 *Value = APValue(FD);
4609 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4610 std::distance(CD->field_begin(), CD->field_end()));
4612 // Store Subobject as its parent before updating it for the last element
4614 if (C == IndirectFieldChain.back())
4615 SubobjectParent = Subobject;
4616 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4619 Value = &Value->getUnionValue();
4621 Value = &Value->getStructField(FD->getFieldIndex());
4624 llvm_unreachable("unknown base initializer kind");
4627 // Need to override This for implicit field initializers as in this case
4628 // This refers to innermost anonymous struct/union containing initializer,
4629 // not to currently constructed class.
4630 const Expr *Init = I->getInit();
4631 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4632 isa<CXXDefaultInitExpr>(Init));
4633 FullExpressionRAII InitScope(Info);
4634 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4635 (FD && FD->isBitField() &&
4636 !truncateBitfieldValue(Info, Init, *Value, FD))) {
4637 // If we're checking for a potential constant expression, evaluate all
4638 // initializers even if some of them fail.
4639 if (!Info.noteFailure())
4646 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4649 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4650 ArrayRef<const Expr*> Args,
4651 const CXXConstructorDecl *Definition,
4652 EvalInfo &Info, APValue &Result) {
4653 ArgVector ArgValues(Args.size());
4654 if (!EvaluateArgs(Args, ArgValues, Info))
4657 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4661 //===----------------------------------------------------------------------===//
4662 // Generic Evaluation
4663 //===----------------------------------------------------------------------===//
4666 template <class Derived>
4667 class ExprEvaluatorBase
4668 : public ConstStmtVisitor<Derived, bool> {
4670 Derived &getDerived() { return static_cast<Derived&>(*this); }
4671 bool DerivedSuccess(const APValue &V, const Expr *E) {
4672 return getDerived().Success(V, E);
4674 bool DerivedZeroInitialization(const Expr *E) {
4675 return getDerived().ZeroInitialization(E);
4678 // Check whether a conditional operator with a non-constant condition is a
4679 // potential constant expression. If neither arm is a potential constant
4680 // expression, then the conditional operator is not either.
4681 template<typename ConditionalOperator>
4682 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4683 assert(Info.checkingPotentialConstantExpression());
4685 // Speculatively evaluate both arms.
4686 SmallVector<PartialDiagnosticAt, 8> Diag;
4688 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4689 StmtVisitorTy::Visit(E->getFalseExpr());
4695 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4697 StmtVisitorTy::Visit(E->getTrueExpr());
4702 Error(E, diag::note_constexpr_conditional_never_const);
4706 template<typename ConditionalOperator>
4707 bool HandleConditionalOperator(const ConditionalOperator *E) {
4709 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4710 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4711 CheckPotentialConstantConditional(E);
4714 if (Info.noteFailure()) {
4715 StmtVisitorTy::Visit(E->getTrueExpr());
4716 StmtVisitorTy::Visit(E->getFalseExpr());
4721 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4722 return StmtVisitorTy::Visit(EvalExpr);
4727 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4728 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4730 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4731 return Info.CCEDiag(E, D);
4734 bool ZeroInitialization(const Expr *E) { return Error(E); }
4737 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4739 EvalInfo &getEvalInfo() { return Info; }
4741 /// Report an evaluation error. This should only be called when an error is
4742 /// first discovered. When propagating an error, just return false.
4743 bool Error(const Expr *E, diag::kind D) {
4747 bool Error(const Expr *E) {
4748 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4751 bool VisitStmt(const Stmt *) {
4752 llvm_unreachable("Expression evaluator should not be called on stmts");
4754 bool VisitExpr(const Expr *E) {
4758 bool VisitConstantExpr(const ConstantExpr *E)
4759 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4760 bool VisitParenExpr(const ParenExpr *E)
4761 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4762 bool VisitUnaryExtension(const UnaryOperator *E)
4763 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4764 bool VisitUnaryPlus(const UnaryOperator *E)
4765 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4766 bool VisitChooseExpr(const ChooseExpr *E)
4767 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4768 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4769 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4770 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4771 { return StmtVisitorTy::Visit(E->getReplacement()); }
4772 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4773 TempVersionRAII RAII(*Info.CurrentCall);
4774 return StmtVisitorTy::Visit(E->getExpr());
4776 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4777 TempVersionRAII RAII(*Info.CurrentCall);
4778 // The initializer may not have been parsed yet, or might be erroneous.
4781 return StmtVisitorTy::Visit(E->getExpr());
4783 // We cannot create any objects for which cleanups are required, so there is
4784 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4785 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4786 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4788 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4789 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4790 return static_cast<Derived*>(this)->VisitCastExpr(E);
4792 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4793 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4794 return static_cast<Derived*>(this)->VisitCastExpr(E);
4797 bool VisitBinaryOperator(const BinaryOperator *E) {
4798 switch (E->getOpcode()) {
4803 VisitIgnoredValue(E->getLHS());
4804 return StmtVisitorTy::Visit(E->getRHS());
4809 if (!HandleMemberPointerAccess(Info, E, Obj))
4812 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4814 return DerivedSuccess(Result, E);
4819 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4820 // Evaluate and cache the common expression. We treat it as a temporary,
4821 // even though it's not quite the same thing.
4822 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4823 Info, E->getCommon()))
4826 return HandleConditionalOperator(E);
4829 bool VisitConditionalOperator(const ConditionalOperator *E) {
4830 bool IsBcpCall = false;
4831 // If the condition (ignoring parens) is a __builtin_constant_p call,
4832 // the result is a constant expression if it can be folded without
4833 // side-effects. This is an important GNU extension. See GCC PR38377
4835 if (const CallExpr *CallCE =
4836 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4837 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4840 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4841 // constant expression; we can't check whether it's potentially foldable.
4842 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4845 FoldConstant Fold(Info, IsBcpCall);
4846 if (!HandleConditionalOperator(E)) {
4847 Fold.keepDiagnostics();
4854 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4855 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4856 return DerivedSuccess(*Value, E);
4858 const Expr *Source = E->getSourceExpr();
4861 if (Source == E) { // sanity checking.
4862 assert(0 && "OpaqueValueExpr recursively refers to itself");
4865 return StmtVisitorTy::Visit(Source);
4868 bool VisitCallExpr(const CallExpr *E) {
4870 if (!handleCallExpr(E, Result, nullptr))
4872 return DerivedSuccess(Result, E);
4875 bool handleCallExpr(const CallExpr *E, APValue &Result,
4876 const LValue *ResultSlot) {
4877 const Expr *Callee = E->getCallee()->IgnoreParens();
4878 QualType CalleeType = Callee->getType();
4880 const FunctionDecl *FD = nullptr;
4881 LValue *This = nullptr, ThisVal;
4882 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4883 bool HasQualifier = false;
4885 // Extract function decl and 'this' pointer from the callee.
4886 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4887 const ValueDecl *Member = nullptr;
4888 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4889 // Explicit bound member calls, such as x.f() or p->g();
4890 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4892 Member = ME->getMemberDecl();
4894 HasQualifier = ME->hasQualifier();
4895 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4896 // Indirect bound member calls ('.*' or '->*').
4897 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4898 if (!Member) return false;
4901 return Error(Callee);
4903 FD = dyn_cast<FunctionDecl>(Member);
4905 return Error(Callee);
4906 } else if (CalleeType->isFunctionPointerType()) {
4908 if (!EvaluatePointer(Callee, Call, Info))
4911 if (!Call.getLValueOffset().isZero())
4912 return Error(Callee);
4913 FD = dyn_cast_or_null<FunctionDecl>(
4914 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4916 return Error(Callee);
4917 // Don't call function pointers which have been cast to some other type.
4918 // Per DR (no number yet), the caller and callee can differ in noexcept.
4919 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4920 CalleeType->getPointeeType(), FD->getType())) {
4924 // Overloaded operator calls to member functions are represented as normal
4925 // calls with '*this' as the first argument.
4926 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4927 if (MD && !MD->isStatic()) {
4928 // FIXME: When selecting an implicit conversion for an overloaded
4929 // operator delete, we sometimes try to evaluate calls to conversion
4930 // operators without a 'this' parameter!
4934 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4937 Args = Args.slice(1);
4938 } else if (MD && MD->isLambdaStaticInvoker()) {
4939 // Map the static invoker for the lambda back to the call operator.
4940 // Conveniently, we don't have to slice out the 'this' argument (as is
4941 // being done for the non-static case), since a static member function
4942 // doesn't have an implicit argument passed in.
4943 const CXXRecordDecl *ClosureClass = MD->getParent();
4945 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4946 "Number of captures must be zero for conversion to function-ptr");
4948 const CXXMethodDecl *LambdaCallOp =
4949 ClosureClass->getLambdaCallOperator();
4951 // Set 'FD', the function that will be called below, to the call
4952 // operator. If the closure object represents a generic lambda, find
4953 // the corresponding specialization of the call operator.
4955 if (ClosureClass->isGenericLambda()) {
4956 assert(MD->isFunctionTemplateSpecialization() &&
4957 "A generic lambda's static-invoker function must be a "
4958 "template specialization");
4959 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4960 FunctionTemplateDecl *CallOpTemplate =
4961 LambdaCallOp->getDescribedFunctionTemplate();
4962 void *InsertPos = nullptr;
4963 FunctionDecl *CorrespondingCallOpSpecialization =
4964 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4965 assert(CorrespondingCallOpSpecialization &&
4966 "We must always have a function call operator specialization "
4967 "that corresponds to our static invoker specialization");
4968 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4977 if (This && !This->checkSubobject(Info, E, CSK_This))
4980 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4981 // calls to such functions in constant expressions.
4982 if (This && !HasQualifier &&
4983 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4984 return Error(E, diag::note_constexpr_virtual_call);
4986 const FunctionDecl *Definition = nullptr;
4987 Stmt *Body = FD->getBody(Definition);
4989 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4990 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4991 Result, ResultSlot))
4997 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4998 return StmtVisitorTy::Visit(E->getInitializer());
5000 bool VisitInitListExpr(const InitListExpr *E) {
5001 if (E->getNumInits() == 0)
5002 return DerivedZeroInitialization(E);
5003 if (E->getNumInits() == 1)
5004 return StmtVisitorTy::Visit(E->getInit(0));
5007 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5008 return DerivedZeroInitialization(E);
5010 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5011 return DerivedZeroInitialization(E);
5013 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5014 return DerivedZeroInitialization(E);
5017 /// A member expression where the object is a prvalue is itself a prvalue.
5018 bool VisitMemberExpr(const MemberExpr *E) {
5019 assert(!E->isArrow() && "missing call to bound member function?");
5022 if (!Evaluate(Val, Info, E->getBase()))
5025 QualType BaseTy = E->getBase()->getType();
5027 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5028 if (!FD) return Error(E);
5029 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5030 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5031 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5033 CompleteObject Obj(&Val, BaseTy, true);
5034 SubobjectDesignator Designator(BaseTy);
5035 Designator.addDeclUnchecked(FD);
5038 return extractSubobject(Info, E, Obj, Designator, Result) &&
5039 DerivedSuccess(Result, E);
5042 bool VisitCastExpr(const CastExpr *E) {
5043 switch (E->getCastKind()) {
5047 case CK_AtomicToNonAtomic: {
5049 // This does not need to be done in place even for class/array types:
5050 // atomic-to-non-atomic conversion implies copying the object
5052 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5054 return DerivedSuccess(AtomicVal, E);
5058 case CK_UserDefinedConversion:
5059 return StmtVisitorTy::Visit(E->getSubExpr());
5061 case CK_LValueToRValue: {
5063 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5066 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5067 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5070 return DerivedSuccess(RVal, E);
5077 bool VisitUnaryPostInc(const UnaryOperator *UO) {
5078 return VisitUnaryPostIncDec(UO);
5080 bool VisitUnaryPostDec(const UnaryOperator *UO) {
5081 return VisitUnaryPostIncDec(UO);
5083 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5084 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5088 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5091 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5092 UO->isIncrementOp(), &RVal))
5094 return DerivedSuccess(RVal, UO);
5097 bool VisitStmtExpr(const StmtExpr *E) {
5098 // We will have checked the full-expressions inside the statement expression
5099 // when they were completed, and don't need to check them again now.
5100 if (Info.checkingForOverflow())
5103 BlockScopeRAII Scope(Info);
5104 const CompoundStmt *CS = E->getSubStmt();
5105 if (CS->body_empty())
5108 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5109 BE = CS->body_end();
5112 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5114 Info.FFDiag((*BI)->getBeginLoc(),
5115 diag::note_constexpr_stmt_expr_unsupported);
5118 return this->Visit(FinalExpr);
5121 APValue ReturnValue;
5122 StmtResult Result = { ReturnValue, nullptr };
5123 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5124 if (ESR != ESR_Succeeded) {
5125 // FIXME: If the statement-expression terminated due to 'return',
5126 // 'break', or 'continue', it would be nice to propagate that to
5127 // the outer statement evaluation rather than bailing out.
5128 if (ESR != ESR_Failed)
5129 Info.FFDiag((*BI)->getBeginLoc(),
5130 diag::note_constexpr_stmt_expr_unsupported);
5135 llvm_unreachable("Return from function from the loop above.");
5138 /// Visit a value which is evaluated, but whose value is ignored.
5139 void VisitIgnoredValue(const Expr *E) {
5140 EvaluateIgnoredValue(Info, E);
5143 /// Potentially visit a MemberExpr's base expression.
5144 void VisitIgnoredBaseExpression(const Expr *E) {
5145 // While MSVC doesn't evaluate the base expression, it does diagnose the
5146 // presence of side-effecting behavior.
5147 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5149 VisitIgnoredValue(E);
5155 //===----------------------------------------------------------------------===//
5156 // Common base class for lvalue and temporary evaluation.
5157 //===----------------------------------------------------------------------===//
5159 template<class Derived>
5160 class LValueExprEvaluatorBase
5161 : public ExprEvaluatorBase<Derived> {
5165 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5166 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5168 bool Success(APValue::LValueBase B) {
5173 bool evaluatePointer(const Expr *E, LValue &Result) {
5174 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5178 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5179 : ExprEvaluatorBaseTy(Info), Result(Result),
5180 InvalidBaseOK(InvalidBaseOK) {}
5182 bool Success(const APValue &V, const Expr *E) {
5183 Result.setFrom(this->Info.Ctx, V);
5187 bool VisitMemberExpr(const MemberExpr *E) {
5188 // Handle non-static data members.
5192 EvalOK = evaluatePointer(E->getBase(), Result);
5193 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5194 } else if (E->getBase()->isRValue()) {
5195 assert(E->getBase()->getType()->isRecordType());
5196 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5197 BaseTy = E->getBase()->getType();
5199 EvalOK = this->Visit(E->getBase());
5200 BaseTy = E->getBase()->getType();
5205 Result.setInvalid(E);
5209 const ValueDecl *MD = E->getMemberDecl();
5210 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5211 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5212 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5214 if (!HandleLValueMember(this->Info, E, Result, FD))
5216 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5217 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5220 return this->Error(E);
5222 if (MD->getType()->isReferenceType()) {
5224 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5227 return Success(RefValue, E);
5232 bool VisitBinaryOperator(const BinaryOperator *E) {
5233 switch (E->getOpcode()) {
5235 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5239 return HandleMemberPointerAccess(this->Info, E, Result);
5243 bool VisitCastExpr(const CastExpr *E) {
5244 switch (E->getCastKind()) {
5246 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5248 case CK_DerivedToBase:
5249 case CK_UncheckedDerivedToBase:
5250 if (!this->Visit(E->getSubExpr()))
5253 // Now figure out the necessary offset to add to the base LV to get from
5254 // the derived class to the base class.
5255 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5262 //===----------------------------------------------------------------------===//
5263 // LValue Evaluation
5265 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5266 // function designators (in C), decl references to void objects (in C), and
5267 // temporaries (if building with -Wno-address-of-temporary).
5269 // LValue evaluation produces values comprising a base expression of one of the
5275 // * CompoundLiteralExpr in C (and in global scope in C++)
5279 // * ObjCStringLiteralExpr
5283 // * CallExpr for a MakeStringConstant builtin
5284 // - Locals and temporaries
5285 // * MaterializeTemporaryExpr
5286 // * Any Expr, with a CallIndex indicating the function in which the temporary
5287 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5288 // from the AST (FIXME).
5289 // * A MaterializeTemporaryExpr that has static storage duration, with no
5290 // CallIndex, for a lifetime-extended temporary.
5291 // plus an offset in bytes.
5292 //===----------------------------------------------------------------------===//
5294 class LValueExprEvaluator
5295 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5297 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5298 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5300 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5301 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5303 bool VisitDeclRefExpr(const DeclRefExpr *E);
5304 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5305 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5306 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5307 bool VisitMemberExpr(const MemberExpr *E);
5308 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5309 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5310 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5311 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5312 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5313 bool VisitUnaryDeref(const UnaryOperator *E);
5314 bool VisitUnaryReal(const UnaryOperator *E);
5315 bool VisitUnaryImag(const UnaryOperator *E);
5316 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5317 return VisitUnaryPreIncDec(UO);
5319 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5320 return VisitUnaryPreIncDec(UO);
5322 bool VisitBinAssign(const BinaryOperator *BO);
5323 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5325 bool VisitCastExpr(const CastExpr *E) {
5326 switch (E->getCastKind()) {
5328 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5330 case CK_LValueBitCast:
5331 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5332 if (!Visit(E->getSubExpr()))
5334 Result.Designator.setInvalid();
5337 case CK_BaseToDerived:
5338 if (!Visit(E->getSubExpr()))
5340 return HandleBaseToDerivedCast(Info, E, Result);
5344 } // end anonymous namespace
5346 /// Evaluate an expression as an lvalue. This can be legitimately called on
5347 /// expressions which are not glvalues, in three cases:
5348 /// * function designators in C, and
5349 /// * "extern void" objects
5350 /// * @selector() expressions in Objective-C
5351 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5352 bool InvalidBaseOK) {
5353 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5354 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5355 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5358 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5359 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5361 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5362 return VisitVarDecl(E, VD);
5363 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5364 return Visit(BD->getBinding());
5369 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5371 // If we are within a lambda's call operator, check whether the 'VD' referred
5372 // to within 'E' actually represents a lambda-capture that maps to a
5373 // data-member/field within the closure object, and if so, evaluate to the
5374 // field or what the field refers to.
5375 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5376 isa<DeclRefExpr>(E) &&
5377 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5378 // We don't always have a complete capture-map when checking or inferring if
5379 // the function call operator meets the requirements of a constexpr function
5380 // - but we don't need to evaluate the captures to determine constexprness
5381 // (dcl.constexpr C++17).
5382 if (Info.checkingPotentialConstantExpression())
5385 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5386 // Start with 'Result' referring to the complete closure object...
5387 Result = *Info.CurrentCall->This;
5388 // ... then update it to refer to the field of the closure object
5389 // that represents the capture.
5390 if (!HandleLValueMember(Info, E, Result, FD))
5392 // And if the field is of reference type, update 'Result' to refer to what
5393 // the field refers to.
5394 if (FD->getType()->isReferenceType()) {
5396 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5399 Result.setFrom(Info.Ctx, RVal);
5404 CallStackFrame *Frame = nullptr;
5405 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5406 // Only if a local variable was declared in the function currently being
5407 // evaluated, do we expect to be able to find its value in the current
5408 // frame. (Otherwise it was likely declared in an enclosing context and
5409 // could either have a valid evaluatable value (for e.g. a constexpr
5410 // variable) or be ill-formed (and trigger an appropriate evaluation
5412 if (Info.CurrentCall->Callee &&
5413 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5414 Frame = Info.CurrentCall;
5418 if (!VD->getType()->isReferenceType()) {
5420 Result.set({VD, Frame->Index,
5421 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5428 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5430 if (V->isUninit()) {
5431 if (!Info.checkingPotentialConstantExpression())
5432 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5435 return Success(*V, E);
5438 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5439 const MaterializeTemporaryExpr *E) {
5440 // Walk through the expression to find the materialized temporary itself.
5441 SmallVector<const Expr *, 2> CommaLHSs;
5442 SmallVector<SubobjectAdjustment, 2> Adjustments;
5443 const Expr *Inner = E->GetTemporaryExpr()->
5444 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5446 // If we passed any comma operators, evaluate their LHSs.
5447 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5448 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5451 // A materialized temporary with static storage duration can appear within the
5452 // result of a constant expression evaluation, so we need to preserve its
5453 // value for use outside this evaluation.
5455 if (E->getStorageDuration() == SD_Static) {
5456 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5460 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5464 QualType Type = Inner->getType();
5466 // Materialize the temporary itself.
5467 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5468 (E->getStorageDuration() == SD_Static &&
5469 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5474 // Adjust our lvalue to refer to the desired subobject.
5475 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5477 switch (Adjustments[I].Kind) {
5478 case SubobjectAdjustment::DerivedToBaseAdjustment:
5479 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5482 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5485 case SubobjectAdjustment::FieldAdjustment:
5486 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5488 Type = Adjustments[I].Field->getType();
5491 case SubobjectAdjustment::MemberPointerAdjustment:
5492 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5493 Adjustments[I].Ptr.RHS))
5495 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5504 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5505 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5506 "lvalue compound literal in c++?");
5507 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5508 // only see this when folding in C, so there's no standard to follow here.
5512 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5513 if (!E->isPotentiallyEvaluated())
5516 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5517 << E->getExprOperand()->getType()
5518 << E->getExprOperand()->getSourceRange();
5522 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5526 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5527 // Handle static data members.
5528 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5529 VisitIgnoredBaseExpression(E->getBase());
5530 return VisitVarDecl(E, VD);
5533 // Handle static member functions.
5534 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5535 if (MD->isStatic()) {
5536 VisitIgnoredBaseExpression(E->getBase());
5541 // Handle non-static data members.
5542 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5545 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5546 // FIXME: Deal with vectors as array subscript bases.
5547 if (E->getBase()->getType()->isVectorType())
5550 bool Success = true;
5551 if (!evaluatePointer(E->getBase(), Result)) {
5552 if (!Info.noteFailure())
5558 if (!EvaluateInteger(E->getIdx(), Index, Info))
5562 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5565 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5566 return evaluatePointer(E->getSubExpr(), Result);
5569 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5570 if (!Visit(E->getSubExpr()))
5572 // __real is a no-op on scalar lvalues.
5573 if (E->getSubExpr()->getType()->isAnyComplexType())
5574 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5578 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5579 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5580 "lvalue __imag__ on scalar?");
5581 if (!Visit(E->getSubExpr()))
5583 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5587 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5588 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5591 if (!this->Visit(UO->getSubExpr()))
5594 return handleIncDec(
5595 this->Info, UO, Result, UO->getSubExpr()->getType(),
5596 UO->isIncrementOp(), nullptr);
5599 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5600 const CompoundAssignOperator *CAO) {
5601 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5606 // The overall lvalue result is the result of evaluating the LHS.
5607 if (!this->Visit(CAO->getLHS())) {
5608 if (Info.noteFailure())
5609 Evaluate(RHS, this->Info, CAO->getRHS());
5613 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5616 return handleCompoundAssignment(
5618 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5619 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5622 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5623 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5628 if (!this->Visit(E->getLHS())) {
5629 if (Info.noteFailure())
5630 Evaluate(NewVal, this->Info, E->getRHS());
5634 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5637 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5641 //===----------------------------------------------------------------------===//
5642 // Pointer Evaluation
5643 //===----------------------------------------------------------------------===//
5645 /// Attempts to compute the number of bytes available at the pointer
5646 /// returned by a function with the alloc_size attribute. Returns true if we
5647 /// were successful. Places an unsigned number into `Result`.
5649 /// This expects the given CallExpr to be a call to a function with an
5650 /// alloc_size attribute.
5651 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5652 const CallExpr *Call,
5653 llvm::APInt &Result) {
5654 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5656 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5657 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5658 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5659 if (Call->getNumArgs() <= SizeArgNo)
5662 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5663 Expr::EvalResult ExprResult;
5664 if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
5666 Into = ExprResult.Val.getInt();
5667 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5669 Into = Into.zextOrSelf(BitsInSizeT);
5674 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5677 if (!AllocSize->getNumElemsParam().isValid()) {
5678 Result = std::move(SizeOfElem);
5682 APSInt NumberOfElems;
5683 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5684 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5688 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5692 Result = std::move(BytesAvailable);
5696 /// Convenience function. LVal's base must be a call to an alloc_size
5698 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5700 llvm::APInt &Result) {
5701 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5702 "Can't get the size of a non alloc_size function");
5703 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5704 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5705 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5708 /// Attempts to evaluate the given LValueBase as the result of a call to
5709 /// a function with the alloc_size attribute. If it was possible to do so, this
5710 /// function will return true, make Result's Base point to said function call,
5711 /// and mark Result's Base as invalid.
5712 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5717 // Because we do no form of static analysis, we only support const variables.
5719 // Additionally, we can't support parameters, nor can we support static
5720 // variables (in the latter case, use-before-assign isn't UB; in the former,
5721 // we have no clue what they'll be assigned to).
5723 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5724 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5727 const Expr *Init = VD->getAnyInitializer();
5731 const Expr *E = Init->IgnoreParens();
5732 if (!tryUnwrapAllocSizeCall(E))
5735 // Store E instead of E unwrapped so that the type of the LValue's base is
5736 // what the user wanted.
5737 Result.setInvalid(E);
5739 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5740 Result.addUnsizedArray(Info, E, Pointee);
5745 class PointerExprEvaluator
5746 : public ExprEvaluatorBase<PointerExprEvaluator> {
5750 bool Success(const Expr *E) {
5755 bool evaluateLValue(const Expr *E, LValue &Result) {
5756 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5759 bool evaluatePointer(const Expr *E, LValue &Result) {
5760 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5763 bool visitNonBuiltinCallExpr(const CallExpr *E);
5766 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5767 : ExprEvaluatorBaseTy(info), Result(Result),
5768 InvalidBaseOK(InvalidBaseOK) {}
5770 bool Success(const APValue &V, const Expr *E) {
5771 Result.setFrom(Info.Ctx, V);
5774 bool ZeroInitialization(const Expr *E) {
5775 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5776 Result.setNull(E->getType(), TargetVal);
5780 bool VisitBinaryOperator(const BinaryOperator *E);
5781 bool VisitCastExpr(const CastExpr* E);
5782 bool VisitUnaryAddrOf(const UnaryOperator *E);
5783 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5784 { return Success(E); }
5785 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5786 if (Info.noteFailure())
5787 EvaluateIgnoredValue(Info, E->getSubExpr());
5790 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5791 { return Success(E); }
5792 bool VisitCallExpr(const CallExpr *E);
5793 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5794 bool VisitBlockExpr(const BlockExpr *E) {
5795 if (!E->getBlockDecl()->hasCaptures())
5799 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5800 // Can't look at 'this' when checking a potential constant expression.
5801 if (Info.checkingPotentialConstantExpression())
5803 if (!Info.CurrentCall->This) {
5804 if (Info.getLangOpts().CPlusPlus11)
5805 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5810 Result = *Info.CurrentCall->This;
5811 // If we are inside a lambda's call operator, the 'this' expression refers
5812 // to the enclosing '*this' object (either by value or reference) which is
5813 // either copied into the closure object's field that represents the '*this'
5814 // or refers to '*this'.
5815 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5816 // Update 'Result' to refer to the data member/field of the closure object
5817 // that represents the '*this' capture.
5818 if (!HandleLValueMember(Info, E, Result,
5819 Info.CurrentCall->LambdaThisCaptureField))
5821 // If we captured '*this' by reference, replace the field with its referent.
5822 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5823 ->isPointerType()) {
5825 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5829 Result.setFrom(Info.Ctx, RVal);
5835 // FIXME: Missing: @protocol, @selector
5837 } // end anonymous namespace
5839 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5840 bool InvalidBaseOK) {
5841 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5842 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5845 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5846 if (E->getOpcode() != BO_Add &&
5847 E->getOpcode() != BO_Sub)
5848 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5850 const Expr *PExp = E->getLHS();
5851 const Expr *IExp = E->getRHS();
5852 if (IExp->getType()->isPointerType())
5853 std::swap(PExp, IExp);
5855 bool EvalPtrOK = evaluatePointer(PExp, Result);
5856 if (!EvalPtrOK && !Info.noteFailure())
5859 llvm::APSInt Offset;
5860 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5863 if (E->getOpcode() == BO_Sub)
5864 negateAsSigned(Offset);
5866 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5867 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5870 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5871 return evaluateLValue(E->getSubExpr(), Result);
5874 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5875 const Expr *SubExpr = E->getSubExpr();
5877 switch (E->getCastKind()) {
5882 case CK_CPointerToObjCPointerCast:
5883 case CK_BlockPointerToObjCPointerCast:
5884 case CK_AnyPointerToBlockPointerCast:
5885 case CK_AddressSpaceConversion:
5886 if (!Visit(SubExpr))
5888 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5889 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5890 // also static_casts, but we disallow them as a resolution to DR1312.
5891 if (!E->getType()->isVoidPointerType()) {
5892 Result.Designator.setInvalid();
5893 if (SubExpr->getType()->isVoidPointerType())
5894 CCEDiag(E, diag::note_constexpr_invalid_cast)
5895 << 3 << SubExpr->getType();
5897 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5899 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5900 ZeroInitialization(E);
5903 case CK_DerivedToBase:
5904 case CK_UncheckedDerivedToBase:
5905 if (!evaluatePointer(E->getSubExpr(), Result))
5907 if (!Result.Base && Result.Offset.isZero())
5910 // Now figure out the necessary offset to add to the base LV to get from
5911 // the derived class to the base class.
5912 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5913 castAs<PointerType>()->getPointeeType(),
5916 case CK_BaseToDerived:
5917 if (!Visit(E->getSubExpr()))
5919 if (!Result.Base && Result.Offset.isZero())
5921 return HandleBaseToDerivedCast(Info, E, Result);
5923 case CK_NullToPointer:
5924 VisitIgnoredValue(E->getSubExpr());
5925 return ZeroInitialization(E);
5927 case CK_IntegralToPointer: {
5928 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5931 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5934 if (Value.isInt()) {
5935 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5936 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5937 Result.Base = (Expr*)nullptr;
5938 Result.InvalidBase = false;
5939 Result.Offset = CharUnits::fromQuantity(N);
5940 Result.Designator.setInvalid();
5941 Result.IsNullPtr = false;
5944 // Cast is of an lvalue, no need to change value.
5945 Result.setFrom(Info.Ctx, Value);
5950 case CK_ArrayToPointerDecay: {
5951 if (SubExpr->isGLValue()) {
5952 if (!evaluateLValue(SubExpr, Result))
5955 APValue &Value = createTemporary(SubExpr, false, Result,
5957 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5960 // The result is a pointer to the first element of the array.
5961 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5962 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5963 Result.addArray(Info, E, CAT);
5965 Result.addUnsizedArray(Info, E, AT->getElementType());
5969 case CK_FunctionToPointerDecay:
5970 return evaluateLValue(SubExpr, Result);
5972 case CK_LValueToRValue: {
5974 if (!evaluateLValue(E->getSubExpr(), LVal))
5978 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5979 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5981 return InvalidBaseOK &&
5982 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5983 return Success(RVal, E);
5987 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5990 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5991 UnaryExprOrTypeTrait ExprKind) {
5992 // C++ [expr.alignof]p3:
5993 // When alignof is applied to a reference type, the result is the
5994 // alignment of the referenced type.
5995 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5996 T = Ref->getPointeeType();
5998 if (T.getQualifiers().hasUnaligned())
5999 return CharUnits::One();
6001 const bool AlignOfReturnsPreferred =
6002 Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
6004 // __alignof is defined to return the preferred alignment.
6005 // Before 8, clang returned the preferred alignment for alignof and _Alignof
6007 if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
6008 return Info.Ctx.toCharUnitsFromBits(
6009 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6010 // alignof and _Alignof are defined to return the ABI alignment.
6011 else if (ExprKind == UETT_AlignOf)
6012 return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
6014 llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
6017 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
6018 UnaryExprOrTypeTrait ExprKind) {
6019 E = E->IgnoreParens();
6021 // The kinds of expressions that we have special-case logic here for
6022 // should be kept up to date with the special checks for those
6023 // expressions in Sema.
6025 // alignof decl is always accepted, even if it doesn't make sense: we default
6026 // to 1 in those cases.
6027 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6028 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6029 /*RefAsPointee*/true);
6031 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6032 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6033 /*RefAsPointee*/true);
6035 return GetAlignOfType(Info, E->getType(), ExprKind);
6038 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6039 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6040 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6043 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6046 Result.setInvalid(E);
6047 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6048 Result.addUnsizedArray(Info, E, PointeeTy);
6052 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6053 if (IsStringLiteralCall(E))
6056 if (unsigned BuiltinOp = E->getBuiltinCallee())
6057 return VisitBuiltinCallExpr(E, BuiltinOp);
6059 return visitNonBuiltinCallExpr(E);
6062 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6063 unsigned BuiltinOp) {
6064 switch (BuiltinOp) {
6065 case Builtin::BI__builtin_addressof:
6066 return evaluateLValue(E->getArg(0), Result);
6067 case Builtin::BI__builtin_assume_aligned: {
6068 // We need to be very careful here because: if the pointer does not have the
6069 // asserted alignment, then the behavior is undefined, and undefined
6070 // behavior is non-constant.
6071 if (!evaluatePointer(E->getArg(0), Result))
6074 LValue OffsetResult(Result);
6076 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6078 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6080 if (E->getNumArgs() > 2) {
6082 if (!EvaluateInteger(E->getArg(2), Offset, Info))
6085 int64_t AdditionalOffset = -Offset.getZExtValue();
6086 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6089 // If there is a base object, then it must have the correct alignment.
6090 if (OffsetResult.Base) {
6091 CharUnits BaseAlignment;
6092 if (const ValueDecl *VD =
6093 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6094 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6096 BaseAlignment = GetAlignOfExpr(
6097 Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
6100 if (BaseAlignment < Align) {
6101 Result.Designator.setInvalid();
6102 // FIXME: Add support to Diagnostic for long / long long.
6103 CCEDiag(E->getArg(0),
6104 diag::note_constexpr_baa_insufficient_alignment) << 0
6105 << (unsigned)BaseAlignment.getQuantity()
6106 << (unsigned)Align.getQuantity();
6111 // The offset must also have the correct alignment.
6112 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6113 Result.Designator.setInvalid();
6116 ? CCEDiag(E->getArg(0),
6117 diag::note_constexpr_baa_insufficient_alignment) << 1
6118 : CCEDiag(E->getArg(0),
6119 diag::note_constexpr_baa_value_insufficient_alignment))
6120 << (int)OffsetResult.Offset.getQuantity()
6121 << (unsigned)Align.getQuantity();
6127 case Builtin::BI__builtin_launder:
6128 return evaluatePointer(E->getArg(0), Result);
6129 case Builtin::BIstrchr:
6130 case Builtin::BIwcschr:
6131 case Builtin::BImemchr:
6132 case Builtin::BIwmemchr:
6133 if (Info.getLangOpts().CPlusPlus11)
6134 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6135 << /*isConstexpr*/0 << /*isConstructor*/0
6136 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6138 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6140 case Builtin::BI__builtin_strchr:
6141 case Builtin::BI__builtin_wcschr:
6142 case Builtin::BI__builtin_memchr:
6143 case Builtin::BI__builtin_char_memchr:
6144 case Builtin::BI__builtin_wmemchr: {
6145 if (!Visit(E->getArg(0)))
6148 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6150 uint64_t MaxLength = uint64_t(-1);
6151 if (BuiltinOp != Builtin::BIstrchr &&
6152 BuiltinOp != Builtin::BIwcschr &&
6153 BuiltinOp != Builtin::BI__builtin_strchr &&
6154 BuiltinOp != Builtin::BI__builtin_wcschr) {
6156 if (!EvaluateInteger(E->getArg(2), N, Info))
6158 MaxLength = N.getExtValue();
6160 // We cannot find the value if there are no candidates to match against.
6161 if (MaxLength == 0u)
6162 return ZeroInitialization(E);
6163 if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
6164 Result.Designator.Invalid)
6166 QualType CharTy = Result.Designator.getType(Info.Ctx);
6167 bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
6168 BuiltinOp == Builtin::BI__builtin_memchr;
6170 Info.Ctx.hasSameUnqualifiedType(
6171 CharTy, E->getArg(0)->getType()->getPointeeType()));
6172 // Pointers to const void may point to objects of incomplete type.
6173 if (IsRawByte && CharTy->isIncompleteType()) {
6174 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
6177 // Give up on byte-oriented matching against multibyte elements.
6178 // FIXME: We can compare the bytes in the correct order.
6179 if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
6181 // Figure out what value we're actually looking for (after converting to
6182 // the corresponding unsigned type if necessary).
6183 uint64_t DesiredVal;
6184 bool StopAtNull = false;
6185 switch (BuiltinOp) {
6186 case Builtin::BIstrchr:
6187 case Builtin::BI__builtin_strchr:
6188 // strchr compares directly to the passed integer, and therefore
6189 // always fails if given an int that is not a char.
6190 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6191 E->getArg(1)->getType(),
6194 return ZeroInitialization(E);
6197 case Builtin::BImemchr:
6198 case Builtin::BI__builtin_memchr:
6199 case Builtin::BI__builtin_char_memchr:
6200 // memchr compares by converting both sides to unsigned char. That's also
6201 // correct for strchr if we get this far (to cope with plain char being
6202 // unsigned in the strchr case).
6203 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6206 case Builtin::BIwcschr:
6207 case Builtin::BI__builtin_wcschr:
6210 case Builtin::BIwmemchr:
6211 case Builtin::BI__builtin_wmemchr:
6212 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6213 DesiredVal = Desired.getZExtValue();
6217 for (; MaxLength; --MaxLength) {
6219 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6222 if (Char.getInt().getZExtValue() == DesiredVal)
6224 if (StopAtNull && !Char.getInt())
6226 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6229 // Not found: return nullptr.
6230 return ZeroInitialization(E);
6233 case Builtin::BImemcpy:
6234 case Builtin::BImemmove:
6235 case Builtin::BIwmemcpy:
6236 case Builtin::BIwmemmove:
6237 if (Info.getLangOpts().CPlusPlus11)
6238 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6239 << /*isConstexpr*/0 << /*isConstructor*/0
6240 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6242 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6244 case Builtin::BI__builtin_memcpy:
6245 case Builtin::BI__builtin_memmove:
6246 case Builtin::BI__builtin_wmemcpy:
6247 case Builtin::BI__builtin_wmemmove: {
6248 bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6249 BuiltinOp == Builtin::BIwmemmove ||
6250 BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6251 BuiltinOp == Builtin::BI__builtin_wmemmove;
6252 bool Move = BuiltinOp == Builtin::BImemmove ||
6253 BuiltinOp == Builtin::BIwmemmove ||
6254 BuiltinOp == Builtin::BI__builtin_memmove ||
6255 BuiltinOp == Builtin::BI__builtin_wmemmove;
6257 // The result of mem* is the first argument.
6258 if (!Visit(E->getArg(0)))
6260 LValue Dest = Result;
6263 if (!EvaluatePointer(E->getArg(1), Src, Info))
6267 if (!EvaluateInteger(E->getArg(2), N, Info))
6269 assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6271 // If the size is zero, we treat this as always being a valid no-op.
6272 // (Even if one of the src and dest pointers is null.)
6276 // Otherwise, if either of the operands is null, we can't proceed. Don't
6277 // try to determine the type of the copied objects, because there aren't
6279 if (!Src.Base || !Dest.Base) {
6281 (!Src.Base ? Src : Dest).moveInto(Val);
6282 Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6283 << Move << WChar << !!Src.Base
6284 << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6287 if (Src.Designator.Invalid || Dest.Designator.Invalid)
6290 // We require that Src and Dest are both pointers to arrays of
6291 // trivially-copyable type. (For the wide version, the designator will be
6292 // invalid if the designated object is not a wchar_t.)
6293 QualType T = Dest.Designator.getType(Info.Ctx);
6294 QualType SrcT = Src.Designator.getType(Info.Ctx);
6295 if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6296 Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6299 if (T->isIncompleteType()) {
6300 Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6303 if (!T.isTriviallyCopyableType(Info.Ctx)) {
6304 Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6308 // Figure out how many T's we're copying.
6309 uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6312 llvm::APInt OrigN = N;
6313 llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6315 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6316 << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6322 // Check that the copying will remain within the arrays, just so that we
6323 // can give a more meaningful diagnostic. This implicitly also checks that
6324 // N fits into 64 bits.
6325 uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6326 uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6327 if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6328 Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6329 << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6330 << N.toString(10, /*Signed*/false);
6333 uint64_t NElems = N.getZExtValue();
6334 uint64_t NBytes = NElems * TSize;
6336 // Check for overlap.
6338 if (HasSameBase(Src, Dest)) {
6339 uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6340 uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6341 if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6342 // Dest is inside the source region.
6344 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6347 // For memmove and friends, copy backwards.
6348 if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6349 !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6352 } else if (!Move && SrcOffset >= DestOffset &&
6353 SrcOffset - DestOffset < NBytes) {
6354 // Src is inside the destination region for memcpy: invalid.
6355 Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6362 if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6363 !handleAssignment(Info, E, Dest, T, Val))
6365 // Do not iterate past the last element; if we're copying backwards, that
6366 // might take us off the start of the array.
6369 if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6370 !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6376 return visitNonBuiltinCallExpr(E);
6380 //===----------------------------------------------------------------------===//
6381 // Member Pointer Evaluation
6382 //===----------------------------------------------------------------------===//
6385 class MemberPointerExprEvaluator
6386 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6389 bool Success(const ValueDecl *D) {
6390 Result = MemberPtr(D);
6395 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6396 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6398 bool Success(const APValue &V, const Expr *E) {
6402 bool ZeroInitialization(const Expr *E) {
6403 return Success((const ValueDecl*)nullptr);
6406 bool VisitCastExpr(const CastExpr *E);
6407 bool VisitUnaryAddrOf(const UnaryOperator *E);
6409 } // end anonymous namespace
6411 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6413 assert(E->isRValue() && E->getType()->isMemberPointerType());
6414 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6417 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6418 switch (E->getCastKind()) {
6420 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6422 case CK_NullToMemberPointer:
6423 VisitIgnoredValue(E->getSubExpr());
6424 return ZeroInitialization(E);
6426 case CK_BaseToDerivedMemberPointer: {
6427 if (!Visit(E->getSubExpr()))
6429 if (E->path_empty())
6431 // Base-to-derived member pointer casts store the path in derived-to-base
6432 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6433 // the wrong end of the derived->base arc, so stagger the path by one class.
6434 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6435 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6436 PathI != PathE; ++PathI) {
6437 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6438 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6439 if (!Result.castToDerived(Derived))
6442 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6443 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6448 case CK_DerivedToBaseMemberPointer:
6449 if (!Visit(E->getSubExpr()))
6451 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6452 PathE = E->path_end(); PathI != PathE; ++PathI) {
6453 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6454 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6455 if (!Result.castToBase(Base))
6462 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6463 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6464 // member can be formed.
6465 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6468 //===----------------------------------------------------------------------===//
6469 // Record Evaluation
6470 //===----------------------------------------------------------------------===//
6473 class RecordExprEvaluator
6474 : public ExprEvaluatorBase<RecordExprEvaluator> {
6479 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6480 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6482 bool Success(const APValue &V, const Expr *E) {
6486 bool ZeroInitialization(const Expr *E) {
6487 return ZeroInitialization(E, E->getType());
6489 bool ZeroInitialization(const Expr *E, QualType T);
6491 bool VisitCallExpr(const CallExpr *E) {
6492 return handleCallExpr(E, Result, &This);
6494 bool VisitCastExpr(const CastExpr *E);
6495 bool VisitInitListExpr(const InitListExpr *E);
6496 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6497 return VisitCXXConstructExpr(E, E->getType());
6499 bool VisitLambdaExpr(const LambdaExpr *E);
6500 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6501 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6502 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6504 bool VisitBinCmp(const BinaryOperator *E);
6508 /// Perform zero-initialization on an object of non-union class type.
6509 /// C++11 [dcl.init]p5:
6510 /// To zero-initialize an object or reference of type T means:
6512 /// -- if T is a (possibly cv-qualified) non-union class type,
6513 /// each non-static data member and each base-class subobject is
6514 /// zero-initialized
6515 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6516 const RecordDecl *RD,
6517 const LValue &This, APValue &Result) {
6518 assert(!RD->isUnion() && "Expected non-union class type");
6519 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6520 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6521 std::distance(RD->field_begin(), RD->field_end()));
6523 if (RD->isInvalidDecl()) return false;
6524 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6528 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6529 End = CD->bases_end(); I != End; ++I, ++Index) {
6530 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6531 LValue Subobject = This;
6532 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6534 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6535 Result.getStructBase(Index)))
6540 for (const auto *I : RD->fields()) {
6541 // -- if T is a reference type, no initialization is performed.
6542 if (I->getType()->isReferenceType())
6545 LValue Subobject = This;
6546 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6549 ImplicitValueInitExpr VIE(I->getType());
6550 if (!EvaluateInPlace(
6551 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6558 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6559 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6560 if (RD->isInvalidDecl()) return false;
6561 if (RD->isUnion()) {
6562 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6563 // object's first non-static named data member is zero-initialized
6564 RecordDecl::field_iterator I = RD->field_begin();
6565 if (I == RD->field_end()) {
6566 Result = APValue((const FieldDecl*)nullptr);
6570 LValue Subobject = This;
6571 if (!HandleLValueMember(Info, E, Subobject, *I))
6573 Result = APValue(*I);
6574 ImplicitValueInitExpr VIE(I->getType());
6575 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6578 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6579 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6583 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6586 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6587 switch (E->getCastKind()) {
6589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6591 case CK_ConstructorConversion:
6592 return Visit(E->getSubExpr());
6594 case CK_DerivedToBase:
6595 case CK_UncheckedDerivedToBase: {
6596 APValue DerivedObject;
6597 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6599 if (!DerivedObject.isStruct())
6600 return Error(E->getSubExpr());
6602 // Derived-to-base rvalue conversion: just slice off the derived part.
6603 APValue *Value = &DerivedObject;
6604 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6605 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6606 PathE = E->path_end(); PathI != PathE; ++PathI) {
6607 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6608 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6609 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6618 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6619 if (E->isTransparent())
6620 return Visit(E->getInit(0));
6622 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6623 if (RD->isInvalidDecl()) return false;
6624 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6626 if (RD->isUnion()) {
6627 const FieldDecl *Field = E->getInitializedFieldInUnion();
6628 Result = APValue(Field);
6632 // If the initializer list for a union does not contain any elements, the
6633 // first element of the union is value-initialized.
6634 // FIXME: The element should be initialized from an initializer list.
6635 // Is this difference ever observable for initializer lists which
6637 ImplicitValueInitExpr VIE(Field->getType());
6638 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6640 LValue Subobject = This;
6641 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6644 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6645 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6646 isa<CXXDefaultInitExpr>(InitExpr));
6648 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6651 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6652 if (Result.isUninit())
6653 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6654 std::distance(RD->field_begin(), RD->field_end()));
6655 unsigned ElementNo = 0;
6656 bool Success = true;
6658 // Initialize base classes.
6660 for (const auto &Base : CXXRD->bases()) {
6661 assert(ElementNo < E->getNumInits() && "missing init for base class");
6662 const Expr *Init = E->getInit(ElementNo);
6664 LValue Subobject = This;
6665 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6668 APValue &FieldVal = Result.getStructBase(ElementNo);
6669 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6670 if (!Info.noteFailure())
6678 // Initialize members.
6679 for (const auto *Field : RD->fields()) {
6680 // Anonymous bit-fields are not considered members of the class for
6681 // purposes of aggregate initialization.
6682 if (Field->isUnnamedBitfield())
6685 LValue Subobject = This;
6687 bool HaveInit = ElementNo < E->getNumInits();
6689 // FIXME: Diagnostics here should point to the end of the initializer
6690 // list, not the start.
6691 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6692 Subobject, Field, &Layout))
6695 // Perform an implicit value-initialization for members beyond the end of
6696 // the initializer list.
6697 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6698 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6700 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6701 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6702 isa<CXXDefaultInitExpr>(Init));
6704 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6705 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6706 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6707 FieldVal, Field))) {
6708 if (!Info.noteFailure())
6717 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6719 // Note that E's type is not necessarily the type of our class here; we might
6720 // be initializing an array element instead.
6721 const CXXConstructorDecl *FD = E->getConstructor();
6722 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6724 bool ZeroInit = E->requiresZeroInitialization();
6725 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6726 // If we've already performed zero-initialization, we're already done.
6727 if (!Result.isUninit())
6730 // We can get here in two different ways:
6731 // 1) We're performing value-initialization, and should zero-initialize
6733 // 2) We're performing default-initialization of an object with a trivial
6734 // constexpr default constructor, in which case we should start the
6735 // lifetimes of all the base subobjects (there can be no data member
6736 // subobjects in this case) per [basic.life]p1.
6737 // Either way, ZeroInitialization is appropriate.
6738 return ZeroInitialization(E, T);
6741 const FunctionDecl *Definition = nullptr;
6742 auto Body = FD->getBody(Definition);
6744 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6747 // Avoid materializing a temporary for an elidable copy/move constructor.
6748 if (E->isElidable() && !ZeroInit)
6749 if (const MaterializeTemporaryExpr *ME
6750 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6751 return Visit(ME->GetTemporaryExpr());
6753 if (ZeroInit && !ZeroInitialization(E, T))
6756 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6757 return HandleConstructorCall(E, This, Args,
6758 cast<CXXConstructorDecl>(Definition), Info,
6762 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6763 const CXXInheritedCtorInitExpr *E) {
6764 if (!Info.CurrentCall) {
6765 assert(Info.checkingPotentialConstantExpression());
6769 const CXXConstructorDecl *FD = E->getConstructor();
6770 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6773 const FunctionDecl *Definition = nullptr;
6774 auto Body = FD->getBody(Definition);
6776 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6779 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6780 cast<CXXConstructorDecl>(Definition), Info,
6784 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6785 const CXXStdInitializerListExpr *E) {
6786 const ConstantArrayType *ArrayType =
6787 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6790 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6793 // Get a pointer to the first element of the array.
6794 Array.addArray(Info, E, ArrayType);
6796 // FIXME: Perform the checks on the field types in SemaInit.
6797 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6798 RecordDecl::field_iterator Field = Record->field_begin();
6799 if (Field == Record->field_end())
6803 if (!Field->getType()->isPointerType() ||
6804 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6805 ArrayType->getElementType()))
6808 // FIXME: What if the initializer_list type has base classes, etc?
6809 Result = APValue(APValue::UninitStruct(), 0, 2);
6810 Array.moveInto(Result.getStructField(0));
6812 if (++Field == Record->field_end())
6815 if (Field->getType()->isPointerType() &&
6816 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6817 ArrayType->getElementType())) {
6819 if (!HandleLValueArrayAdjustment(Info, E, Array,
6820 ArrayType->getElementType(),
6821 ArrayType->getSize().getZExtValue()))
6823 Array.moveInto(Result.getStructField(1));
6824 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6826 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6830 if (++Field != Record->field_end())
6836 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6837 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6838 if (ClosureClass->isInvalidDecl()) return false;
6840 if (Info.checkingPotentialConstantExpression()) return true;
6842 const size_t NumFields =
6843 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6845 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6846 E->capture_init_end()) &&
6847 "The number of lambda capture initializers should equal the number of "
6848 "fields within the closure type");
6850 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6851 // Iterate through all the lambda's closure object's fields and initialize
6853 auto *CaptureInitIt = E->capture_init_begin();
6854 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6855 bool Success = true;
6856 for (const auto *Field : ClosureClass->fields()) {
6857 assert(CaptureInitIt != E->capture_init_end());
6858 // Get the initializer for this field
6859 Expr *const CurFieldInit = *CaptureInitIt++;
6861 // If there is no initializer, either this is a VLA or an error has
6866 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6867 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6868 if (!Info.keepEvaluatingAfterFailure())
6877 static bool EvaluateRecord(const Expr *E, const LValue &This,
6878 APValue &Result, EvalInfo &Info) {
6879 assert(E->isRValue() && E->getType()->isRecordType() &&
6880 "can't evaluate expression as a record rvalue");
6881 return RecordExprEvaluator(Info, This, Result).Visit(E);
6884 //===----------------------------------------------------------------------===//
6885 // Temporary Evaluation
6887 // Temporaries are represented in the AST as rvalues, but generally behave like
6888 // lvalues. The full-object of which the temporary is a subobject is implicitly
6889 // materialized so that a reference can bind to it.
6890 //===----------------------------------------------------------------------===//
6892 class TemporaryExprEvaluator
6893 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6895 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6896 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6898 /// Visit an expression which constructs the value of this temporary.
6899 bool VisitConstructExpr(const Expr *E) {
6900 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6901 return EvaluateInPlace(Value, Info, Result, E);
6904 bool VisitCastExpr(const CastExpr *E) {
6905 switch (E->getCastKind()) {
6907 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6909 case CK_ConstructorConversion:
6910 return VisitConstructExpr(E->getSubExpr());
6913 bool VisitInitListExpr(const InitListExpr *E) {
6914 return VisitConstructExpr(E);
6916 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6917 return VisitConstructExpr(E);
6919 bool VisitCallExpr(const CallExpr *E) {
6920 return VisitConstructExpr(E);
6922 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6923 return VisitConstructExpr(E);
6925 bool VisitLambdaExpr(const LambdaExpr *E) {
6926 return VisitConstructExpr(E);
6929 } // end anonymous namespace
6931 /// Evaluate an expression of record type as a temporary.
6932 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6933 assert(E->isRValue() && E->getType()->isRecordType());
6934 return TemporaryExprEvaluator(Info, Result).Visit(E);
6937 //===----------------------------------------------------------------------===//
6938 // Vector Evaluation
6939 //===----------------------------------------------------------------------===//
6942 class VectorExprEvaluator
6943 : public ExprEvaluatorBase<VectorExprEvaluator> {
6947 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6948 : ExprEvaluatorBaseTy(info), Result(Result) {}
6950 bool Success(ArrayRef<APValue> V, const Expr *E) {
6951 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6952 // FIXME: remove this APValue copy.
6953 Result = APValue(V.data(), V.size());
6956 bool Success(const APValue &V, const Expr *E) {
6957 assert(V.isVector());
6961 bool ZeroInitialization(const Expr *E);
6963 bool VisitUnaryReal(const UnaryOperator *E)
6964 { return Visit(E->getSubExpr()); }
6965 bool VisitCastExpr(const CastExpr* E);
6966 bool VisitInitListExpr(const InitListExpr *E);
6967 bool VisitUnaryImag(const UnaryOperator *E);
6968 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6969 // binary comparisons, binary and/or/xor,
6970 // shufflevector, ExtVectorElementExpr
6972 } // end anonymous namespace
6974 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6975 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6976 return VectorExprEvaluator(Info, Result).Visit(E);
6979 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6980 const VectorType *VTy = E->getType()->castAs<VectorType>();
6981 unsigned NElts = VTy->getNumElements();
6983 const Expr *SE = E->getSubExpr();
6984 QualType SETy = SE->getType();
6986 switch (E->getCastKind()) {
6987 case CK_VectorSplat: {
6988 APValue Val = APValue();
6989 if (SETy->isIntegerType()) {
6991 if (!EvaluateInteger(SE, IntResult, Info))
6993 Val = APValue(std::move(IntResult));
6994 } else if (SETy->isRealFloatingType()) {
6995 APFloat FloatResult(0.0);
6996 if (!EvaluateFloat(SE, FloatResult, Info))
6998 Val = APValue(std::move(FloatResult));
7003 // Splat and create vector APValue.
7004 SmallVector<APValue, 4> Elts(NElts, Val);
7005 return Success(Elts, E);
7008 // Evaluate the operand into an APInt we can extract from.
7009 llvm::APInt SValInt;
7010 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
7012 // Extract the elements
7013 QualType EltTy = VTy->getElementType();
7014 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
7015 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
7016 SmallVector<APValue, 4> Elts;
7017 if (EltTy->isRealFloatingType()) {
7018 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
7019 unsigned FloatEltSize = EltSize;
7020 if (&Sem == &APFloat::x87DoubleExtended())
7022 for (unsigned i = 0; i < NElts; i++) {
7025 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
7027 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
7028 Elts.push_back(APValue(APFloat(Sem, Elt)));
7030 } else if (EltTy->isIntegerType()) {
7031 for (unsigned i = 0; i < NElts; i++) {
7034 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
7036 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
7037 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
7042 return Success(Elts, E);
7045 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7050 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7051 const VectorType *VT = E->getType()->castAs<VectorType>();
7052 unsigned NumInits = E->getNumInits();
7053 unsigned NumElements = VT->getNumElements();
7055 QualType EltTy = VT->getElementType();
7056 SmallVector<APValue, 4> Elements;
7058 // The number of initializers can be less than the number of
7059 // vector elements. For OpenCL, this can be due to nested vector
7060 // initialization. For GCC compatibility, missing trailing elements
7061 // should be initialized with zeroes.
7062 unsigned CountInits = 0, CountElts = 0;
7063 while (CountElts < NumElements) {
7064 // Handle nested vector initialization.
7065 if (CountInits < NumInits
7066 && E->getInit(CountInits)->getType()->isVectorType()) {
7068 if (!EvaluateVector(E->getInit(CountInits), v, Info))
7070 unsigned vlen = v.getVectorLength();
7071 for (unsigned j = 0; j < vlen; j++)
7072 Elements.push_back(v.getVectorElt(j));
7074 } else if (EltTy->isIntegerType()) {
7075 llvm::APSInt sInt(32);
7076 if (CountInits < NumInits) {
7077 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7079 } else // trailing integer zero.
7080 sInt = Info.Ctx.MakeIntValue(0, EltTy);
7081 Elements.push_back(APValue(sInt));
7084 llvm::APFloat f(0.0);
7085 if (CountInits < NumInits) {
7086 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7088 } else // trailing float zero.
7089 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7090 Elements.push_back(APValue(f));
7095 return Success(Elements, E);
7099 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7100 const VectorType *VT = E->getType()->getAs<VectorType>();
7101 QualType EltTy = VT->getElementType();
7102 APValue ZeroElement;
7103 if (EltTy->isIntegerType())
7104 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7107 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7109 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7110 return Success(Elements, E);
7113 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7114 VisitIgnoredValue(E->getSubExpr());
7115 return ZeroInitialization(E);
7118 //===----------------------------------------------------------------------===//
7120 //===----------------------------------------------------------------------===//
7123 class ArrayExprEvaluator
7124 : public ExprEvaluatorBase<ArrayExprEvaluator> {
7129 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7130 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7132 bool Success(const APValue &V, const Expr *E) {
7133 assert((V.isArray() || V.isLValue()) &&
7134 "expected array or string literal");
7139 bool ZeroInitialization(const Expr *E) {
7140 const ConstantArrayType *CAT =
7141 Info.Ctx.getAsConstantArrayType(E->getType());
7145 Result = APValue(APValue::UninitArray(), 0,
7146 CAT->getSize().getZExtValue());
7147 if (!Result.hasArrayFiller()) return true;
7149 // Zero-initialize all elements.
7150 LValue Subobject = This;
7151 Subobject.addArray(Info, E, CAT);
7152 ImplicitValueInitExpr VIE(CAT->getElementType());
7153 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7156 bool VisitCallExpr(const CallExpr *E) {
7157 return handleCallExpr(E, Result, &This);
7159 bool VisitInitListExpr(const InitListExpr *E);
7160 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7161 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7162 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7163 const LValue &Subobject,
7164 APValue *Value, QualType Type);
7166 } // end anonymous namespace
7168 static bool EvaluateArray(const Expr *E, const LValue &This,
7169 APValue &Result, EvalInfo &Info) {
7170 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7171 return ArrayExprEvaluator(Info, This, Result).Visit(E);
7174 // Return true iff the given array filler may depend on the element index.
7175 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7176 // For now, just whitelist non-class value-initialization and initialization
7177 // lists comprised of them.
7178 if (isa<ImplicitValueInitExpr>(FillerExpr))
7180 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7181 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7182 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7190 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7191 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7195 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7196 // an appropriately-typed string literal enclosed in braces.
7197 if (E->isStringLiteralInit()) {
7199 if (!EvaluateLValue(E->getInit(0), LV, Info))
7203 return Success(Val, E);
7206 bool Success = true;
7208 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7209 "zero-initialized array shouldn't have any initialized elts");
7211 if (Result.isArray() && Result.hasArrayFiller())
7212 Filler = Result.getArrayFiller();
7214 unsigned NumEltsToInit = E->getNumInits();
7215 unsigned NumElts = CAT->getSize().getZExtValue();
7216 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7218 // If the initializer might depend on the array index, run it for each
7220 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7221 NumEltsToInit = NumElts;
7223 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7224 << NumEltsToInit << ".\n");
7226 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7228 // If the array was previously zero-initialized, preserve the
7229 // zero-initialized values.
7230 if (!Filler.isUninit()) {
7231 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7232 Result.getArrayInitializedElt(I) = Filler;
7233 if (Result.hasArrayFiller())
7234 Result.getArrayFiller() = Filler;
7237 LValue Subobject = This;
7238 Subobject.addArray(Info, E, CAT);
7239 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7241 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7242 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7243 Info, Subobject, Init) ||
7244 !HandleLValueArrayAdjustment(Info, Init, Subobject,
7245 CAT->getElementType(), 1)) {
7246 if (!Info.noteFailure())
7252 if (!Result.hasArrayFiller())
7255 // If we get here, we have a trivial filler, which we can just evaluate
7256 // once and splat over the rest of the array elements.
7257 assert(FillerExpr && "no array filler for incomplete init list");
7258 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7259 FillerExpr) && Success;
7262 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7263 if (E->getCommonExpr() &&
7264 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7265 Info, E->getCommonExpr()->getSourceExpr()))
7268 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7270 uint64_t Elements = CAT->getSize().getZExtValue();
7271 Result = APValue(APValue::UninitArray(), Elements, Elements);
7273 LValue Subobject = This;
7274 Subobject.addArray(Info, E, CAT);
7276 bool Success = true;
7277 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7278 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7279 Info, Subobject, E->getSubExpr()) ||
7280 !HandleLValueArrayAdjustment(Info, E, Subobject,
7281 CAT->getElementType(), 1)) {
7282 if (!Info.noteFailure())
7291 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7292 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7295 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7296 const LValue &Subobject,
7299 bool HadZeroInit = !Value->isUninit();
7301 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7302 unsigned N = CAT->getSize().getZExtValue();
7304 // Preserve the array filler if we had prior zero-initialization.
7306 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7309 *Value = APValue(APValue::UninitArray(), N, N);
7312 for (unsigned I = 0; I != N; ++I)
7313 Value->getArrayInitializedElt(I) = Filler;
7315 // Initialize the elements.
7316 LValue ArrayElt = Subobject;
7317 ArrayElt.addArray(Info, E, CAT);
7318 for (unsigned I = 0; I != N; ++I)
7319 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7320 CAT->getElementType()) ||
7321 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7322 CAT->getElementType(), 1))
7328 if (!Type->isRecordType())
7331 return RecordExprEvaluator(Info, Subobject, *Value)
7332 .VisitCXXConstructExpr(E, Type);
7335 //===----------------------------------------------------------------------===//
7336 // Integer Evaluation
7338 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7339 // types and back in constant folding. Integer values are thus represented
7340 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7341 //===----------------------------------------------------------------------===//
7344 class IntExprEvaluator
7345 : public ExprEvaluatorBase<IntExprEvaluator> {
7348 IntExprEvaluator(EvalInfo &info, APValue &result)
7349 : ExprEvaluatorBaseTy(info), Result(result) {}
7351 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7352 assert(E->getType()->isIntegralOrEnumerationType() &&
7353 "Invalid evaluation result.");
7354 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7355 "Invalid evaluation result.");
7356 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7357 "Invalid evaluation result.");
7358 Result = APValue(SI);
7361 bool Success(const llvm::APSInt &SI, const Expr *E) {
7362 return Success(SI, E, Result);
7365 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7366 assert(E->getType()->isIntegralOrEnumerationType() &&
7367 "Invalid evaluation result.");
7368 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7369 "Invalid evaluation result.");
7370 Result = APValue(APSInt(I));
7371 Result.getInt().setIsUnsigned(
7372 E->getType()->isUnsignedIntegerOrEnumerationType());
7375 bool Success(const llvm::APInt &I, const Expr *E) {
7376 return Success(I, E, Result);
7379 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7380 assert(E->getType()->isIntegralOrEnumerationType() &&
7381 "Invalid evaluation result.");
7382 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7385 bool Success(uint64_t Value, const Expr *E) {
7386 return Success(Value, E, Result);
7389 bool Success(CharUnits Size, const Expr *E) {
7390 return Success(Size.getQuantity(), E);
7393 bool Success(const APValue &V, const Expr *E) {
7394 if (V.isLValue() || V.isAddrLabelDiff()) {
7398 return Success(V.getInt(), E);
7401 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7403 //===--------------------------------------------------------------------===//
7405 //===--------------------------------------------------------------------===//
7407 bool VisitConstantExpr(const ConstantExpr *E);
7409 bool VisitIntegerLiteral(const IntegerLiteral *E) {
7410 return Success(E->getValue(), E);
7412 bool VisitCharacterLiteral(const CharacterLiteral *E) {
7413 return Success(E->getValue(), E);
7416 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7417 bool VisitDeclRefExpr(const DeclRefExpr *E) {
7418 if (CheckReferencedDecl(E, E->getDecl()))
7421 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7423 bool VisitMemberExpr(const MemberExpr *E) {
7424 if (CheckReferencedDecl(E, E->getMemberDecl())) {
7425 VisitIgnoredBaseExpression(E->getBase());
7429 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7432 bool VisitCallExpr(const CallExpr *E);
7433 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7434 bool VisitBinaryOperator(const BinaryOperator *E);
7435 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7436 bool VisitUnaryOperator(const UnaryOperator *E);
7438 bool VisitCastExpr(const CastExpr* E);
7439 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7441 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7442 return Success(E->getValue(), E);
7445 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7446 return Success(E->getValue(), E);
7449 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7450 if (Info.ArrayInitIndex == uint64_t(-1)) {
7451 // We were asked to evaluate this subexpression independent of the
7452 // enclosing ArrayInitLoopExpr. We can't do that.
7456 return Success(Info.ArrayInitIndex, E);
7459 // Note, GNU defines __null as an integer, not a pointer.
7460 bool VisitGNUNullExpr(const GNUNullExpr *E) {
7461 return ZeroInitialization(E);
7464 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7465 return Success(E->getValue(), E);
7468 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7469 return Success(E->getValue(), E);
7472 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7473 return Success(E->getValue(), E);
7476 bool VisitUnaryReal(const UnaryOperator *E);
7477 bool VisitUnaryImag(const UnaryOperator *E);
7479 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7480 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7482 // FIXME: Missing: array subscript of vector, member of vector
7485 class FixedPointExprEvaluator
7486 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7490 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7491 : ExprEvaluatorBaseTy(info), Result(result) {}
7493 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7494 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7495 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7496 "Invalid evaluation result.");
7497 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7498 "Invalid evaluation result.");
7499 Result = APValue(SI);
7502 bool Success(const llvm::APSInt &SI, const Expr *E) {
7503 return Success(SI, E, Result);
7506 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7507 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7508 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7509 "Invalid evaluation result.");
7510 Result = APValue(APSInt(I));
7511 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7514 bool Success(const llvm::APInt &I, const Expr *E) {
7515 return Success(I, E, Result);
7518 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7519 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7520 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7523 bool Success(uint64_t Value, const Expr *E) {
7524 return Success(Value, E, Result);
7527 bool Success(CharUnits Size, const Expr *E) {
7528 return Success(Size.getQuantity(), E);
7531 bool Success(const APValue &V, const Expr *E) {
7532 if (V.isLValue() || V.isAddrLabelDiff()) {
7536 return Success(V.getInt(), E);
7539 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7541 //===--------------------------------------------------------------------===//
7543 //===--------------------------------------------------------------------===//
7545 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7546 return Success(E->getValue(), E);
7549 bool VisitUnaryOperator(const UnaryOperator *E);
7551 } // end anonymous namespace
7553 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7554 /// produce either the integer value or a pointer.
7556 /// GCC has a heinous extension which folds casts between pointer types and
7557 /// pointer-sized integral types. We support this by allowing the evaluation of
7558 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7559 /// Some simple arithmetic on such values is supported (they are treated much
7561 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7563 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7564 return IntExprEvaluator(Info, Result).Visit(E);
7567 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7569 if (!EvaluateIntegerOrLValue(E, Val, Info))
7572 // FIXME: It would be better to produce the diagnostic for casting
7573 // a pointer to an integer.
7574 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7577 Result = Val.getInt();
7581 /// Check whether the given declaration can be directly converted to an integral
7582 /// rvalue. If not, no diagnostic is produced; there are other things we can
7584 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7585 // Enums are integer constant exprs.
7586 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7587 // Check for signedness/width mismatches between E type and ECD value.
7588 bool SameSign = (ECD->getInitVal().isSigned()
7589 == E->getType()->isSignedIntegerOrEnumerationType());
7590 bool SameWidth = (ECD->getInitVal().getBitWidth()
7591 == Info.Ctx.getIntWidth(E->getType()));
7592 if (SameSign && SameWidth)
7593 return Success(ECD->getInitVal(), E);
7595 // Get rid of mismatch (otherwise Success assertions will fail)
7596 // by computing a new value matching the type of E.
7597 llvm::APSInt Val = ECD->getInitVal();
7599 Val.setIsSigned(!ECD->getInitVal().isSigned());
7601 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7602 return Success(Val, E);
7608 /// Values returned by __builtin_classify_type, chosen to match the values
7609 /// produced by GCC's builtin.
7610 enum class GCCTypeClass {
7614 // GCC reserves 2 for character types, but instead classifies them as
7619 // GCC reserves 6 for references, but appears to never use it (because
7620 // expressions never have reference type, presumably).
7621 PointerToDataMember = 7,
7624 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7625 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7626 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7627 // uses 12 for that purpose, same as for a class or struct. Maybe it
7628 // internally implements a pointer to member as a struct? Who knows.
7629 PointerToMemberFunction = 12, // Not a bug, see above.
7632 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7633 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7634 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7638 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7641 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7642 assert(!T->isDependentType() && "unexpected dependent type");
7644 QualType CanTy = T.getCanonicalType();
7645 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7647 switch (CanTy->getTypeClass()) {
7648 #define TYPE(ID, BASE)
7649 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7650 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7651 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7652 #include "clang/AST/TypeNodes.def"
7654 case Type::DeducedTemplateSpecialization:
7655 llvm_unreachable("unexpected non-canonical or dependent type");
7658 switch (BT->getKind()) {
7659 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7660 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7661 case BuiltinType::ID: return GCCTypeClass::Integer;
7662 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7663 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7664 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7665 case BuiltinType::ID: break;
7666 #include "clang/AST/BuiltinTypes.def"
7667 case BuiltinType::Void:
7668 return GCCTypeClass::Void;
7670 case BuiltinType::Bool:
7671 return GCCTypeClass::Bool;
7673 case BuiltinType::Char_U:
7674 case BuiltinType::UChar:
7675 case BuiltinType::WChar_U:
7676 case BuiltinType::Char8:
7677 case BuiltinType::Char16:
7678 case BuiltinType::Char32:
7679 case BuiltinType::UShort:
7680 case BuiltinType::UInt:
7681 case BuiltinType::ULong:
7682 case BuiltinType::ULongLong:
7683 case BuiltinType::UInt128:
7684 return GCCTypeClass::Integer;
7686 case BuiltinType::UShortAccum:
7687 case BuiltinType::UAccum:
7688 case BuiltinType::ULongAccum:
7689 case BuiltinType::UShortFract:
7690 case BuiltinType::UFract:
7691 case BuiltinType::ULongFract:
7692 case BuiltinType::SatUShortAccum:
7693 case BuiltinType::SatUAccum:
7694 case BuiltinType::SatULongAccum:
7695 case BuiltinType::SatUShortFract:
7696 case BuiltinType::SatUFract:
7697 case BuiltinType::SatULongFract:
7698 return GCCTypeClass::None;
7700 case BuiltinType::NullPtr:
7702 case BuiltinType::ObjCId:
7703 case BuiltinType::ObjCClass:
7704 case BuiltinType::ObjCSel:
7705 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7706 case BuiltinType::Id:
7707 #include "clang/Basic/OpenCLImageTypes.def"
7708 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7709 case BuiltinType::Id:
7710 #include "clang/Basic/OpenCLExtensionTypes.def"
7711 case BuiltinType::OCLSampler:
7712 case BuiltinType::OCLEvent:
7713 case BuiltinType::OCLClkEvent:
7714 case BuiltinType::OCLQueue:
7715 case BuiltinType::OCLReserveID:
7716 return GCCTypeClass::None;
7718 case BuiltinType::Dependent:
7719 llvm_unreachable("unexpected dependent type");
7721 llvm_unreachable("unexpected placeholder type");
7724 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7727 case Type::ConstantArray:
7728 case Type::VariableArray:
7729 case Type::IncompleteArray:
7730 case Type::FunctionNoProto:
7731 case Type::FunctionProto:
7732 return GCCTypeClass::Pointer;
7734 case Type::MemberPointer:
7735 return CanTy->isMemberDataPointerType()
7736 ? GCCTypeClass::PointerToDataMember
7737 : GCCTypeClass::PointerToMemberFunction;
7740 return GCCTypeClass::Complex;
7743 return CanTy->isUnionType() ? GCCTypeClass::Union
7744 : GCCTypeClass::ClassOrStruct;
7747 // GCC classifies _Atomic T the same as T.
7748 return EvaluateBuiltinClassifyType(
7749 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7751 case Type::BlockPointer:
7753 case Type::ExtVector:
7754 case Type::ObjCObject:
7755 case Type::ObjCInterface:
7756 case Type::ObjCObjectPointer:
7758 // GCC classifies vectors as None. We follow its lead and classify all
7759 // other types that don't fit into the regular classification the same way.
7760 return GCCTypeClass::None;
7762 case Type::LValueReference:
7763 case Type::RValueReference:
7764 llvm_unreachable("invalid type for expression");
7767 llvm_unreachable("unexpected type class");
7770 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7773 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7774 // If no argument was supplied, default to None. This isn't
7775 // ideal, however it is what gcc does.
7776 if (E->getNumArgs() == 0)
7777 return GCCTypeClass::None;
7779 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7780 // being an ICE, but still folds it to a constant using the type of the first
7782 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7785 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7786 /// __builtin_constant_p when applied to the given lvalue.
7788 /// An lvalue is only "constant" if it is a pointer or reference to the first
7789 /// character of a string literal.
7790 template<typename LValue>
7791 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7792 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7793 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7796 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7797 /// GCC as we can manage.
7798 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7799 QualType ArgType = Arg->getType();
7801 // __builtin_constant_p always has one operand. The rules which gcc follows
7802 // are not precisely documented, but are as follows:
7804 // - If the operand is of integral, floating, complex or enumeration type,
7805 // and can be folded to a known value of that type, it returns 1.
7806 // - If the operand and can be folded to a pointer to the first character
7807 // of a string literal (or such a pointer cast to an integral type), it
7810 // Otherwise, it returns 0.
7812 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7813 // its support for this does not currently work.
7814 if (ArgType->isIntegralOrEnumerationType()) {
7815 Expr::EvalResult Result;
7816 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7819 APValue &V = Result.Val;
7820 if (V.getKind() == APValue::Int)
7822 if (V.getKind() == APValue::LValue)
7823 return EvaluateBuiltinConstantPForLValue(V);
7824 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7825 return Arg->isEvaluatable(Ctx);
7826 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7828 Expr::EvalStatus Status;
7829 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7830 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7831 : EvaluatePointer(Arg, LV, Info)) &&
7832 !Status.HasSideEffects)
7833 return EvaluateBuiltinConstantPForLValue(LV);
7836 // Anything else isn't considered to be sufficiently constant.
7840 /// Retrieves the "underlying object type" of the given expression,
7841 /// as used by __builtin_object_size.
7842 static QualType getObjectType(APValue::LValueBase B) {
7843 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7844 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7845 return VD->getType();
7846 } else if (const Expr *E = B.get<const Expr*>()) {
7847 if (isa<CompoundLiteralExpr>(E))
7848 return E->getType();
7854 /// A more selective version of E->IgnoreParenCasts for
7855 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7856 /// to change the type of E.
7857 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7859 /// Always returns an RValue with a pointer representation.
7860 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7861 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7863 auto *NoParens = E->IgnoreParens();
7864 auto *Cast = dyn_cast<CastExpr>(NoParens);
7865 if (Cast == nullptr)
7868 // We only conservatively allow a few kinds of casts, because this code is
7869 // inherently a simple solution that seeks to support the common case.
7870 auto CastKind = Cast->getCastKind();
7871 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7872 CastKind != CK_AddressSpaceConversion)
7875 auto *SubExpr = Cast->getSubExpr();
7876 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7878 return ignorePointerCastsAndParens(SubExpr);
7881 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7882 /// record layout. e.g.
7883 /// struct { struct { int a, b; } fst, snd; } obj;
7889 /// obj.snd.b // yes
7891 /// Please note: this function is specialized for how __builtin_object_size
7892 /// views "objects".
7894 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7895 /// correct result, it will always return true.
7896 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7897 assert(!LVal.Designator.Invalid);
7899 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7900 const RecordDecl *Parent = FD->getParent();
7901 Invalid = Parent->isInvalidDecl();
7902 if (Invalid || Parent->isUnion())
7904 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7905 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7908 auto &Base = LVal.getLValueBase();
7909 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7910 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7912 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7914 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7915 for (auto *FD : IFD->chain()) {
7917 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7924 QualType BaseType = getType(Base);
7925 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7926 // If we don't know the array bound, conservatively assume we're looking at
7927 // the final array element.
7929 if (BaseType->isIncompleteArrayType())
7930 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7932 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7935 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7936 const auto &Entry = LVal.Designator.Entries[I];
7937 if (BaseType->isArrayType()) {
7938 // Because __builtin_object_size treats arrays as objects, we can ignore
7939 // the index iff this is the last array in the Designator.
7942 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7943 uint64_t Index = Entry.ArrayIndex;
7944 if (Index + 1 != CAT->getSize())
7946 BaseType = CAT->getElementType();
7947 } else if (BaseType->isAnyComplexType()) {
7948 const auto *CT = BaseType->castAs<ComplexType>();
7949 uint64_t Index = Entry.ArrayIndex;
7952 BaseType = CT->getElementType();
7953 } else if (auto *FD = getAsField(Entry)) {
7955 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7957 BaseType = FD->getType();
7959 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7966 /// Tests to see if the LValue has a user-specified designator (that isn't
7967 /// necessarily valid). Note that this always returns 'true' if the LValue has
7968 /// an unsized array as its first designator entry, because there's currently no
7969 /// way to tell if the user typed *foo or foo[0].
7970 static bool refersToCompleteObject(const LValue &LVal) {
7971 if (LVal.Designator.Invalid)
7974 if (!LVal.Designator.Entries.empty())
7975 return LVal.Designator.isMostDerivedAnUnsizedArray();
7977 if (!LVal.InvalidBase)
7980 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7982 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7983 return !E || !isa<MemberExpr>(E);
7986 /// Attempts to detect a user writing into a piece of memory that's impossible
7987 /// to figure out the size of by just using types.
7988 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7989 const SubobjectDesignator &Designator = LVal.Designator;
7991 // - Users can only write off of the end when we have an invalid base. Invalid
7992 // bases imply we don't know where the memory came from.
7993 // - We used to be a bit more aggressive here; we'd only be conservative if
7994 // the array at the end was flexible, or if it had 0 or 1 elements. This
7995 // broke some common standard library extensions (PR30346), but was
7996 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7997 // with some sort of whitelist. OTOH, it seems that GCC is always
7998 // conservative with the last element in structs (if it's an array), so our
7999 // current behavior is more compatible than a whitelisting approach would
8001 return LVal.InvalidBase &&
8002 Designator.Entries.size() == Designator.MostDerivedPathLength &&
8003 Designator.MostDerivedIsArrayElement &&
8004 isDesignatorAtObjectEnd(Ctx, LVal);
8007 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
8008 /// Fails if the conversion would cause loss of precision.
8009 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
8010 CharUnits &Result) {
8011 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
8012 if (Int.ugt(CharUnitsMax))
8014 Result = CharUnits::fromQuantity(Int.getZExtValue());
8018 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
8019 /// determine how many bytes exist from the beginning of the object to either
8020 /// the end of the current subobject, or the end of the object itself, depending
8021 /// on what the LValue looks like + the value of Type.
8023 /// If this returns false, the value of Result is undefined.
8024 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
8025 unsigned Type, const LValue &LVal,
8026 CharUnits &EndOffset) {
8027 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
8029 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
8030 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
8032 return HandleSizeof(Info, ExprLoc, Ty, Result);
8035 // We want to evaluate the size of the entire object. This is a valid fallback
8036 // for when Type=1 and the designator is invalid, because we're asked for an
8038 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
8039 // Type=3 wants a lower bound, so we can't fall back to this.
8040 if (Type == 3 && !DetermineForCompleteObject)
8043 llvm::APInt APEndOffset;
8044 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8045 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8046 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8048 if (LVal.InvalidBase)
8051 QualType BaseTy = getObjectType(LVal.getLValueBase());
8052 return CheckedHandleSizeof(BaseTy, EndOffset);
8055 // We want to evaluate the size of a subobject.
8056 const SubobjectDesignator &Designator = LVal.Designator;
8058 // The following is a moderately common idiom in C:
8060 // struct Foo { int a; char c[1]; };
8061 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8062 // strcpy(&F->c[0], Bar);
8064 // In order to not break too much legacy code, we need to support it.
8065 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8066 // If we can resolve this to an alloc_size call, we can hand that back,
8067 // because we know for certain how many bytes there are to write to.
8068 llvm::APInt APEndOffset;
8069 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8070 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8071 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8073 // If we cannot determine the size of the initial allocation, then we can't
8074 // given an accurate upper-bound. However, we are still able to give
8075 // conservative lower-bounds for Type=3.
8080 CharUnits BytesPerElem;
8081 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8084 // According to the GCC documentation, we want the size of the subobject
8085 // denoted by the pointer. But that's not quite right -- what we actually
8086 // want is the size of the immediately-enclosing array, if there is one.
8087 int64_t ElemsRemaining;
8088 if (Designator.MostDerivedIsArrayElement &&
8089 Designator.Entries.size() == Designator.MostDerivedPathLength) {
8090 uint64_t ArraySize = Designator.getMostDerivedArraySize();
8091 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8092 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8094 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8097 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8101 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8102 /// returns true and stores the result in @p Size.
8104 /// If @p WasError is non-null, this will report whether the failure to evaluate
8105 /// is to be treated as an Error in IntExprEvaluator.
8106 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8107 EvalInfo &Info, uint64_t &Size) {
8108 // Determine the denoted object.
8111 // The operand of __builtin_object_size is never evaluated for side-effects.
8112 // If there are any, but we can determine the pointed-to object anyway, then
8113 // ignore the side-effects.
8114 SpeculativeEvaluationRAII SpeculativeEval(Info);
8115 IgnoreSideEffectsRAII Fold(Info);
8117 if (E->isGLValue()) {
8118 // It's possible for us to be given GLValues if we're called via
8119 // Expr::tryEvaluateObjectSize.
8121 if (!EvaluateAsRValue(Info, E, RVal))
8123 LVal.setFrom(Info.Ctx, RVal);
8124 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8125 /*InvalidBaseOK=*/true))
8129 // If we point to before the start of the object, there are no accessible
8131 if (LVal.getLValueOffset().isNegative()) {
8136 CharUnits EndOffset;
8137 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8140 // If we've fallen outside of the end offset, just pretend there's nothing to
8141 // write to/read from.
8142 if (EndOffset <= LVal.getLValueOffset())
8145 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8149 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
8150 llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
8151 return ExprEvaluatorBaseTy::VisitConstantExpr(E);
8154 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8155 if (unsigned BuiltinOp = E->getBuiltinCallee())
8156 return VisitBuiltinCallExpr(E, BuiltinOp);
8158 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8161 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8162 unsigned BuiltinOp) {
8163 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8165 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8167 case Builtin::BI__builtin_object_size: {
8168 // The type was checked when we built the expression.
8170 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8171 assert(Type <= 3 && "unexpected type");
8174 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8175 return Success(Size, E);
8177 if (E->getArg(0)->HasSideEffects(Info.Ctx))
8178 return Success((Type & 2) ? 0 : -1, E);
8180 // Expression had no side effects, but we couldn't statically determine the
8181 // size of the referenced object.
8182 switch (Info.EvalMode) {
8183 case EvalInfo::EM_ConstantExpression:
8184 case EvalInfo::EM_PotentialConstantExpression:
8185 case EvalInfo::EM_ConstantFold:
8186 case EvalInfo::EM_EvaluateForOverflow:
8187 case EvalInfo::EM_IgnoreSideEffects:
8188 // Leave it to IR generation.
8190 case EvalInfo::EM_ConstantExpressionUnevaluated:
8191 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8192 // Reduce it to a constant now.
8193 return Success((Type & 2) ? 0 : -1, E);
8196 llvm_unreachable("unexpected EvalMode");
8199 case Builtin::BI__builtin_os_log_format_buffer_size: {
8200 analyze_os_log::OSLogBufferLayout Layout;
8201 analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8202 return Success(Layout.size().getQuantity(), E);
8205 case Builtin::BI__builtin_bswap16:
8206 case Builtin::BI__builtin_bswap32:
8207 case Builtin::BI__builtin_bswap64: {
8209 if (!EvaluateInteger(E->getArg(0), Val, Info))
8212 return Success(Val.byteSwap(), E);
8215 case Builtin::BI__builtin_classify_type:
8216 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8218 case Builtin::BI__builtin_clrsb:
8219 case Builtin::BI__builtin_clrsbl:
8220 case Builtin::BI__builtin_clrsbll: {
8222 if (!EvaluateInteger(E->getArg(0), Val, Info))
8225 return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8228 case Builtin::BI__builtin_clz:
8229 case Builtin::BI__builtin_clzl:
8230 case Builtin::BI__builtin_clzll:
8231 case Builtin::BI__builtin_clzs: {
8233 if (!EvaluateInteger(E->getArg(0), Val, Info))
8238 return Success(Val.countLeadingZeros(), E);
8241 case Builtin::BI__builtin_constant_p: {
8242 auto Arg = E->getArg(0);
8243 if (EvaluateBuiltinConstantP(Info.Ctx, Arg))
8244 return Success(true, E);
8245 auto ArgTy = Arg->IgnoreImplicit()->getType();
8246 if (!Info.InConstantContext && !Arg->HasSideEffects(Info.Ctx) &&
8247 !ArgTy->isAggregateType() && !ArgTy->isPointerType()) {
8248 // We can delay calculation of __builtin_constant_p until after
8249 // inlining. Note: This diagnostic won't be shown to the user.
8250 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8253 return Success(false, E);
8256 case Builtin::BI__builtin_ctz:
8257 case Builtin::BI__builtin_ctzl:
8258 case Builtin::BI__builtin_ctzll:
8259 case Builtin::BI__builtin_ctzs: {
8261 if (!EvaluateInteger(E->getArg(0), Val, Info))
8266 return Success(Val.countTrailingZeros(), E);
8269 case Builtin::BI__builtin_eh_return_data_regno: {
8270 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8271 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8272 return Success(Operand, E);
8275 case Builtin::BI__builtin_expect:
8276 return Visit(E->getArg(0));
8278 case Builtin::BI__builtin_ffs:
8279 case Builtin::BI__builtin_ffsl:
8280 case Builtin::BI__builtin_ffsll: {
8282 if (!EvaluateInteger(E->getArg(0), Val, Info))
8285 unsigned N = Val.countTrailingZeros();
8286 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8289 case Builtin::BI__builtin_fpclassify: {
8291 if (!EvaluateFloat(E->getArg(5), Val, Info))
8294 switch (Val.getCategory()) {
8295 case APFloat::fcNaN: Arg = 0; break;
8296 case APFloat::fcInfinity: Arg = 1; break;
8297 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8298 case APFloat::fcZero: Arg = 4; break;
8300 return Visit(E->getArg(Arg));
8303 case Builtin::BI__builtin_isinf_sign: {
8305 return EvaluateFloat(E->getArg(0), Val, Info) &&
8306 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8309 case Builtin::BI__builtin_isinf: {
8311 return EvaluateFloat(E->getArg(0), Val, Info) &&
8312 Success(Val.isInfinity() ? 1 : 0, E);
8315 case Builtin::BI__builtin_isfinite: {
8317 return EvaluateFloat(E->getArg(0), Val, Info) &&
8318 Success(Val.isFinite() ? 1 : 0, E);
8321 case Builtin::BI__builtin_isnan: {
8323 return EvaluateFloat(E->getArg(0), Val, Info) &&
8324 Success(Val.isNaN() ? 1 : 0, E);
8327 case Builtin::BI__builtin_isnormal: {
8329 return EvaluateFloat(E->getArg(0), Val, Info) &&
8330 Success(Val.isNormal() ? 1 : 0, E);
8333 case Builtin::BI__builtin_parity:
8334 case Builtin::BI__builtin_parityl:
8335 case Builtin::BI__builtin_parityll: {
8337 if (!EvaluateInteger(E->getArg(0), Val, Info))
8340 return Success(Val.countPopulation() % 2, E);
8343 case Builtin::BI__builtin_popcount:
8344 case Builtin::BI__builtin_popcountl:
8345 case Builtin::BI__builtin_popcountll: {
8347 if (!EvaluateInteger(E->getArg(0), Val, Info))
8350 return Success(Val.countPopulation(), E);
8353 case Builtin::BIstrlen:
8354 case Builtin::BIwcslen:
8355 // A call to strlen is not a constant expression.
8356 if (Info.getLangOpts().CPlusPlus11)
8357 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8358 << /*isConstexpr*/0 << /*isConstructor*/0
8359 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8361 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8363 case Builtin::BI__builtin_strlen:
8364 case Builtin::BI__builtin_wcslen: {
8365 // As an extension, we support __builtin_strlen() as a constant expression,
8366 // and support folding strlen() to a constant.
8368 if (!EvaluatePointer(E->getArg(0), String, Info))
8371 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8373 // Fast path: if it's a string literal, search the string value.
8374 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8375 String.getLValueBase().dyn_cast<const Expr *>())) {
8376 // The string literal may have embedded null characters. Find the first
8377 // one and truncate there.
8378 StringRef Str = S->getBytes();
8379 int64_t Off = String.Offset.getQuantity();
8380 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8381 S->getCharByteWidth() == 1 &&
8382 // FIXME: Add fast-path for wchar_t too.
8383 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8384 Str = Str.substr(Off);
8386 StringRef::size_type Pos = Str.find(0);
8387 if (Pos != StringRef::npos)
8388 Str = Str.substr(0, Pos);
8390 return Success(Str.size(), E);
8393 // Fall through to slow path to issue appropriate diagnostic.
8396 // Slow path: scan the bytes of the string looking for the terminating 0.
8397 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8399 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8403 return Success(Strlen, E);
8404 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8409 case Builtin::BIstrcmp:
8410 case Builtin::BIwcscmp:
8411 case Builtin::BIstrncmp:
8412 case Builtin::BIwcsncmp:
8413 case Builtin::BImemcmp:
8414 case Builtin::BIwmemcmp:
8415 // A call to strlen is not a constant expression.
8416 if (Info.getLangOpts().CPlusPlus11)
8417 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8418 << /*isConstexpr*/0 << /*isConstructor*/0
8419 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8421 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8423 case Builtin::BI__builtin_strcmp:
8424 case Builtin::BI__builtin_wcscmp:
8425 case Builtin::BI__builtin_strncmp:
8426 case Builtin::BI__builtin_wcsncmp:
8427 case Builtin::BI__builtin_memcmp:
8428 case Builtin::BI__builtin_wmemcmp: {
8429 LValue String1, String2;
8430 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8431 !EvaluatePointer(E->getArg(1), String2, Info))
8434 uint64_t MaxLength = uint64_t(-1);
8435 if (BuiltinOp != Builtin::BIstrcmp &&
8436 BuiltinOp != Builtin::BIwcscmp &&
8437 BuiltinOp != Builtin::BI__builtin_strcmp &&
8438 BuiltinOp != Builtin::BI__builtin_wcscmp) {
8440 if (!EvaluateInteger(E->getArg(2), N, Info))
8442 MaxLength = N.getExtValue();
8445 // Empty substrings compare equal by definition.
8446 if (MaxLength == 0u)
8447 return Success(0, E);
8449 if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8450 !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8451 String1.Designator.Invalid || String2.Designator.Invalid)
8454 QualType CharTy1 = String1.Designator.getType(Info.Ctx);
8455 QualType CharTy2 = String2.Designator.getType(Info.Ctx);
8457 bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
8458 BuiltinOp == Builtin::BI__builtin_memcmp;
8461 (Info.Ctx.hasSameUnqualifiedType(
8462 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
8463 Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
8465 const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
8466 return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
8467 handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
8468 Char1.isInt() && Char2.isInt();
8470 const auto &AdvanceElems = [&] {
8471 return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
8472 HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
8476 uint64_t BytesRemaining = MaxLength;
8477 // Pointers to const void may point to objects of incomplete type.
8478 if (CharTy1->isIncompleteType()) {
8479 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
8482 if (CharTy2->isIncompleteType()) {
8483 Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
8486 uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
8487 CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
8488 // Give up on comparing between elements with disparate widths.
8489 if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
8491 uint64_t BytesPerElement = CharTy1Size.getQuantity();
8492 assert(BytesRemaining && "BytesRemaining should not be zero: the "
8493 "following loop considers at least one element");
8495 APValue Char1, Char2;
8496 if (!ReadCurElems(Char1, Char2))
8498 // We have compatible in-memory widths, but a possible type and
8499 // (for `bool`) internal representation mismatch.
8500 // Assuming two's complement representation, including 0 for `false` and
8501 // 1 for `true`, we can check an appropriate number of elements for
8502 // equality even if they are not byte-sized.
8503 APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
8504 APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
8505 if (Char1InMem.ne(Char2InMem)) {
8506 // If the elements are byte-sized, then we can produce a three-way
8507 // comparison result in a straightforward manner.
8508 if (BytesPerElement == 1u) {
8509 // memcmp always compares unsigned chars.
8510 return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
8512 // The result is byte-order sensitive, and we have multibyte elements.
8513 // FIXME: We can compare the remaining bytes in the correct order.
8516 if (!AdvanceElems())
8518 if (BytesRemaining <= BytesPerElement)
8520 BytesRemaining -= BytesPerElement;
8522 // Enough elements are equal to account for the memcmp limit.
8523 return Success(0, E);
8526 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8527 BuiltinOp != Builtin::BIwmemcmp &&
8528 BuiltinOp != Builtin::BI__builtin_memcmp &&
8529 BuiltinOp != Builtin::BI__builtin_wmemcmp);
8530 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8531 BuiltinOp == Builtin::BIwcsncmp ||
8532 BuiltinOp == Builtin::BIwmemcmp ||
8533 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8534 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8535 BuiltinOp == Builtin::BI__builtin_wmemcmp;
8537 for (; MaxLength; --MaxLength) {
8538 APValue Char1, Char2;
8539 if (!ReadCurElems(Char1, Char2))
8541 if (Char1.getInt() != Char2.getInt()) {
8542 if (IsWide) // wmemcmp compares with wchar_t signedness.
8543 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8544 // memcmp always compares unsigned chars.
8545 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8547 if (StopAtNull && !Char1.getInt())
8548 return Success(0, E);
8549 assert(!(StopAtNull && !Char2.getInt()));
8550 if (!AdvanceElems())
8553 // We hit the strncmp / memcmp limit.
8554 return Success(0, E);
8557 case Builtin::BI__atomic_always_lock_free:
8558 case Builtin::BI__atomic_is_lock_free:
8559 case Builtin::BI__c11_atomic_is_lock_free: {
8561 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8564 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8565 // of two less than the maximum inline atomic width, we know it is
8566 // lock-free. If the size isn't a power of two, or greater than the
8567 // maximum alignment where we promote atomics, we know it is not lock-free
8568 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8569 // the answer can only be determined at runtime; for example, 16-byte
8570 // atomics have lock-free implementations on some, but not all,
8571 // x86-64 processors.
8573 // Check power-of-two.
8574 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8575 if (Size.isPowerOfTwo()) {
8576 // Check against inlining width.
8577 unsigned InlineWidthBits =
8578 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8579 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8580 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8581 Size == CharUnits::One() ||
8582 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8583 Expr::NPC_NeverValueDependent))
8584 // OK, we will inline appropriately-aligned operations of this size,
8585 // and _Atomic(T) is appropriately-aligned.
8586 return Success(1, E);
8588 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8589 castAs<PointerType>()->getPointeeType();
8590 if (!PointeeType->isIncompleteType() &&
8591 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8592 // OK, we will inline operations on this object.
8593 return Success(1, E);
8598 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8599 Success(0, E) : Error(E);
8601 case Builtin::BIomp_is_initial_device:
8602 // We can decide statically which value the runtime would return if called.
8603 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8604 case Builtin::BI__builtin_add_overflow:
8605 case Builtin::BI__builtin_sub_overflow:
8606 case Builtin::BI__builtin_mul_overflow:
8607 case Builtin::BI__builtin_sadd_overflow:
8608 case Builtin::BI__builtin_uadd_overflow:
8609 case Builtin::BI__builtin_uaddl_overflow:
8610 case Builtin::BI__builtin_uaddll_overflow:
8611 case Builtin::BI__builtin_usub_overflow:
8612 case Builtin::BI__builtin_usubl_overflow:
8613 case Builtin::BI__builtin_usubll_overflow:
8614 case Builtin::BI__builtin_umul_overflow:
8615 case Builtin::BI__builtin_umull_overflow:
8616 case Builtin::BI__builtin_umulll_overflow:
8617 case Builtin::BI__builtin_saddl_overflow:
8618 case Builtin::BI__builtin_saddll_overflow:
8619 case Builtin::BI__builtin_ssub_overflow:
8620 case Builtin::BI__builtin_ssubl_overflow:
8621 case Builtin::BI__builtin_ssubll_overflow:
8622 case Builtin::BI__builtin_smul_overflow:
8623 case Builtin::BI__builtin_smull_overflow:
8624 case Builtin::BI__builtin_smulll_overflow: {
8625 LValue ResultLValue;
8628 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8629 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8630 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8631 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8635 bool DidOverflow = false;
8637 // If the types don't have to match, enlarge all 3 to the largest of them.
8638 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8639 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8640 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8641 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8642 ResultType->isSignedIntegerOrEnumerationType();
8643 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8644 ResultType->isSignedIntegerOrEnumerationType();
8645 uint64_t LHSSize = LHS.getBitWidth();
8646 uint64_t RHSSize = RHS.getBitWidth();
8647 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8648 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8650 // Add an additional bit if the signedness isn't uniformly agreed to. We
8651 // could do this ONLY if there is a signed and an unsigned that both have
8652 // MaxBits, but the code to check that is pretty nasty. The issue will be
8653 // caught in the shrink-to-result later anyway.
8654 if (IsSigned && !AllSigned)
8657 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8659 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8661 Result = APSInt(MaxBits, !IsSigned);
8664 // Find largest int.
8665 switch (BuiltinOp) {
8667 llvm_unreachable("Invalid value for BuiltinOp");
8668 case Builtin::BI__builtin_add_overflow:
8669 case Builtin::BI__builtin_sadd_overflow:
8670 case Builtin::BI__builtin_saddl_overflow:
8671 case Builtin::BI__builtin_saddll_overflow:
8672 case Builtin::BI__builtin_uadd_overflow:
8673 case Builtin::BI__builtin_uaddl_overflow:
8674 case Builtin::BI__builtin_uaddll_overflow:
8675 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8676 : LHS.uadd_ov(RHS, DidOverflow);
8678 case Builtin::BI__builtin_sub_overflow:
8679 case Builtin::BI__builtin_ssub_overflow:
8680 case Builtin::BI__builtin_ssubl_overflow:
8681 case Builtin::BI__builtin_ssubll_overflow:
8682 case Builtin::BI__builtin_usub_overflow:
8683 case Builtin::BI__builtin_usubl_overflow:
8684 case Builtin::BI__builtin_usubll_overflow:
8685 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8686 : LHS.usub_ov(RHS, DidOverflow);
8688 case Builtin::BI__builtin_mul_overflow:
8689 case Builtin::BI__builtin_smul_overflow:
8690 case Builtin::BI__builtin_smull_overflow:
8691 case Builtin::BI__builtin_smulll_overflow:
8692 case Builtin::BI__builtin_umul_overflow:
8693 case Builtin::BI__builtin_umull_overflow:
8694 case Builtin::BI__builtin_umulll_overflow:
8695 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8696 : LHS.umul_ov(RHS, DidOverflow);
8700 // In the case where multiple sizes are allowed, truncate and see if
8701 // the values are the same.
8702 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8703 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8704 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8705 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8706 // since it will give us the behavior of a TruncOrSelf in the case where
8707 // its parameter <= its size. We previously set Result to be at least the
8708 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8709 // will work exactly like TruncOrSelf.
8710 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8711 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8713 if (!APSInt::isSameValue(Temp, Result))
8718 APValue APV{Result};
8719 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8721 return Success(DidOverflow, E);
8726 /// Determine whether this is a pointer past the end of the complete
8727 /// object referred to by the lvalue.
8728 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8730 // A null pointer can be viewed as being "past the end" but we don't
8731 // choose to look at it that way here.
8732 if (!LV.getLValueBase())
8735 // If the designator is valid and refers to a subobject, we're not pointing
8737 if (!LV.getLValueDesignator().Invalid &&
8738 !LV.getLValueDesignator().isOnePastTheEnd())
8741 // A pointer to an incomplete type might be past-the-end if the type's size is
8742 // zero. We cannot tell because the type is incomplete.
8743 QualType Ty = getType(LV.getLValueBase());
8744 if (Ty->isIncompleteType())
8747 // We're a past-the-end pointer if we point to the byte after the object,
8748 // no matter what our type or path is.
8749 auto Size = Ctx.getTypeSizeInChars(Ty);
8750 return LV.getLValueOffset() == Size;
8755 /// Data recursive integer evaluator of certain binary operators.
8757 /// We use a data recursive algorithm for binary operators so that we are able
8758 /// to handle extreme cases of chained binary operators without causing stack
8760 class DataRecursiveIntBinOpEvaluator {
8765 EvalResult() : Failed(false) { }
8767 void swap(EvalResult &RHS) {
8769 Failed = RHS.Failed;
8776 EvalResult LHSResult; // meaningful only for binary operator expression.
8777 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8780 Job(Job &&) = default;
8782 void startSpeculativeEval(EvalInfo &Info) {
8783 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8787 SpeculativeEvaluationRAII SpecEvalRAII;
8790 SmallVector<Job, 16> Queue;
8792 IntExprEvaluator &IntEval;
8794 APValue &FinalResult;
8797 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8798 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8800 /// True if \param E is a binary operator that we are going to handle
8801 /// data recursively.
8802 /// We handle binary operators that are comma, logical, or that have operands
8803 /// with integral or enumeration type.
8804 static bool shouldEnqueue(const BinaryOperator *E) {
8805 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8806 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8807 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8808 E->getRHS()->getType()->isIntegralOrEnumerationType());
8811 bool Traverse(const BinaryOperator *E) {
8813 EvalResult PrevResult;
8814 while (!Queue.empty())
8815 process(PrevResult);
8817 if (PrevResult.Failed) return false;
8819 FinalResult.swap(PrevResult.Val);
8824 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8825 return IntEval.Success(Value, E, Result);
8827 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8828 return IntEval.Success(Value, E, Result);
8830 bool Error(const Expr *E) {
8831 return IntEval.Error(E);
8833 bool Error(const Expr *E, diag::kind D) {
8834 return IntEval.Error(E, D);
8837 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8838 return Info.CCEDiag(E, D);
8841 // Returns true if visiting the RHS is necessary, false otherwise.
8842 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8843 bool &SuppressRHSDiags);
8845 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8846 const BinaryOperator *E, APValue &Result);
8848 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8849 Result.Failed = !Evaluate(Result.Val, Info, E);
8851 Result.Val = APValue();
8854 void process(EvalResult &Result);
8856 void enqueue(const Expr *E) {
8857 E = E->IgnoreParens();
8858 Queue.resize(Queue.size()+1);
8860 Queue.back().Kind = Job::AnyExprKind;
8866 bool DataRecursiveIntBinOpEvaluator::
8867 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8868 bool &SuppressRHSDiags) {
8869 if (E->getOpcode() == BO_Comma) {
8870 // Ignore LHS but note if we could not evaluate it.
8871 if (LHSResult.Failed)
8872 return Info.noteSideEffect();
8876 if (E->isLogicalOp()) {
8878 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8879 // We were able to evaluate the LHS, see if we can get away with not
8880 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8881 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8882 Success(LHSAsBool, E, LHSResult.Val);
8883 return false; // Ignore RHS
8886 LHSResult.Failed = true;
8888 // Since we weren't able to evaluate the left hand side, it
8889 // might have had side effects.
8890 if (!Info.noteSideEffect())
8893 // We can't evaluate the LHS; however, sometimes the result
8894 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8895 // Don't ignore RHS and suppress diagnostics from this arm.
8896 SuppressRHSDiags = true;
8902 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8903 E->getRHS()->getType()->isIntegralOrEnumerationType());
8905 if (LHSResult.Failed && !Info.noteFailure())
8906 return false; // Ignore RHS;
8911 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8913 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8914 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8916 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8917 CharUnits &Offset = LVal.getLValueOffset();
8918 uint64_t Offset64 = Offset.getQuantity();
8919 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8920 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8921 : Offset64 + Index64);
8924 bool DataRecursiveIntBinOpEvaluator::
8925 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8926 const BinaryOperator *E, APValue &Result) {
8927 if (E->getOpcode() == BO_Comma) {
8928 if (RHSResult.Failed)
8930 Result = RHSResult.Val;
8934 if (E->isLogicalOp()) {
8935 bool lhsResult, rhsResult;
8936 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8937 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8941 if (E->getOpcode() == BO_LOr)
8942 return Success(lhsResult || rhsResult, E, Result);
8944 return Success(lhsResult && rhsResult, E, Result);
8948 // We can't evaluate the LHS; however, sometimes the result
8949 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8950 if (rhsResult == (E->getOpcode() == BO_LOr))
8951 return Success(rhsResult, E, Result);
8958 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8959 E->getRHS()->getType()->isIntegralOrEnumerationType());
8961 if (LHSResult.Failed || RHSResult.Failed)
8964 const APValue &LHSVal = LHSResult.Val;
8965 const APValue &RHSVal = RHSResult.Val;
8967 // Handle cases like (unsigned long)&a + 4.
8968 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8970 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8974 // Handle cases like 4 + (unsigned long)&a
8975 if (E->getOpcode() == BO_Add &&
8976 RHSVal.isLValue() && LHSVal.isInt()) {
8978 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8982 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8983 // Handle (intptr_t)&&A - (intptr_t)&&B.
8984 if (!LHSVal.getLValueOffset().isZero() ||
8985 !RHSVal.getLValueOffset().isZero())
8987 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8988 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8989 if (!LHSExpr || !RHSExpr)
8991 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8992 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8993 if (!LHSAddrExpr || !RHSAddrExpr)
8995 // Make sure both labels come from the same function.
8996 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8997 RHSAddrExpr->getLabel()->getDeclContext())
8999 Result = APValue(LHSAddrExpr, RHSAddrExpr);
9003 // All the remaining cases expect both operands to be an integer
9004 if (!LHSVal.isInt() || !RHSVal.isInt())
9007 // Set up the width and signedness manually, in case it can't be deduced
9008 // from the operation we're performing.
9009 // FIXME: Don't do this in the cases where we can deduce it.
9010 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
9011 E->getType()->isUnsignedIntegerOrEnumerationType());
9012 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
9013 RHSVal.getInt(), Value))
9015 return Success(Value, E, Result);
9018 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
9019 Job &job = Queue.back();
9022 case Job::AnyExprKind: {
9023 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
9024 if (shouldEnqueue(Bop)) {
9025 job.Kind = Job::BinOpKind;
9026 enqueue(Bop->getLHS());
9031 EvaluateExpr(job.E, Result);
9036 case Job::BinOpKind: {
9037 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9038 bool SuppressRHSDiags = false;
9039 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
9043 if (SuppressRHSDiags)
9044 job.startSpeculativeEval(Info);
9045 job.LHSResult.swap(Result);
9046 job.Kind = Job::BinOpVisitedLHSKind;
9047 enqueue(Bop->getRHS());
9051 case Job::BinOpVisitedLHSKind: {
9052 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
9055 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
9061 llvm_unreachable("Invalid Job::Kind!");
9065 /// Used when we determine that we should fail, but can keep evaluating prior to
9066 /// noting that we had a failure.
9067 class DelayedNoteFailureRAII {
9072 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
9073 : Info(Info), NoteFailure(NoteFailure) {}
9074 ~DelayedNoteFailureRAII() {
9076 bool ContinueAfterFailure = Info.noteFailure();
9077 (void)ContinueAfterFailure;
9078 assert(ContinueAfterFailure &&
9079 "Shouldn't have kept evaluating on failure.");
9085 template <class SuccessCB, class AfterCB>
9087 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
9088 SuccessCB &&Success, AfterCB &&DoAfter) {
9089 assert(E->isComparisonOp() && "expected comparison operator");
9090 assert((E->getOpcode() == BO_Cmp ||
9091 E->getType()->isIntegralOrEnumerationType()) &&
9092 "unsupported binary expression evaluation");
9093 auto Error = [&](const Expr *E) {
9094 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9098 using CCR = ComparisonCategoryResult;
9099 bool IsRelational = E->isRelationalOp();
9100 bool IsEquality = E->isEqualityOp();
9101 if (E->getOpcode() == BO_Cmp) {
9102 const ComparisonCategoryInfo &CmpInfo =
9103 Info.Ctx.CompCategories.getInfoForType(E->getType());
9104 IsRelational = CmpInfo.isOrdered();
9105 IsEquality = CmpInfo.isEquality();
9108 QualType LHSTy = E->getLHS()->getType();
9109 QualType RHSTy = E->getRHS()->getType();
9111 if (LHSTy->isIntegralOrEnumerationType() &&
9112 RHSTy->isIntegralOrEnumerationType()) {
9114 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
9115 if (!LHSOK && !Info.noteFailure())
9117 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
9120 return Success(CCR::Less, E);
9122 return Success(CCR::Greater, E);
9123 return Success(CCR::Equal, E);
9126 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
9127 ComplexValue LHS, RHS;
9129 if (E->isAssignmentOp()) {
9131 EvaluateLValue(E->getLHS(), LV, Info);
9133 } else if (LHSTy->isRealFloatingType()) {
9134 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
9136 LHS.makeComplexFloat();
9137 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
9140 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
9142 if (!LHSOK && !Info.noteFailure())
9145 if (E->getRHS()->getType()->isRealFloatingType()) {
9146 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
9148 RHS.makeComplexFloat();
9149 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
9150 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9153 if (LHS.isComplexFloat()) {
9154 APFloat::cmpResult CR_r =
9155 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9156 APFloat::cmpResult CR_i =
9157 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
9158 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9159 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9161 assert(IsEquality && "invalid complex comparison");
9162 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9163 LHS.getComplexIntImag() == RHS.getComplexIntImag();
9164 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9168 if (LHSTy->isRealFloatingType() &&
9169 RHSTy->isRealFloatingType()) {
9170 APFloat RHS(0.0), LHS(0.0);
9172 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
9173 if (!LHSOK && !Info.noteFailure())
9176 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
9179 assert(E->isComparisonOp() && "Invalid binary operator!");
9180 auto GetCmpRes = [&]() {
9181 switch (LHS.compare(RHS)) {
9182 case APFloat::cmpEqual:
9184 case APFloat::cmpLessThan:
9186 case APFloat::cmpGreaterThan:
9187 return CCR::Greater;
9188 case APFloat::cmpUnordered:
9189 return CCR::Unordered;
9191 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9193 return Success(GetCmpRes(), E);
9196 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9197 LValue LHSValue, RHSValue;
9199 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9200 if (!LHSOK && !Info.noteFailure())
9203 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9206 // Reject differing bases from the normal codepath; we special-case
9207 // comparisons to null.
9208 if (!HasSameBase(LHSValue, RHSValue)) {
9209 // Inequalities and subtractions between unrelated pointers have
9210 // unspecified or undefined behavior.
9213 // A constant address may compare equal to the address of a symbol.
9214 // The one exception is that address of an object cannot compare equal
9215 // to a null pointer constant.
9216 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9217 (!RHSValue.Base && !RHSValue.Offset.isZero()))
9219 // It's implementation-defined whether distinct literals will have
9220 // distinct addresses. In clang, the result of such a comparison is
9221 // unspecified, so it is not a constant expression. However, we do know
9222 // that the address of a literal will be non-null.
9223 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9224 LHSValue.Base && RHSValue.Base)
9226 // We can't tell whether weak symbols will end up pointing to the same
9228 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9230 // We can't compare the address of the start of one object with the
9231 // past-the-end address of another object, per C++ DR1652.
9232 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9233 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9234 (RHSValue.Base && RHSValue.Offset.isZero() &&
9235 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9237 // We can't tell whether an object is at the same address as another
9238 // zero sized object.
9239 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9240 (LHSValue.Base && isZeroSized(RHSValue)))
9242 return Success(CCR::Nonequal, E);
9245 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9246 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9248 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9249 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9251 // C++11 [expr.rel]p3:
9252 // Pointers to void (after pointer conversions) can be compared, with a
9253 // result defined as follows: If both pointers represent the same
9254 // address or are both the null pointer value, the result is true if the
9255 // operator is <= or >= and false otherwise; otherwise the result is
9257 // We interpret this as applying to pointers to *cv* void.
9258 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9259 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9261 // C++11 [expr.rel]p2:
9262 // - If two pointers point to non-static data members of the same object,
9263 // or to subobjects or array elements fo such members, recursively, the
9264 // pointer to the later declared member compares greater provided the
9265 // two members have the same access control and provided their class is
9268 // - Otherwise pointer comparisons are unspecified.
9269 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9271 unsigned Mismatch = FindDesignatorMismatch(
9272 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9273 // At the point where the designators diverge, the comparison has a
9274 // specified value if:
9275 // - we are comparing array indices
9276 // - we are comparing fields of a union, or fields with the same access
9277 // Otherwise, the result is unspecified and thus the comparison is not a
9278 // constant expression.
9279 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9280 Mismatch < RHSDesignator.Entries.size()) {
9281 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9282 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9284 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9286 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9287 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9288 << RF->getParent() << RF;
9290 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9291 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9292 << LF->getParent() << LF;
9293 else if (!LF->getParent()->isUnion() &&
9294 LF->getAccess() != RF->getAccess())
9296 diag::note_constexpr_pointer_comparison_differing_access)
9297 << LF << LF->getAccess() << RF << RF->getAccess()
9302 // The comparison here must be unsigned, and performed with the same
9303 // width as the pointer.
9304 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9305 uint64_t CompareLHS = LHSOffset.getQuantity();
9306 uint64_t CompareRHS = RHSOffset.getQuantity();
9307 assert(PtrSize <= 64 && "Unexpected pointer width");
9308 uint64_t Mask = ~0ULL >> (64 - PtrSize);
9312 // If there is a base and this is a relational operator, we can only
9313 // compare pointers within the object in question; otherwise, the result
9314 // depends on where the object is located in memory.
9315 if (!LHSValue.Base.isNull() && IsRelational) {
9316 QualType BaseTy = getType(LHSValue.Base);
9317 if (BaseTy->isIncompleteType())
9319 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9320 uint64_t OffsetLimit = Size.getQuantity();
9321 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9325 if (CompareLHS < CompareRHS)
9326 return Success(CCR::Less, E);
9327 if (CompareLHS > CompareRHS)
9328 return Success(CCR::Greater, E);
9329 return Success(CCR::Equal, E);
9332 if (LHSTy->isMemberPointerType()) {
9333 assert(IsEquality && "unexpected member pointer operation");
9334 assert(RHSTy->isMemberPointerType() && "invalid comparison");
9336 MemberPtr LHSValue, RHSValue;
9338 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9339 if (!LHSOK && !Info.noteFailure())
9342 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9345 // C++11 [expr.eq]p2:
9346 // If both operands are null, they compare equal. Otherwise if only one is
9347 // null, they compare unequal.
9348 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9349 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9350 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9353 // Otherwise if either is a pointer to a virtual member function, the
9354 // result is unspecified.
9355 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9356 if (MD->isVirtual())
9357 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9358 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9359 if (MD->isVirtual())
9360 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9362 // Otherwise they compare equal if and only if they would refer to the
9363 // same member of the same most derived object or the same subobject if
9364 // they were dereferenced with a hypothetical object of the associated
9366 bool Equal = LHSValue == RHSValue;
9367 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9370 if (LHSTy->isNullPtrType()) {
9371 assert(E->isComparisonOp() && "unexpected nullptr operation");
9372 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9373 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9374 // are compared, the result is true of the operator is <=, >= or ==, and
9376 return Success(CCR::Equal, E);
9382 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9383 if (!CheckLiteralType(Info, E))
9386 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9387 const BinaryOperator *E) {
9388 // Evaluation succeeded. Lookup the information for the comparison category
9389 // type and fetch the VarDecl for the result.
9390 const ComparisonCategoryInfo &CmpInfo =
9391 Info.Ctx.CompCategories.getInfoForType(E->getType());
9393 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9394 // Check and evaluate the result as a constant expression.
9397 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9399 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9401 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9402 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9406 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9407 // We don't call noteFailure immediately because the assignment happens after
9408 // we evaluate LHS and RHS.
9409 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9412 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9413 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9414 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9416 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9417 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9418 "DataRecursiveIntBinOpEvaluator should have handled integral types");
9420 if (E->isComparisonOp()) {
9421 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9422 // comparisons and then translating the result.
9423 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9424 const BinaryOperator *E) {
9425 using CCR = ComparisonCategoryResult;
9426 bool IsEqual = ResKind == CCR::Equal,
9427 IsLess = ResKind == CCR::Less,
9428 IsGreater = ResKind == CCR::Greater;
9429 auto Op = E->getOpcode();
9432 llvm_unreachable("unsupported binary operator");
9435 return Success(IsEqual == (Op == BO_EQ), E);
9436 case BO_LT: return Success(IsLess, E);
9437 case BO_GT: return Success(IsGreater, E);
9438 case BO_LE: return Success(IsEqual || IsLess, E);
9439 case BO_GE: return Success(IsEqual || IsGreater, E);
9442 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9443 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9447 QualType LHSTy = E->getLHS()->getType();
9448 QualType RHSTy = E->getRHS()->getType();
9450 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9451 E->getOpcode() == BO_Sub) {
9452 LValue LHSValue, RHSValue;
9454 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9455 if (!LHSOK && !Info.noteFailure())
9458 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9461 // Reject differing bases from the normal codepath; we special-case
9462 // comparisons to null.
9463 if (!HasSameBase(LHSValue, RHSValue)) {
9464 // Handle &&A - &&B.
9465 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9467 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9468 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9469 if (!LHSExpr || !RHSExpr)
9471 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9472 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9473 if (!LHSAddrExpr || !RHSAddrExpr)
9475 // Make sure both labels come from the same function.
9476 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9477 RHSAddrExpr->getLabel()->getDeclContext())
9479 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9481 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9482 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9484 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9485 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9487 // C++11 [expr.add]p6:
9488 // Unless both pointers point to elements of the same array object, or
9489 // one past the last element of the array object, the behavior is
9491 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9492 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9494 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9496 QualType Type = E->getLHS()->getType();
9497 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9499 CharUnits ElementSize;
9500 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9503 // As an extension, a type may have zero size (empty struct or union in
9504 // C, array of zero length). Pointer subtraction in such cases has
9505 // undefined behavior, so is not constant.
9506 if (ElementSize.isZero()) {
9507 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9512 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9513 // and produce incorrect results when it overflows. Such behavior
9514 // appears to be non-conforming, but is common, so perhaps we should
9515 // assume the standard intended for such cases to be undefined behavior
9516 // and check for them.
9518 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9519 // overflow in the final conversion to ptrdiff_t.
9520 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9521 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9522 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9524 APSInt TrueResult = (LHS - RHS) / ElemSize;
9525 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9527 if (Result.extend(65) != TrueResult &&
9528 !HandleOverflow(Info, E, TrueResult, E->getType()))
9530 return Success(Result, E);
9533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9536 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9537 /// a result as the expression's type.
9538 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9539 const UnaryExprOrTypeTraitExpr *E) {
9540 switch(E->getKind()) {
9541 case UETT_PreferredAlignOf:
9542 case UETT_AlignOf: {
9543 if (E->isArgumentType())
9544 return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9547 return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9551 case UETT_VecStep: {
9552 QualType Ty = E->getTypeOfArgument();
9554 if (Ty->isVectorType()) {
9555 unsigned n = Ty->castAs<VectorType>()->getNumElements();
9557 // The vec_step built-in functions that take a 3-component
9558 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9562 return Success(n, E);
9564 return Success(1, E);
9568 QualType SrcTy = E->getTypeOfArgument();
9569 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9570 // the result is the size of the referenced type."
9571 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9572 SrcTy = Ref->getPointeeType();
9575 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9577 return Success(Sizeof, E);
9579 case UETT_OpenMPRequiredSimdAlign:
9580 assert(E->isArgumentType());
9582 Info.Ctx.toCharUnitsFromBits(
9583 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9588 llvm_unreachable("unknown expr/type trait");
9591 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9593 unsigned n = OOE->getNumComponents();
9596 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9597 for (unsigned i = 0; i != n; ++i) {
9598 OffsetOfNode ON = OOE->getComponent(i);
9599 switch (ON.getKind()) {
9600 case OffsetOfNode::Array: {
9601 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9603 if (!EvaluateInteger(Idx, IdxResult, Info))
9605 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9608 CurrentType = AT->getElementType();
9609 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9610 Result += IdxResult.getSExtValue() * ElementSize;
9614 case OffsetOfNode::Field: {
9615 FieldDecl *MemberDecl = ON.getField();
9616 const RecordType *RT = CurrentType->getAs<RecordType>();
9619 RecordDecl *RD = RT->getDecl();
9620 if (RD->isInvalidDecl()) return false;
9621 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9622 unsigned i = MemberDecl->getFieldIndex();
9623 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9624 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9625 CurrentType = MemberDecl->getType().getNonReferenceType();
9629 case OffsetOfNode::Identifier:
9630 llvm_unreachable("dependent __builtin_offsetof");
9632 case OffsetOfNode::Base: {
9633 CXXBaseSpecifier *BaseSpec = ON.getBase();
9634 if (BaseSpec->isVirtual())
9637 // Find the layout of the class whose base we are looking into.
9638 const RecordType *RT = CurrentType->getAs<RecordType>();
9641 RecordDecl *RD = RT->getDecl();
9642 if (RD->isInvalidDecl()) return false;
9643 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9645 // Find the base class itself.
9646 CurrentType = BaseSpec->getType();
9647 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9651 // Add the offset to the base.
9652 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9657 return Success(Result, OOE);
9660 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9661 switch (E->getOpcode()) {
9663 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9667 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9668 // If so, we could clear the diagnostic ID.
9669 return Visit(E->getSubExpr());
9671 // The result is just the value.
9672 return Visit(E->getSubExpr());
9674 if (!Visit(E->getSubExpr()))
9676 if (!Result.isInt()) return Error(E);
9677 const APSInt &Value = Result.getInt();
9678 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9679 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9682 return Success(-Value, E);
9685 if (!Visit(E->getSubExpr()))
9687 if (!Result.isInt()) return Error(E);
9688 return Success(~Result.getInt(), E);
9692 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9694 return Success(!bres, E);
9699 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9700 /// result type is integer.
9701 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9702 const Expr *SubExpr = E->getSubExpr();
9703 QualType DestType = E->getType();
9704 QualType SrcType = SubExpr->getType();
9706 switch (E->getCastKind()) {
9707 case CK_BaseToDerived:
9708 case CK_DerivedToBase:
9709 case CK_UncheckedDerivedToBase:
9712 case CK_ArrayToPointerDecay:
9713 case CK_FunctionToPointerDecay:
9714 case CK_NullToPointer:
9715 case CK_NullToMemberPointer:
9716 case CK_BaseToDerivedMemberPointer:
9717 case CK_DerivedToBaseMemberPointer:
9718 case CK_ReinterpretMemberPointer:
9719 case CK_ConstructorConversion:
9720 case CK_IntegralToPointer:
9722 case CK_VectorSplat:
9723 case CK_IntegralToFloating:
9724 case CK_FloatingCast:
9725 case CK_CPointerToObjCPointerCast:
9726 case CK_BlockPointerToObjCPointerCast:
9727 case CK_AnyPointerToBlockPointerCast:
9728 case CK_ObjCObjectLValueCast:
9729 case CK_FloatingRealToComplex:
9730 case CK_FloatingComplexToReal:
9731 case CK_FloatingComplexCast:
9732 case CK_FloatingComplexToIntegralComplex:
9733 case CK_IntegralRealToComplex:
9734 case CK_IntegralComplexCast:
9735 case CK_IntegralComplexToFloatingComplex:
9736 case CK_BuiltinFnToFnPtr:
9737 case CK_ZeroToOCLOpaqueType:
9738 case CK_NonAtomicToAtomic:
9739 case CK_AddressSpaceConversion:
9740 case CK_IntToOCLSampler:
9741 case CK_FixedPointCast:
9742 llvm_unreachable("invalid cast kind for integral value");
9746 case CK_LValueBitCast:
9747 case CK_ARCProduceObject:
9748 case CK_ARCConsumeObject:
9749 case CK_ARCReclaimReturnedObject:
9750 case CK_ARCExtendBlockObject:
9751 case CK_CopyAndAutoreleaseBlockObject:
9754 case CK_UserDefinedConversion:
9755 case CK_LValueToRValue:
9756 case CK_AtomicToNonAtomic:
9758 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9760 case CK_MemberPointerToBoolean:
9761 case CK_PointerToBoolean:
9762 case CK_IntegralToBoolean:
9763 case CK_FloatingToBoolean:
9764 case CK_BooleanToSignedIntegral:
9765 case CK_FloatingComplexToBoolean:
9766 case CK_IntegralComplexToBoolean: {
9768 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9770 uint64_t IntResult = BoolResult;
9771 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9772 IntResult = (uint64_t)-1;
9773 return Success(IntResult, E);
9776 case CK_FixedPointToBoolean: {
9777 // Unsigned padding does not affect this.
9779 if (!Evaluate(Val, Info, SubExpr))
9781 return Success(Val.getInt().getBoolValue(), E);
9784 case CK_IntegralCast: {
9785 if (!Visit(SubExpr))
9788 if (!Result.isInt()) {
9789 // Allow casts of address-of-label differences if they are no-ops
9790 // or narrowing. (The narrowing case isn't actually guaranteed to
9791 // be constant-evaluatable except in some narrow cases which are hard
9792 // to detect here. We let it through on the assumption the user knows
9793 // what they are doing.)
9794 if (Result.isAddrLabelDiff())
9795 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9796 // Only allow casts of lvalues if they are lossless.
9797 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9800 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9801 Result.getInt()), E);
9804 case CK_PointerToIntegral: {
9805 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9808 if (!EvaluatePointer(SubExpr, LV, Info))
9811 if (LV.getLValueBase()) {
9812 // Only allow based lvalue casts if they are lossless.
9813 // FIXME: Allow a larger integer size than the pointer size, and allow
9814 // narrowing back down to pointer width in subsequent integral casts.
9815 // FIXME: Check integer type's active bits, not its type size.
9816 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9819 LV.Designator.setInvalid();
9820 LV.moveInto(Result);
9827 if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
9828 llvm_unreachable("Can't cast this!");
9830 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9833 case CK_IntegralComplexToReal: {
9835 if (!EvaluateComplex(SubExpr, C, Info))
9837 return Success(C.getComplexIntReal(), E);
9840 case CK_FloatingToIntegral: {
9842 if (!EvaluateFloat(SubExpr, F, Info))
9846 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9848 return Success(Value, E);
9852 llvm_unreachable("unknown cast resulting in integral value");
9855 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9856 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9858 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9860 if (!LV.isComplexInt())
9862 return Success(LV.getComplexIntReal(), E);
9865 return Visit(E->getSubExpr());
9868 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9869 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9871 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9873 if (!LV.isComplexInt())
9875 return Success(LV.getComplexIntImag(), E);
9878 VisitIgnoredValue(E->getSubExpr());
9879 return Success(0, E);
9882 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9883 return Success(E->getPackLength(), E);
9886 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9887 return Success(E->getValue(), E);
9890 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9891 switch (E->getOpcode()) {
9893 // Invalid unary operators
9896 // The result is just the value.
9897 return Visit(E->getSubExpr());
9899 if (!Visit(E->getSubExpr())) return false;
9900 if (!Result.isInt()) return Error(E);
9901 const APSInt &Value = Result.getInt();
9902 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9904 FixedPointValueToString(S, Value,
9905 Info.Ctx.getTypeInfo(E->getType()).Width);
9906 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9907 if (Info.noteUndefinedBehavior()) return false;
9909 return Success(-Value, E);
9913 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9915 return Success(!bres, E);
9920 //===----------------------------------------------------------------------===//
9922 //===----------------------------------------------------------------------===//
9925 class FloatExprEvaluator
9926 : public ExprEvaluatorBase<FloatExprEvaluator> {
9929 FloatExprEvaluator(EvalInfo &info, APFloat &result)
9930 : ExprEvaluatorBaseTy(info), Result(result) {}
9932 bool Success(const APValue &V, const Expr *e) {
9933 Result = V.getFloat();
9937 bool ZeroInitialization(const Expr *E) {
9938 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9942 bool VisitCallExpr(const CallExpr *E);
9944 bool VisitUnaryOperator(const UnaryOperator *E);
9945 bool VisitBinaryOperator(const BinaryOperator *E);
9946 bool VisitFloatingLiteral(const FloatingLiteral *E);
9947 bool VisitCastExpr(const CastExpr *E);
9949 bool VisitUnaryReal(const UnaryOperator *E);
9950 bool VisitUnaryImag(const UnaryOperator *E);
9952 // FIXME: Missing: array subscript of vector, member of vector
9954 } // end anonymous namespace
9956 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9957 assert(E->isRValue() && E->getType()->isRealFloatingType());
9958 return FloatExprEvaluator(Info, Result).Visit(E);
9961 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9965 llvm::APFloat &Result) {
9966 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9967 if (!S) return false;
9969 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9973 // Treat empty strings as if they were zero.
9974 if (S->getString().empty())
9975 fill = llvm::APInt(32, 0);
9976 else if (S->getString().getAsInteger(0, fill))
9979 if (Context.getTargetInfo().isNan2008()) {
9981 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9983 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9985 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9986 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9987 // a different encoding to what became a standard in 2008, and for pre-
9988 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9989 // sNaN. This is now known as "legacy NaN" encoding.
9991 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9993 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9999 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
10000 switch (E->getBuiltinCallee()) {
10002 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10004 case Builtin::BI__builtin_huge_val:
10005 case Builtin::BI__builtin_huge_valf:
10006 case Builtin::BI__builtin_huge_vall:
10007 case Builtin::BI__builtin_huge_valf128:
10008 case Builtin::BI__builtin_inf:
10009 case Builtin::BI__builtin_inff:
10010 case Builtin::BI__builtin_infl:
10011 case Builtin::BI__builtin_inff128: {
10012 const llvm::fltSemantics &Sem =
10013 Info.Ctx.getFloatTypeSemantics(E->getType());
10014 Result = llvm::APFloat::getInf(Sem);
10018 case Builtin::BI__builtin_nans:
10019 case Builtin::BI__builtin_nansf:
10020 case Builtin::BI__builtin_nansl:
10021 case Builtin::BI__builtin_nansf128:
10022 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10027 case Builtin::BI__builtin_nan:
10028 case Builtin::BI__builtin_nanf:
10029 case Builtin::BI__builtin_nanl:
10030 case Builtin::BI__builtin_nanf128:
10031 // If this is __builtin_nan() turn this into a nan, otherwise we
10032 // can't constant fold it.
10033 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
10038 case Builtin::BI__builtin_fabs:
10039 case Builtin::BI__builtin_fabsf:
10040 case Builtin::BI__builtin_fabsl:
10041 case Builtin::BI__builtin_fabsf128:
10042 if (!EvaluateFloat(E->getArg(0), Result, Info))
10045 if (Result.isNegative())
10046 Result.changeSign();
10049 // FIXME: Builtin::BI__builtin_powi
10050 // FIXME: Builtin::BI__builtin_powif
10051 // FIXME: Builtin::BI__builtin_powil
10053 case Builtin::BI__builtin_copysign:
10054 case Builtin::BI__builtin_copysignf:
10055 case Builtin::BI__builtin_copysignl:
10056 case Builtin::BI__builtin_copysignf128: {
10058 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
10059 !EvaluateFloat(E->getArg(1), RHS, Info))
10061 Result.copySign(RHS);
10067 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
10068 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10070 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10072 Result = CV.FloatReal;
10076 return Visit(E->getSubExpr());
10079 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10080 if (E->getSubExpr()->getType()->isAnyComplexType()) {
10082 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
10084 Result = CV.FloatImag;
10088 VisitIgnoredValue(E->getSubExpr());
10089 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
10090 Result = llvm::APFloat::getZero(Sem);
10094 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10095 switch (E->getOpcode()) {
10096 default: return Error(E);
10098 return EvaluateFloat(E->getSubExpr(), Result, Info);
10100 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
10102 Result.changeSign();
10107 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10108 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10109 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10112 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
10113 if (!LHSOK && !Info.noteFailure())
10115 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
10116 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
10119 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
10120 Result = E->getValue();
10124 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
10125 const Expr* SubExpr = E->getSubExpr();
10127 switch (E->getCastKind()) {
10129 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10131 case CK_IntegralToFloating: {
10133 return EvaluateInteger(SubExpr, IntResult, Info) &&
10134 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
10135 E->getType(), Result);
10138 case CK_FloatingCast: {
10139 if (!Visit(SubExpr))
10141 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
10145 case CK_FloatingComplexToReal: {
10147 if (!EvaluateComplex(SubExpr, V, Info))
10149 Result = V.getComplexFloatReal();
10155 //===----------------------------------------------------------------------===//
10156 // Complex Evaluation (for float and integer)
10157 //===----------------------------------------------------------------------===//
10160 class ComplexExprEvaluator
10161 : public ExprEvaluatorBase<ComplexExprEvaluator> {
10162 ComplexValue &Result;
10165 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
10166 : ExprEvaluatorBaseTy(info), Result(Result) {}
10168 bool Success(const APValue &V, const Expr *e) {
10173 bool ZeroInitialization(const Expr *E);
10175 //===--------------------------------------------------------------------===//
10177 //===--------------------------------------------------------------------===//
10179 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
10180 bool VisitCastExpr(const CastExpr *E);
10181 bool VisitBinaryOperator(const BinaryOperator *E);
10182 bool VisitUnaryOperator(const UnaryOperator *E);
10183 bool VisitInitListExpr(const InitListExpr *E);
10185 } // end anonymous namespace
10187 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10189 assert(E->isRValue() && E->getType()->isAnyComplexType());
10190 return ComplexExprEvaluator(Info, Result).Visit(E);
10193 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10194 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10195 if (ElemTy->isRealFloatingType()) {
10196 Result.makeComplexFloat();
10197 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10198 Result.FloatReal = Zero;
10199 Result.FloatImag = Zero;
10201 Result.makeComplexInt();
10202 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10203 Result.IntReal = Zero;
10204 Result.IntImag = Zero;
10209 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10210 const Expr* SubExpr = E->getSubExpr();
10212 if (SubExpr->getType()->isRealFloatingType()) {
10213 Result.makeComplexFloat();
10214 APFloat &Imag = Result.FloatImag;
10215 if (!EvaluateFloat(SubExpr, Imag, Info))
10218 Result.FloatReal = APFloat(Imag.getSemantics());
10221 assert(SubExpr->getType()->isIntegerType() &&
10222 "Unexpected imaginary literal.");
10224 Result.makeComplexInt();
10225 APSInt &Imag = Result.IntImag;
10226 if (!EvaluateInteger(SubExpr, Imag, Info))
10229 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10234 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10236 switch (E->getCastKind()) {
10238 case CK_BaseToDerived:
10239 case CK_DerivedToBase:
10240 case CK_UncheckedDerivedToBase:
10243 case CK_ArrayToPointerDecay:
10244 case CK_FunctionToPointerDecay:
10245 case CK_NullToPointer:
10246 case CK_NullToMemberPointer:
10247 case CK_BaseToDerivedMemberPointer:
10248 case CK_DerivedToBaseMemberPointer:
10249 case CK_MemberPointerToBoolean:
10250 case CK_ReinterpretMemberPointer:
10251 case CK_ConstructorConversion:
10252 case CK_IntegralToPointer:
10253 case CK_PointerToIntegral:
10254 case CK_PointerToBoolean:
10256 case CK_VectorSplat:
10257 case CK_IntegralCast:
10258 case CK_BooleanToSignedIntegral:
10259 case CK_IntegralToBoolean:
10260 case CK_IntegralToFloating:
10261 case CK_FloatingToIntegral:
10262 case CK_FloatingToBoolean:
10263 case CK_FloatingCast:
10264 case CK_CPointerToObjCPointerCast:
10265 case CK_BlockPointerToObjCPointerCast:
10266 case CK_AnyPointerToBlockPointerCast:
10267 case CK_ObjCObjectLValueCast:
10268 case CK_FloatingComplexToReal:
10269 case CK_FloatingComplexToBoolean:
10270 case CK_IntegralComplexToReal:
10271 case CK_IntegralComplexToBoolean:
10272 case CK_ARCProduceObject:
10273 case CK_ARCConsumeObject:
10274 case CK_ARCReclaimReturnedObject:
10275 case CK_ARCExtendBlockObject:
10276 case CK_CopyAndAutoreleaseBlockObject:
10277 case CK_BuiltinFnToFnPtr:
10278 case CK_ZeroToOCLOpaqueType:
10279 case CK_NonAtomicToAtomic:
10280 case CK_AddressSpaceConversion:
10281 case CK_IntToOCLSampler:
10282 case CK_FixedPointCast:
10283 case CK_FixedPointToBoolean:
10284 llvm_unreachable("invalid cast kind for complex value");
10286 case CK_LValueToRValue:
10287 case CK_AtomicToNonAtomic:
10289 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10292 case CK_LValueBitCast:
10293 case CK_UserDefinedConversion:
10296 case CK_FloatingRealToComplex: {
10297 APFloat &Real = Result.FloatReal;
10298 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
10301 Result.makeComplexFloat();
10302 Result.FloatImag = APFloat(Real.getSemantics());
10306 case CK_FloatingComplexCast: {
10307 if (!Visit(E->getSubExpr()))
10310 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10312 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10314 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10315 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
10318 case CK_FloatingComplexToIntegralComplex: {
10319 if (!Visit(E->getSubExpr()))
10322 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10324 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10325 Result.makeComplexInt();
10326 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10327 To, Result.IntReal) &&
10328 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10329 To, Result.IntImag);
10332 case CK_IntegralRealToComplex: {
10333 APSInt &Real = Result.IntReal;
10334 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10337 Result.makeComplexInt();
10338 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10342 case CK_IntegralComplexCast: {
10343 if (!Visit(E->getSubExpr()))
10346 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10348 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10350 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10351 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10355 case CK_IntegralComplexToFloatingComplex: {
10356 if (!Visit(E->getSubExpr()))
10359 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10361 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10362 Result.makeComplexFloat();
10363 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10364 To, Result.FloatReal) &&
10365 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10366 To, Result.FloatImag);
10370 llvm_unreachable("unknown cast resulting in complex value");
10373 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10374 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10375 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10377 // Track whether the LHS or RHS is real at the type system level. When this is
10378 // the case we can simplify our evaluation strategy.
10379 bool LHSReal = false, RHSReal = false;
10382 if (E->getLHS()->getType()->isRealFloatingType()) {
10384 APFloat &Real = Result.FloatReal;
10385 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10387 Result.makeComplexFloat();
10388 Result.FloatImag = APFloat(Real.getSemantics());
10391 LHSOK = Visit(E->getLHS());
10393 if (!LHSOK && !Info.noteFailure())
10397 if (E->getRHS()->getType()->isRealFloatingType()) {
10399 APFloat &Real = RHS.FloatReal;
10400 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10402 RHS.makeComplexFloat();
10403 RHS.FloatImag = APFloat(Real.getSemantics());
10404 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10407 assert(!(LHSReal && RHSReal) &&
10408 "Cannot have both operands of a complex operation be real.");
10409 switch (E->getOpcode()) {
10410 default: return Error(E);
10412 if (Result.isComplexFloat()) {
10413 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10414 APFloat::rmNearestTiesToEven);
10416 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10418 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10419 APFloat::rmNearestTiesToEven);
10421 Result.getComplexIntReal() += RHS.getComplexIntReal();
10422 Result.getComplexIntImag() += RHS.getComplexIntImag();
10426 if (Result.isComplexFloat()) {
10427 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10428 APFloat::rmNearestTiesToEven);
10430 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10431 Result.getComplexFloatImag().changeSign();
10432 } else if (!RHSReal) {
10433 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10434 APFloat::rmNearestTiesToEven);
10437 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10438 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10442 if (Result.isComplexFloat()) {
10443 // This is an implementation of complex multiplication according to the
10444 // constraints laid out in C11 Annex G. The implementation uses the
10445 // following naming scheme:
10446 // (a + ib) * (c + id)
10447 ComplexValue LHS = Result;
10448 APFloat &A = LHS.getComplexFloatReal();
10449 APFloat &B = LHS.getComplexFloatImag();
10450 APFloat &C = RHS.getComplexFloatReal();
10451 APFloat &D = RHS.getComplexFloatImag();
10452 APFloat &ResR = Result.getComplexFloatReal();
10453 APFloat &ResI = Result.getComplexFloatImag();
10455 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10458 } else if (RHSReal) {
10462 // In the fully general case, we need to handle NaNs and infinities
10464 APFloat AC = A * C;
10465 APFloat BD = B * D;
10466 APFloat AD = A * D;
10467 APFloat BC = B * C;
10470 if (ResR.isNaN() && ResI.isNaN()) {
10471 bool Recalc = false;
10472 if (A.isInfinity() || B.isInfinity()) {
10473 A = APFloat::copySign(
10474 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10475 B = APFloat::copySign(
10476 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10478 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10480 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10483 if (C.isInfinity() || D.isInfinity()) {
10484 C = APFloat::copySign(
10485 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10486 D = APFloat::copySign(
10487 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10489 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10491 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10494 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10495 AD.isInfinity() || BC.isInfinity())) {
10497 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10499 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10501 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10503 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10507 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10508 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10513 ComplexValue LHS = Result;
10514 Result.getComplexIntReal() =
10515 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10516 LHS.getComplexIntImag() * RHS.getComplexIntImag());
10517 Result.getComplexIntImag() =
10518 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10519 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10523 if (Result.isComplexFloat()) {
10524 // This is an implementation of complex division according to the
10525 // constraints laid out in C11 Annex G. The implementation uses the
10526 // following naming scheme:
10527 // (a + ib) / (c + id)
10528 ComplexValue LHS = Result;
10529 APFloat &A = LHS.getComplexFloatReal();
10530 APFloat &B = LHS.getComplexFloatImag();
10531 APFloat &C = RHS.getComplexFloatReal();
10532 APFloat &D = RHS.getComplexFloatImag();
10533 APFloat &ResR = Result.getComplexFloatReal();
10534 APFloat &ResI = Result.getComplexFloatImag();
10540 // No real optimizations we can do here, stub out with zero.
10541 B = APFloat::getZero(A.getSemantics());
10544 APFloat MaxCD = maxnum(abs(C), abs(D));
10545 if (MaxCD.isFinite()) {
10546 DenomLogB = ilogb(MaxCD);
10547 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10548 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10550 APFloat Denom = C * C + D * D;
10551 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10552 APFloat::rmNearestTiesToEven);
10553 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10554 APFloat::rmNearestTiesToEven);
10555 if (ResR.isNaN() && ResI.isNaN()) {
10556 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10557 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10558 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10559 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10561 A = APFloat::copySign(
10562 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10563 B = APFloat::copySign(
10564 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10565 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10566 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10567 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10568 C = APFloat::copySign(
10569 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10570 D = APFloat::copySign(
10571 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10572 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10573 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10578 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10579 return Error(E, diag::note_expr_divide_by_zero);
10581 ComplexValue LHS = Result;
10582 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10583 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10584 Result.getComplexIntReal() =
10585 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10586 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10587 Result.getComplexIntImag() =
10588 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10589 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10597 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10598 // Get the operand value into 'Result'.
10599 if (!Visit(E->getSubExpr()))
10602 switch (E->getOpcode()) {
10608 // The result is always just the subexpr.
10611 if (Result.isComplexFloat()) {
10612 Result.getComplexFloatReal().changeSign();
10613 Result.getComplexFloatImag().changeSign();
10616 Result.getComplexIntReal() = -Result.getComplexIntReal();
10617 Result.getComplexIntImag() = -Result.getComplexIntImag();
10621 if (Result.isComplexFloat())
10622 Result.getComplexFloatImag().changeSign();
10624 Result.getComplexIntImag() = -Result.getComplexIntImag();
10629 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10630 if (E->getNumInits() == 2) {
10631 if (E->getType()->isComplexType()) {
10632 Result.makeComplexFloat();
10633 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10635 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10638 Result.makeComplexInt();
10639 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10641 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10646 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10649 //===----------------------------------------------------------------------===//
10650 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10651 // implicit conversion.
10652 //===----------------------------------------------------------------------===//
10655 class AtomicExprEvaluator :
10656 public ExprEvaluatorBase<AtomicExprEvaluator> {
10657 const LValue *This;
10660 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10661 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10663 bool Success(const APValue &V, const Expr *E) {
10668 bool ZeroInitialization(const Expr *E) {
10669 ImplicitValueInitExpr VIE(
10670 E->getType()->castAs<AtomicType>()->getValueType());
10671 // For atomic-qualified class (and array) types in C++, initialize the
10672 // _Atomic-wrapped subobject directly, in-place.
10673 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10674 : Evaluate(Result, Info, &VIE);
10677 bool VisitCastExpr(const CastExpr *E) {
10678 switch (E->getCastKind()) {
10680 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10681 case CK_NonAtomicToAtomic:
10682 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10683 : Evaluate(Result, Info, E->getSubExpr());
10687 } // end anonymous namespace
10689 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10691 assert(E->isRValue() && E->getType()->isAtomicType());
10692 return AtomicExprEvaluator(Info, This, Result).Visit(E);
10695 //===----------------------------------------------------------------------===//
10696 // Void expression evaluation, primarily for a cast to void on the LHS of a
10698 //===----------------------------------------------------------------------===//
10701 class VoidExprEvaluator
10702 : public ExprEvaluatorBase<VoidExprEvaluator> {
10704 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10706 bool Success(const APValue &V, const Expr *e) { return true; }
10708 bool ZeroInitialization(const Expr *E) { return true; }
10710 bool VisitCastExpr(const CastExpr *E) {
10711 switch (E->getCastKind()) {
10713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10715 VisitIgnoredValue(E->getSubExpr());
10720 bool VisitCallExpr(const CallExpr *E) {
10721 switch (E->getBuiltinCallee()) {
10723 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10724 case Builtin::BI__assume:
10725 case Builtin::BI__builtin_assume:
10726 // The argument is not evaluated!
10731 } // end anonymous namespace
10733 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10734 assert(E->isRValue() && E->getType()->isVoidType());
10735 return VoidExprEvaluator(Info).Visit(E);
10738 //===----------------------------------------------------------------------===//
10739 // Top level Expr::EvaluateAsRValue method.
10740 //===----------------------------------------------------------------------===//
10742 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10743 // In C, function designators are not lvalues, but we evaluate them as if they
10745 QualType T = E->getType();
10746 if (E->isGLValue() || T->isFunctionType()) {
10748 if (!EvaluateLValue(E, LV, Info))
10750 LV.moveInto(Result);
10751 } else if (T->isVectorType()) {
10752 if (!EvaluateVector(E, Result, Info))
10754 } else if (T->isIntegralOrEnumerationType()) {
10755 if (!IntExprEvaluator(Info, Result).Visit(E))
10757 } else if (T->hasPointerRepresentation()) {
10759 if (!EvaluatePointer(E, LV, Info))
10761 LV.moveInto(Result);
10762 } else if (T->isRealFloatingType()) {
10763 llvm::APFloat F(0.0);
10764 if (!EvaluateFloat(E, F, Info))
10766 Result = APValue(F);
10767 } else if (T->isAnyComplexType()) {
10769 if (!EvaluateComplex(E, C, Info))
10771 C.moveInto(Result);
10772 } else if (T->isFixedPointType()) {
10773 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10774 } else if (T->isMemberPointerType()) {
10776 if (!EvaluateMemberPointer(E, P, Info))
10778 P.moveInto(Result);
10780 } else if (T->isArrayType()) {
10782 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10783 if (!EvaluateArray(E, LV, Value, Info))
10786 } else if (T->isRecordType()) {
10788 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10789 if (!EvaluateRecord(E, LV, Value, Info))
10792 } else if (T->isVoidType()) {
10793 if (!Info.getLangOpts().CPlusPlus11)
10794 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10796 if (!EvaluateVoid(E, Info))
10798 } else if (T->isAtomicType()) {
10799 QualType Unqual = T.getAtomicUnqualifiedType();
10800 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10802 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10803 if (!EvaluateAtomic(E, &LV, Value, Info))
10806 if (!EvaluateAtomic(E, nullptr, Result, Info))
10809 } else if (Info.getLangOpts().CPlusPlus11) {
10810 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10813 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10820 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10821 /// cases, the in-place evaluation is essential, since later initializers for
10822 /// an object can indirectly refer to subobjects which were initialized earlier.
10823 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10824 const Expr *E, bool AllowNonLiteralTypes) {
10825 assert(!E->isValueDependent());
10827 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10830 if (E->isRValue()) {
10831 // Evaluate arrays and record types in-place, so that later initializers can
10832 // refer to earlier-initialized members of the object.
10833 QualType T = E->getType();
10834 if (T->isArrayType())
10835 return EvaluateArray(E, This, Result, Info);
10836 else if (T->isRecordType())
10837 return EvaluateRecord(E, This, Result, Info);
10838 else if (T->isAtomicType()) {
10839 QualType Unqual = T.getAtomicUnqualifiedType();
10840 if (Unqual->isArrayType() || Unqual->isRecordType())
10841 return EvaluateAtomic(E, &This, Result, Info);
10845 // For any other type, in-place evaluation is unimportant.
10846 return Evaluate(Result, Info, E);
10849 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10850 /// lvalue-to-rvalue cast if it is an lvalue.
10851 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10852 if (E->getType().isNull())
10855 if (!CheckLiteralType(Info, E))
10858 if (!::Evaluate(Result, Info, E))
10861 if (E->isGLValue()) {
10863 LV.setFrom(Info.Ctx, Result);
10864 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10868 // Check this core constant expression is a constant expression.
10869 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10872 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10873 const ASTContext &Ctx, bool &IsConst) {
10874 // Fast-path evaluations of integer literals, since we sometimes see files
10875 // containing vast quantities of these.
10876 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10877 Result.Val = APValue(APSInt(L->getValue(),
10878 L->getType()->isUnsignedIntegerType()));
10883 // This case should be rare, but we need to check it before we check on
10885 if (Exp->getType().isNull()) {
10890 // FIXME: Evaluating values of large array and record types can cause
10891 // performance problems. Only do so in C++11 for now.
10892 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10893 Exp->getType()->isRecordType()) &&
10894 !Ctx.getLangOpts().CPlusPlus11) {
10901 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10902 Expr::SideEffectsKind SEK) {
10903 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10904 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10907 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
10908 const ASTContext &Ctx, EvalInfo &Info) {
10910 if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
10913 return EvaluateAsRValue(Info, E, Result.Val);
10916 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
10917 const ASTContext &Ctx,
10918 Expr::SideEffectsKind AllowSideEffects,
10920 if (!E->getType()->isIntegralOrEnumerationType())
10923 if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
10924 !ExprResult.Val.isInt() ||
10925 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10931 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10932 /// any crazy technique (that has nothing to do with language standards) that
10933 /// we want to. If this function returns true, it returns the folded constant
10934 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10935 /// will be applied to the result.
10936 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
10937 bool InConstantContext) const {
10938 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10939 Info.InConstantContext = InConstantContext;
10940 return ::EvaluateAsRValue(this, Result, Ctx, Info);
10943 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10944 const ASTContext &Ctx) const {
10945 EvalResult Scratch;
10946 return EvaluateAsRValue(Scratch, Ctx) &&
10947 HandleConversionToBool(Scratch.Val, Result);
10950 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
10951 SideEffectsKind AllowSideEffects) const {
10952 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10953 return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
10956 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10957 SideEffectsKind AllowSideEffects) const {
10958 if (!getType()->isRealFloatingType())
10961 EvalResult ExprResult;
10962 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10963 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10966 Result = ExprResult.Val.getFloat();
10970 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10971 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10974 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10975 !CheckLValueConstantExpression(Info, getExprLoc(),
10976 Ctx.getLValueReferenceType(getType()), LV,
10977 Expr::EvaluateForCodeGen))
10980 LV.moveInto(Result.Val);
10984 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10985 const ASTContext &Ctx) const {
10986 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10987 EvalInfo Info(Ctx, Result, EM);
10988 Info.InConstantContext = true;
10989 if (!::Evaluate(Result.Val, Info, this))
10992 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10996 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10998 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10999 // FIXME: Evaluating initializers for large array and record types can cause
11000 // performance problems. Only do so in C++11 for now.
11001 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
11002 !Ctx.getLangOpts().CPlusPlus11)
11005 Expr::EvalStatus EStatus;
11006 EStatus.Diag = &Notes;
11008 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
11009 ? EvalInfo::EM_ConstantExpression
11010 : EvalInfo::EM_ConstantFold);
11011 InitInfo.setEvaluatingDecl(VD, Value);
11012 InitInfo.InConstantContext = true;
11017 // C++11 [basic.start.init]p2:
11018 // Variables with static storage duration or thread storage duration shall be
11019 // zero-initialized before any other initialization takes place.
11020 // This behavior is not present in C.
11021 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
11022 !VD->getType()->isReferenceType()) {
11023 ImplicitValueInitExpr VIE(VD->getType());
11024 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
11025 /*AllowNonLiteralTypes=*/true))
11029 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
11030 /*AllowNonLiteralTypes=*/true) ||
11031 EStatus.HasSideEffects)
11034 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
11038 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
11039 /// constant folded, but discard the result.
11040 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
11042 return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
11043 !hasUnacceptableSideEffect(Result, SEK);
11046 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
11047 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11048 EvalResult EVResult;
11049 EVResult.Diag = Diag;
11050 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
11051 Info.InConstantContext = true;
11053 bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
11055 assert(Result && "Could not evaluate expression");
11056 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11058 return EVResult.Val.getInt();
11061 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
11062 const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
11063 EvalResult EVResult;
11064 EVResult.Diag = Diag;
11065 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11066 Info.InConstantContext = true;
11068 bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
11070 assert(Result && "Could not evaluate expression");
11071 assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
11073 return EVResult.Val.getInt();
11076 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
11078 EvalResult EVResult;
11079 if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
11080 EvalInfo Info(Ctx, EVResult, EvalInfo::EM_EvaluateForOverflow);
11081 (void)::EvaluateAsRValue(Info, this, EVResult.Val);
11085 bool Expr::EvalResult::isGlobalLValue() const {
11086 assert(Val.isLValue());
11087 return IsGlobalLValue(Val.getLValueBase());
11091 /// isIntegerConstantExpr - this recursive routine will test if an expression is
11092 /// an integer constant expression.
11094 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
11097 // CheckICE - This function does the fundamental ICE checking: the returned
11098 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
11099 // and a (possibly null) SourceLocation indicating the location of the problem.
11101 // Note that to reduce code duplication, this helper does no evaluation
11102 // itself; the caller checks whether the expression is evaluatable, and
11103 // in the rare cases where CheckICE actually cares about the evaluated
11104 // value, it calls into Evaluate.
11109 /// This expression is an ICE.
11111 /// This expression is not an ICE, but if it isn't evaluated, it's
11112 /// a legal subexpression for an ICE. This return value is used to handle
11113 /// the comma operator in C99 mode, and non-constant subexpressions.
11114 IK_ICEIfUnevaluated,
11115 /// This expression is not an ICE, and is not a legal subexpression for one.
11121 SourceLocation Loc;
11123 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
11128 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
11130 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
11132 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
11133 Expr::EvalResult EVResult;
11134 Expr::EvalStatus Status;
11135 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11137 Info.InConstantContext = true;
11138 if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
11139 !EVResult.Val.isInt())
11140 return ICEDiag(IK_NotICE, E->getBeginLoc());
11145 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
11146 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
11147 if (!E->getType()->isIntegralOrEnumerationType())
11148 return ICEDiag(IK_NotICE, E->getBeginLoc());
11150 switch (E->getStmtClass()) {
11151 #define ABSTRACT_STMT(Node)
11152 #define STMT(Node, Base) case Expr::Node##Class:
11153 #define EXPR(Node, Base)
11154 #include "clang/AST/StmtNodes.inc"
11155 case Expr::PredefinedExprClass:
11156 case Expr::FloatingLiteralClass:
11157 case Expr::ImaginaryLiteralClass:
11158 case Expr::StringLiteralClass:
11159 case Expr::ArraySubscriptExprClass:
11160 case Expr::OMPArraySectionExprClass:
11161 case Expr::MemberExprClass:
11162 case Expr::CompoundAssignOperatorClass:
11163 case Expr::CompoundLiteralExprClass:
11164 case Expr::ExtVectorElementExprClass:
11165 case Expr::DesignatedInitExprClass:
11166 case Expr::ArrayInitLoopExprClass:
11167 case Expr::ArrayInitIndexExprClass:
11168 case Expr::NoInitExprClass:
11169 case Expr::DesignatedInitUpdateExprClass:
11170 case Expr::ImplicitValueInitExprClass:
11171 case Expr::ParenListExprClass:
11172 case Expr::VAArgExprClass:
11173 case Expr::AddrLabelExprClass:
11174 case Expr::StmtExprClass:
11175 case Expr::CXXMemberCallExprClass:
11176 case Expr::CUDAKernelCallExprClass:
11177 case Expr::CXXDynamicCastExprClass:
11178 case Expr::CXXTypeidExprClass:
11179 case Expr::CXXUuidofExprClass:
11180 case Expr::MSPropertyRefExprClass:
11181 case Expr::MSPropertySubscriptExprClass:
11182 case Expr::CXXNullPtrLiteralExprClass:
11183 case Expr::UserDefinedLiteralClass:
11184 case Expr::CXXThisExprClass:
11185 case Expr::CXXThrowExprClass:
11186 case Expr::CXXNewExprClass:
11187 case Expr::CXXDeleteExprClass:
11188 case Expr::CXXPseudoDestructorExprClass:
11189 case Expr::UnresolvedLookupExprClass:
11190 case Expr::TypoExprClass:
11191 case Expr::DependentScopeDeclRefExprClass:
11192 case Expr::CXXConstructExprClass:
11193 case Expr::CXXInheritedCtorInitExprClass:
11194 case Expr::CXXStdInitializerListExprClass:
11195 case Expr::CXXBindTemporaryExprClass:
11196 case Expr::ExprWithCleanupsClass:
11197 case Expr::CXXTemporaryObjectExprClass:
11198 case Expr::CXXUnresolvedConstructExprClass:
11199 case Expr::CXXDependentScopeMemberExprClass:
11200 case Expr::UnresolvedMemberExprClass:
11201 case Expr::ObjCStringLiteralClass:
11202 case Expr::ObjCBoxedExprClass:
11203 case Expr::ObjCArrayLiteralClass:
11204 case Expr::ObjCDictionaryLiteralClass:
11205 case Expr::ObjCEncodeExprClass:
11206 case Expr::ObjCMessageExprClass:
11207 case Expr::ObjCSelectorExprClass:
11208 case Expr::ObjCProtocolExprClass:
11209 case Expr::ObjCIvarRefExprClass:
11210 case Expr::ObjCPropertyRefExprClass:
11211 case Expr::ObjCSubscriptRefExprClass:
11212 case Expr::ObjCIsaExprClass:
11213 case Expr::ObjCAvailabilityCheckExprClass:
11214 case Expr::ShuffleVectorExprClass:
11215 case Expr::ConvertVectorExprClass:
11216 case Expr::BlockExprClass:
11217 case Expr::NoStmtClass:
11218 case Expr::OpaqueValueExprClass:
11219 case Expr::PackExpansionExprClass:
11220 case Expr::SubstNonTypeTemplateParmPackExprClass:
11221 case Expr::FunctionParmPackExprClass:
11222 case Expr::AsTypeExprClass:
11223 case Expr::ObjCIndirectCopyRestoreExprClass:
11224 case Expr::MaterializeTemporaryExprClass:
11225 case Expr::PseudoObjectExprClass:
11226 case Expr::AtomicExprClass:
11227 case Expr::LambdaExprClass:
11228 case Expr::CXXFoldExprClass:
11229 case Expr::CoawaitExprClass:
11230 case Expr::DependentCoawaitExprClass:
11231 case Expr::CoyieldExprClass:
11232 return ICEDiag(IK_NotICE, E->getBeginLoc());
11234 case Expr::InitListExprClass: {
11235 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11236 // form "T x = { a };" is equivalent to "T x = a;".
11237 // Unless we're initializing a reference, T is a scalar as it is known to be
11238 // of integral or enumeration type.
11240 if (cast<InitListExpr>(E)->getNumInits() == 1)
11241 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
11242 return ICEDiag(IK_NotICE, E->getBeginLoc());
11245 case Expr::SizeOfPackExprClass:
11246 case Expr::GNUNullExprClass:
11247 // GCC considers the GNU __null value to be an integral constant expression.
11250 case Expr::SubstNonTypeTemplateParmExprClass:
11252 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11254 case Expr::ConstantExprClass:
11255 return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11257 case Expr::ParenExprClass:
11258 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
11259 case Expr::GenericSelectionExprClass:
11260 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
11261 case Expr::IntegerLiteralClass:
11262 case Expr::FixedPointLiteralClass:
11263 case Expr::CharacterLiteralClass:
11264 case Expr::ObjCBoolLiteralExprClass:
11265 case Expr::CXXBoolLiteralExprClass:
11266 case Expr::CXXScalarValueInitExprClass:
11267 case Expr::TypeTraitExprClass:
11268 case Expr::ArrayTypeTraitExprClass:
11269 case Expr::ExpressionTraitExprClass:
11270 case Expr::CXXNoexceptExprClass:
11272 case Expr::CallExprClass:
11273 case Expr::CXXOperatorCallExprClass: {
11274 // C99 6.6/3 allows function calls within unevaluated subexpressions of
11275 // constant expressions, but they can never be ICEs because an ICE cannot
11276 // contain an operand of (pointer to) function type.
11277 const CallExpr *CE = cast<CallExpr>(E);
11278 if (CE->getBuiltinCallee())
11279 return CheckEvalInICE(E, Ctx);
11280 return ICEDiag(IK_NotICE, E->getBeginLoc());
11282 case Expr::DeclRefExprClass: {
11283 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11285 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
11286 if (Ctx.getLangOpts().CPlusPlus &&
11287 D && IsConstNonVolatile(D->getType())) {
11288 // Parameter variables are never constants. Without this check,
11289 // getAnyInitializer() can find a default argument, which leads
11291 if (isa<ParmVarDecl>(D))
11292 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11295 // A variable of non-volatile const-qualified integral or enumeration
11296 // type initialized by an ICE can be used in ICEs.
11297 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
11298 if (!Dcl->getType()->isIntegralOrEnumerationType())
11299 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11302 // Look for a declaration of this variable that has an initializer, and
11303 // check whether it is an ICE.
11304 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11307 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11310 return ICEDiag(IK_NotICE, E->getBeginLoc());
11312 case Expr::UnaryOperatorClass: {
11313 const UnaryOperator *Exp = cast<UnaryOperator>(E);
11314 switch (Exp->getOpcode()) {
11322 // C99 6.6/3 allows increment and decrement within unevaluated
11323 // subexpressions of constant expressions, but they can never be ICEs
11324 // because an ICE cannot contain an lvalue operand.
11325 return ICEDiag(IK_NotICE, E->getBeginLoc());
11333 return CheckICE(Exp->getSubExpr(), Ctx);
11335 llvm_unreachable("invalid unary operator class");
11337 case Expr::OffsetOfExprClass: {
11338 // Note that per C99, offsetof must be an ICE. And AFAIK, using
11339 // EvaluateAsRValue matches the proposed gcc behavior for cases like
11340 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
11341 // compliance: we should warn earlier for offsetof expressions with
11342 // array subscripts that aren't ICEs, and if the array subscripts
11343 // are ICEs, the value of the offsetof must be an integer constant.
11344 return CheckEvalInICE(E, Ctx);
11346 case Expr::UnaryExprOrTypeTraitExprClass: {
11347 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11348 if ((Exp->getKind() == UETT_SizeOf) &&
11349 Exp->getTypeOfArgument()->isVariableArrayType())
11350 return ICEDiag(IK_NotICE, E->getBeginLoc());
11353 case Expr::BinaryOperatorClass: {
11354 const BinaryOperator *Exp = cast<BinaryOperator>(E);
11355 switch (Exp->getOpcode()) {
11369 // C99 6.6/3 allows assignments within unevaluated subexpressions of
11370 // constant expressions, but they can never be ICEs because an ICE cannot
11371 // contain an lvalue operand.
11372 return ICEDiag(IK_NotICE, E->getBeginLoc());
11392 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11393 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11394 if (Exp->getOpcode() == BO_Div ||
11395 Exp->getOpcode() == BO_Rem) {
11396 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11397 // we don't evaluate one.
11398 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11399 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11401 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11402 if (REval.isSigned() && REval.isAllOnesValue()) {
11403 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11404 if (LEval.isMinSignedValue())
11405 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11409 if (Exp->getOpcode() == BO_Comma) {
11410 if (Ctx.getLangOpts().C99) {
11411 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11412 // if it isn't evaluated.
11413 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11414 return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11416 // In both C89 and C++, commas in ICEs are illegal.
11417 return ICEDiag(IK_NotICE, E->getBeginLoc());
11420 return Worst(LHSResult, RHSResult);
11424 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11425 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11426 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11427 // Rare case where the RHS has a comma "side-effect"; we need
11428 // to actually check the condition to see whether the side
11429 // with the comma is evaluated.
11430 if ((Exp->getOpcode() == BO_LAnd) !=
11431 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11436 return Worst(LHSResult, RHSResult);
11439 llvm_unreachable("invalid binary operator kind");
11441 case Expr::ImplicitCastExprClass:
11442 case Expr::CStyleCastExprClass:
11443 case Expr::CXXFunctionalCastExprClass:
11444 case Expr::CXXStaticCastExprClass:
11445 case Expr::CXXReinterpretCastExprClass:
11446 case Expr::CXXConstCastExprClass:
11447 case Expr::ObjCBridgedCastExprClass: {
11448 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11449 if (isa<ExplicitCastExpr>(E)) {
11450 if (const FloatingLiteral *FL
11451 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11452 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11453 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11454 APSInt IgnoredVal(DestWidth, !DestSigned);
11456 // If the value does not fit in the destination type, the behavior is
11457 // undefined, so we are not required to treat it as a constant
11459 if (FL->getValue().convertToInteger(IgnoredVal,
11460 llvm::APFloat::rmTowardZero,
11461 &Ignored) & APFloat::opInvalidOp)
11462 return ICEDiag(IK_NotICE, E->getBeginLoc());
11466 switch (cast<CastExpr>(E)->getCastKind()) {
11467 case CK_LValueToRValue:
11468 case CK_AtomicToNonAtomic:
11469 case CK_NonAtomicToAtomic:
11471 case CK_IntegralToBoolean:
11472 case CK_IntegralCast:
11473 return CheckICE(SubExpr, Ctx);
11475 return ICEDiag(IK_NotICE, E->getBeginLoc());
11478 case Expr::BinaryConditionalOperatorClass: {
11479 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11480 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11481 if (CommonResult.Kind == IK_NotICE) return CommonResult;
11482 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11483 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11484 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11485 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11486 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11487 return FalseResult;
11489 case Expr::ConditionalOperatorClass: {
11490 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11491 // If the condition (ignoring parens) is a __builtin_constant_p call,
11492 // then only the true side is actually considered in an integer constant
11493 // expression, and it is fully evaluated. This is an important GNU
11494 // extension. See GCC PR38377 for discussion.
11495 if (const CallExpr *CallCE
11496 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11497 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11498 return CheckEvalInICE(E, Ctx);
11499 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11500 if (CondResult.Kind == IK_NotICE)
11503 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11504 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11506 if (TrueResult.Kind == IK_NotICE)
11508 if (FalseResult.Kind == IK_NotICE)
11509 return FalseResult;
11510 if (CondResult.Kind == IK_ICEIfUnevaluated)
11512 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11514 // Rare case where the diagnostics depend on which side is evaluated
11515 // Note that if we get here, CondResult is 0, and at least one of
11516 // TrueResult and FalseResult is non-zero.
11517 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11518 return FalseResult;
11521 case Expr::CXXDefaultArgExprClass:
11522 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11523 case Expr::CXXDefaultInitExprClass:
11524 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11525 case Expr::ChooseExprClass: {
11526 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11530 llvm_unreachable("Invalid StmtClass!");
11533 /// Evaluate an expression as a C++11 integral constant expression.
11534 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11536 llvm::APSInt *Value,
11537 SourceLocation *Loc) {
11538 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11539 if (Loc) *Loc = E->getExprLoc();
11544 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11547 if (!Result.isInt()) {
11548 if (Loc) *Loc = E->getExprLoc();
11552 if (Value) *Value = Result.getInt();
11556 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11557 SourceLocation *Loc) const {
11558 if (Ctx.getLangOpts().CPlusPlus11)
11559 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11561 ICEDiag D = CheckICE(this, Ctx);
11562 if (D.Kind != IK_ICE) {
11563 if (Loc) *Loc = D.Loc;
11569 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11570 SourceLocation *Loc, bool isEvaluated) const {
11571 if (Ctx.getLangOpts().CPlusPlus11)
11572 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11574 if (!isIntegerConstantExpr(Ctx, Loc))
11577 // The only possible side-effects here are due to UB discovered in the
11578 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11579 // required to treat the expression as an ICE, so we produce the folded
11581 EvalResult ExprResult;
11582 Expr::EvalStatus Status;
11583 EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
11584 Info.InConstantContext = true;
11586 if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
11587 llvm_unreachable("ICE cannot be evaluated!");
11589 Value = ExprResult.Val.getInt();
11593 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11594 return CheckICE(this, Ctx).Kind == IK_ICE;
11597 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11598 SourceLocation *Loc) const {
11599 // We support this checking in C++98 mode in order to diagnose compatibility
11601 assert(Ctx.getLangOpts().CPlusPlus);
11603 // Build evaluation settings.
11604 Expr::EvalStatus Status;
11605 SmallVector<PartialDiagnosticAt, 8> Diags;
11606 Status.Diag = &Diags;
11607 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11610 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11612 if (!Diags.empty()) {
11613 IsConstExpr = false;
11614 if (Loc) *Loc = Diags[0].first;
11615 } else if (!IsConstExpr) {
11616 // FIXME: This shouldn't happen.
11617 if (Loc) *Loc = getExprLoc();
11620 return IsConstExpr;
11623 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11624 const FunctionDecl *Callee,
11625 ArrayRef<const Expr*> Args,
11626 const Expr *This) const {
11627 Expr::EvalStatus Status;
11628 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11629 Info.InConstantContext = true;
11632 const LValue *ThisPtr = nullptr;
11635 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11636 assert(MD && "Don't provide `this` for non-methods.");
11637 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11639 if (EvaluateObjectArgument(Info, This, ThisVal))
11640 ThisPtr = &ThisVal;
11641 if (Info.EvalStatus.HasSideEffects)
11645 ArgVector ArgValues(Args.size());
11646 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11648 if ((*I)->isValueDependent() ||
11649 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11650 // If evaluation fails, throw away the argument entirely.
11651 ArgValues[I - Args.begin()] = APValue();
11652 if (Info.EvalStatus.HasSideEffects)
11656 // Build fake call to Callee.
11657 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11659 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11662 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11664 PartialDiagnosticAt> &Diags) {
11665 // FIXME: It would be useful to check constexpr function templates, but at the
11666 // moment the constant expression evaluator cannot cope with the non-rigorous
11667 // ASTs which we build for dependent expressions.
11668 if (FD->isDependentContext())
11671 Expr::EvalStatus Status;
11672 Status.Diag = &Diags;
11674 EvalInfo Info(FD->getASTContext(), Status,
11675 EvalInfo::EM_PotentialConstantExpression);
11676 Info.InConstantContext = true;
11678 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11679 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11681 // Fabricate an arbitrary expression on the stack and pretend that it
11682 // is a temporary being used as the 'this' pointer.
11684 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11685 This.set({&VIE, Info.CurrentCall->Index});
11687 ArrayRef<const Expr*> Args;
11690 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11691 // Evaluate the call as a constant initializer, to allow the construction
11692 // of objects of non-literal types.
11693 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11694 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11696 SourceLocation Loc = FD->getLocation();
11697 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11698 Args, FD->getBody(), Info, Scratch, nullptr);
11701 return Diags.empty();
11704 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11705 const FunctionDecl *FD,
11707 PartialDiagnosticAt> &Diags) {
11708 Expr::EvalStatus Status;
11709 Status.Diag = &Diags;
11711 EvalInfo Info(FD->getASTContext(), Status,
11712 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11713 Info.InConstantContext = true;
11715 // Fabricate a call stack frame to give the arguments a plausible cover story.
11716 ArrayRef<const Expr*> Args;
11717 ArgVector ArgValues(0);
11718 bool Success = EvaluateArgs(Args, ArgValues, Info);
11721 "Failed to set up arguments for potential constant evaluation");
11722 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11724 APValue ResultScratch;
11725 Evaluate(ResultScratch, Info, E);
11726 return Diags.empty();
11729 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11730 unsigned Type) const {
11731 if (!getType()->isPointerType())
11734 Expr::EvalStatus Status;
11735 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11736 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);