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/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
51 #define DEBUG_TYPE "exprconstant"
53 using namespace clang;
57 static bool IsGlobalLValue(APValue::LValueBase B);
61 struct CallStackFrame;
64 static QualType getType(APValue::LValueBase B) {
65 if (!B) return QualType();
66 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
67 // FIXME: It's unclear where we're supposed to take the type from, and
68 // this actually matters for arrays of unknown bound. Eg:
70 // extern int arr[]; void f() { extern int arr[3]; };
71 // constexpr int *p = &arr[1]; // valid?
73 // For now, we take the array bound from the most recent declaration.
74 for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75 Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76 QualType T = Redecl->getType();
77 if (!T->isIncompleteArrayType())
83 const Expr *Base = B.get<const Expr*>();
85 // For a materialized temporary, the type of the temporary we materialized
86 // may not be the type of the expression.
87 if (const MaterializeTemporaryExpr *MTE =
88 dyn_cast<MaterializeTemporaryExpr>(Base)) {
89 SmallVector<const Expr *, 2> CommaLHSs;
90 SmallVector<SubobjectAdjustment, 2> Adjustments;
91 const Expr *Temp = MTE->GetTemporaryExpr();
92 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
94 // Keep any cv-qualifiers from the reference if we generated a temporary
95 // for it directly. Otherwise use the type after adjustment.
96 if (!Adjustments.empty())
97 return Inner->getType();
100 return Base->getType();
103 /// Get an LValue path entry, which is known to not be an array index, as a
104 /// field or base class.
106 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
107 APValue::BaseOrMemberType Value;
108 Value.setFromOpaqueValue(E.BaseOrMember);
112 /// Get an LValue path entry, which is known to not be an array index, as a
113 /// field declaration.
114 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
115 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
117 /// Get an LValue path entry, which is known to not be an array index, as a
118 /// base class declaration.
119 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
120 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
122 /// Determine whether this LValue path entry for a base class names a virtual
124 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
125 return getAsBaseOrMember(E).getInt();
128 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130 const FunctionDecl *Callee = CE->getDirectCallee();
131 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135 /// This will look through a single cast.
137 /// Returns null if we couldn't unwrap a function with alloc_size.
138 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139 if (!E->getType()->isPointerType())
142 E = E->IgnoreParens();
143 // If we're doing a variable assignment from e.g. malloc(N), there will
144 // probably be a cast of some kind. In exotic cases, we might also see a
145 // top-level ExprWithCleanups. Ignore them either way.
146 if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147 E = EC->getSubExpr()->IgnoreParens();
149 if (const auto *Cast = dyn_cast<CastExpr>(E))
150 E = Cast->getSubExpr()->IgnoreParens();
152 if (const auto *CE = dyn_cast<CallExpr>(E))
153 return getAllocSizeAttr(CE) ? CE : nullptr;
157 /// Determines whether or not the given Base contains a call to a function
158 /// with the alloc_size attribute.
159 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160 const auto *E = Base.dyn_cast<const Expr *>();
161 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164 /// The bound to claim that an array of unknown bound has.
165 /// The value in MostDerivedArraySize is undefined in this case. So, set it
166 /// to an arbitrary value that's likely to loudly break things if it's used.
167 static const uint64_t AssumedSizeForUnsizedArray =
168 std::numeric_limits<uint64_t>::max() / 2;
170 /// Determines if an LValue with the given LValueBase will have an unsized
171 /// array in its designator.
172 /// Find the path length and type of the most-derived subobject in the given
173 /// path, and find the size of the containing array, if any.
175 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176 ArrayRef<APValue::LValuePathEntry> Path,
177 uint64_t &ArraySize, QualType &Type, bool &IsArray,
178 bool &FirstEntryIsUnsizedArray) {
179 // This only accepts LValueBases from APValues, and APValues don't support
180 // arrays that lack size info.
181 assert(!isBaseAnAllocSizeCall(Base) &&
182 "Unsized arrays shouldn't appear here");
183 unsigned MostDerivedLength = 0;
184 Type = getType(Base);
186 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
187 if (Type->isArrayType()) {
188 const ArrayType *AT = Ctx.getAsArrayType(Type);
189 Type = AT->getElementType();
190 MostDerivedLength = I + 1;
193 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194 ArraySize = CAT->getSize().getZExtValue();
196 assert(I == 0 && "unexpected unsized array designator");
197 FirstEntryIsUnsizedArray = true;
198 ArraySize = AssumedSizeForUnsizedArray;
200 } else if (Type->isAnyComplexType()) {
201 const ComplexType *CT = Type->castAs<ComplexType>();
202 Type = CT->getElementType();
204 MostDerivedLength = I + 1;
206 } else if (const FieldDecl *FD = getAsField(Path[I])) {
207 Type = FD->getType();
209 MostDerivedLength = I + 1;
212 // Path[I] describes a base class.
217 return MostDerivedLength;
220 // The order of this enum is important for diagnostics.
221 enum CheckSubobjectKind {
222 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
223 CSK_This, CSK_Real, CSK_Imag
226 /// A path from a glvalue to a subobject of that glvalue.
227 struct SubobjectDesignator {
228 /// True if the subobject was named in a manner not supported by C++11. Such
229 /// lvalues can still be folded, but they are not core constant expressions
230 /// and we cannot perform lvalue-to-rvalue conversions on them.
231 unsigned Invalid : 1;
233 /// Is this a pointer one past the end of an object?
234 unsigned IsOnePastTheEnd : 1;
236 /// Indicator of whether the first entry is an unsized array.
237 unsigned FirstEntryIsAnUnsizedArray : 1;
239 /// Indicator of whether the most-derived object is an array element.
240 unsigned MostDerivedIsArrayElement : 1;
242 /// The length of the path to the most-derived object of which this is a
244 unsigned MostDerivedPathLength : 28;
246 /// The size of the array of which the most-derived object is an element.
247 /// This will always be 0 if the most-derived object is not an array
248 /// element. 0 is not an indicator of whether or not the most-derived object
249 /// is an array, however, because 0-length arrays are allowed.
251 /// If the current array is an unsized array, the value of this is
253 uint64_t MostDerivedArraySize;
255 /// The type of the most derived object referred to by this address.
256 QualType MostDerivedType;
258 typedef APValue::LValuePathEntry PathEntry;
260 /// The entries on the path from the glvalue to the designated subobject.
261 SmallVector<PathEntry, 8> Entries;
263 SubobjectDesignator() : Invalid(true) {}
265 explicit SubobjectDesignator(QualType T)
266 : Invalid(false), IsOnePastTheEnd(false),
267 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
268 MostDerivedPathLength(0), MostDerivedArraySize(0),
269 MostDerivedType(T) {}
271 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
272 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
273 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274 MostDerivedPathLength(0), MostDerivedArraySize(0) {
275 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
277 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
278 ArrayRef<PathEntry> VEntries = V.getLValuePath();
279 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
280 if (V.getLValueBase()) {
281 bool IsArray = false;
282 bool FirstIsUnsizedArray = false;
283 MostDerivedPathLength = findMostDerivedSubobject(
284 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
285 MostDerivedType, IsArray, FirstIsUnsizedArray);
286 MostDerivedIsArrayElement = IsArray;
287 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297 /// Determine whether the most derived subobject is an array without a
299 bool isMostDerivedAnUnsizedArray() const {
300 assert(!Invalid && "Calling this makes no sense on invalid designators");
301 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
304 /// Determine what the most derived array's size is. Results in an assertion
305 /// failure if the most derived array lacks a size.
306 uint64_t getMostDerivedArraySize() const {
307 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308 return MostDerivedArraySize;
311 /// Determine whether this is a one-past-the-end pointer.
312 bool isOnePastTheEnd() const {
316 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
317 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
322 /// Check that this refers to a valid subobject.
323 bool isValidSubobject() const {
326 return !isOnePastTheEnd();
328 /// Check that this refers to a valid subobject, and if not, produce a
329 /// relevant diagnostic and set the designator as invalid.
330 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
332 /// Update this designator to refer to the first element within this array.
333 void addArrayUnchecked(const ConstantArrayType *CAT) {
335 Entry.ArrayIndex = 0;
336 Entries.push_back(Entry);
338 // This is a most-derived object.
339 MostDerivedType = CAT->getElementType();
340 MostDerivedIsArrayElement = true;
341 MostDerivedArraySize = CAT->getSize().getZExtValue();
342 MostDerivedPathLength = Entries.size();
344 /// Update this designator to refer to the first element within the array of
345 /// elements of type T. This is an array of unknown size.
346 void addUnsizedArrayUnchecked(QualType ElemTy) {
348 Entry.ArrayIndex = 0;
349 Entries.push_back(Entry);
351 MostDerivedType = ElemTy;
352 MostDerivedIsArrayElement = true;
353 // The value in MostDerivedArraySize is undefined in this case. So, set it
354 // to an arbitrary value that's likely to loudly break things if it's
356 MostDerivedArraySize = AssumedSizeForUnsizedArray;
357 MostDerivedPathLength = Entries.size();
359 /// Update this designator to refer to the given base or member of this
361 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
363 APValue::BaseOrMemberType Value(D, Virtual);
364 Entry.BaseOrMember = Value.getOpaqueValue();
365 Entries.push_back(Entry);
367 // If this isn't a base class, it's a new most-derived object.
368 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
369 MostDerivedType = FD->getType();
370 MostDerivedIsArrayElement = false;
371 MostDerivedArraySize = 0;
372 MostDerivedPathLength = Entries.size();
375 /// Update this designator to refer to the given complex component.
376 void addComplexUnchecked(QualType EltTy, bool Imag) {
378 Entry.ArrayIndex = Imag;
379 Entries.push_back(Entry);
381 // This is technically a most-derived object, though in practice this
382 // is unlikely to matter.
383 MostDerivedType = EltTy;
384 MostDerivedIsArrayElement = true;
385 MostDerivedArraySize = 2;
386 MostDerivedPathLength = Entries.size();
388 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
389 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
391 /// Add N to the address of this subobject.
392 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
393 if (Invalid || !N) return;
394 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
395 if (isMostDerivedAnUnsizedArray()) {
396 diagnoseUnsizedArrayPointerArithmetic(Info, E);
397 // Can't verify -- trust that the user is doing the right thing (or if
398 // not, trust that the caller will catch the bad behavior).
399 // FIXME: Should we reject if this overflows, at least?
400 Entries.back().ArrayIndex += TruncatedN;
404 // [expr.add]p4: For the purposes of these operators, a pointer to a
405 // nonarray object behaves the same as a pointer to the first element of
406 // an array of length one with the type of the object as its element type.
407 bool IsArray = MostDerivedPathLength == Entries.size() &&
408 MostDerivedIsArrayElement;
409 uint64_t ArrayIndex =
410 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
412 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
414 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
415 // Calculate the actual index in a wide enough type, so we can include
417 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
418 (llvm::APInt&)N += ArrayIndex;
419 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
420 diagnosePointerArithmetic(Info, E, N);
425 ArrayIndex += TruncatedN;
426 assert(ArrayIndex <= ArraySize &&
427 "bounds check succeeded for out-of-bounds index");
430 Entries.back().ArrayIndex = ArrayIndex;
432 IsOnePastTheEnd = (ArrayIndex != 0);
436 /// A stack frame in the constexpr call stack.
437 struct CallStackFrame {
440 /// Parent - The caller of this stack frame.
441 CallStackFrame *Caller;
443 /// Callee - The function which was called.
444 const FunctionDecl *Callee;
446 /// This - The binding for the this pointer in this call, if any.
449 /// Arguments - Parameter bindings for this function call, indexed by
450 /// parameters' function scope indices.
453 // Note that we intentionally use std::map here so that references to
454 // values are stable.
455 typedef std::pair<const void *, unsigned> MapKeyTy;
456 typedef std::map<MapKeyTy, APValue> MapTy;
457 /// Temporaries - Temporary lvalues materialized within this stack frame.
460 /// CallLoc - The location of the call expression for this call.
461 SourceLocation CallLoc;
463 /// Index - The call index of this call.
466 /// The stack of integers for tracking version numbers for temporaries.
467 SmallVector<unsigned, 2> TempVersionStack = {1};
468 unsigned CurTempVersion = TempVersionStack.back();
470 unsigned getTempVersion() const { return TempVersionStack.back(); }
472 void pushTempVersion() {
473 TempVersionStack.push_back(++CurTempVersion);
476 void popTempVersion() {
477 TempVersionStack.pop_back();
480 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
481 // on the overall stack usage of deeply-recursing constexpr evaluataions.
482 // (We should cache this map rather than recomputing it repeatedly.)
483 // But let's try this and see how it goes; we can look into caching the map
484 // as a later change.
486 /// LambdaCaptureFields - Mapping from captured variables/this to
487 /// corresponding data members in the closure class.
488 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
489 FieldDecl *LambdaThisCaptureField;
491 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
492 const FunctionDecl *Callee, const LValue *This,
496 // Return the temporary for Key whose version number is Version.
497 APValue *getTemporary(const void *Key, unsigned Version) {
498 MapKeyTy KV(Key, Version);
499 auto LB = Temporaries.lower_bound(KV);
500 if (LB != Temporaries.end() && LB->first == KV)
502 // Pair (Key,Version) wasn't found in the map. Check that no elements
503 // in the map have 'Key' as their key.
504 assert((LB == Temporaries.end() || LB->first.first != Key) &&
505 (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
506 "Element with key 'Key' found in map");
510 // Return the current temporary for Key in the map.
511 APValue *getCurrentTemporary(const void *Key) {
512 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
513 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
514 return &std::prev(UB)->second;
518 // Return the version number of the current temporary for Key.
519 unsigned getCurrentTemporaryVersion(const void *Key) const {
520 auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
521 if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
522 return std::prev(UB)->first.second;
526 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
529 /// Temporarily override 'this'.
530 class ThisOverrideRAII {
532 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
533 : Frame(Frame), OldThis(Frame.This) {
535 Frame.This = NewThis;
537 ~ThisOverrideRAII() {
538 Frame.This = OldThis;
541 CallStackFrame &Frame;
542 const LValue *OldThis;
545 /// A partial diagnostic which we might know in advance that we are not going
547 class OptionalDiagnostic {
548 PartialDiagnostic *Diag;
551 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
555 OptionalDiagnostic &operator<<(const T &v) {
561 OptionalDiagnostic &operator<<(const APSInt &I) {
563 SmallVector<char, 32> Buffer;
565 *Diag << StringRef(Buffer.data(), Buffer.size());
570 OptionalDiagnostic &operator<<(const APFloat &F) {
572 // FIXME: Force the precision of the source value down so we don't
573 // print digits which are usually useless (we don't really care here if
574 // we truncate a digit by accident in edge cases). Ideally,
575 // APFloat::toString would automatically print the shortest
576 // representation which rounds to the correct value, but it's a bit
577 // tricky to implement.
579 llvm::APFloat::semanticsPrecision(F.getSemantics());
580 precision = (precision * 59 + 195) / 196;
581 SmallVector<char, 32> Buffer;
582 F.toString(Buffer, precision);
583 *Diag << StringRef(Buffer.data(), Buffer.size());
589 /// A cleanup, and a flag indicating whether it is lifetime-extended.
591 llvm::PointerIntPair<APValue*, 1, bool> Value;
594 Cleanup(APValue *Val, bool IsLifetimeExtended)
595 : Value(Val, IsLifetimeExtended) {}
597 bool isLifetimeExtended() const { return Value.getInt(); }
599 *Value.getPointer() = APValue();
603 /// EvalInfo - This is a private struct used by the evaluator to capture
604 /// information about a subexpression as it is folded. It retains information
605 /// about the AST context, but also maintains information about the folded
608 /// If an expression could be evaluated, it is still possible it is not a C
609 /// "integer constant expression" or constant expression. If not, this struct
610 /// captures information about how and why not.
612 /// One bit of information passed *into* the request for constant folding
613 /// indicates whether the subexpression is "evaluated" or not according to C
614 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
615 /// evaluate the expression regardless of what the RHS is, but C only allows
616 /// certain things in certain situations.
620 /// EvalStatus - Contains information about the evaluation.
621 Expr::EvalStatus &EvalStatus;
623 /// CurrentCall - The top of the constexpr call stack.
624 CallStackFrame *CurrentCall;
626 /// CallStackDepth - The number of calls in the call stack right now.
627 unsigned CallStackDepth;
629 /// NextCallIndex - The next call index to assign.
630 unsigned NextCallIndex;
632 /// StepsLeft - The remaining number of evaluation steps we're permitted
633 /// to perform. This is essentially a limit for the number of statements
634 /// we will evaluate.
637 /// BottomFrame - The frame in which evaluation started. This must be
638 /// initialized after CurrentCall and CallStackDepth.
639 CallStackFrame BottomFrame;
641 /// A stack of values whose lifetimes end at the end of some surrounding
642 /// evaluation frame.
643 llvm::SmallVector<Cleanup, 16> CleanupStack;
645 /// EvaluatingDecl - This is the declaration whose initializer is being
646 /// evaluated, if any.
647 APValue::LValueBase EvaluatingDecl;
649 /// EvaluatingDeclValue - This is the value being constructed for the
650 /// declaration whose initializer is being evaluated, if any.
651 APValue *EvaluatingDeclValue;
653 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
654 /// the call index that that lvalue was allocated in.
655 typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
658 /// EvaluatingConstructors - Set of objects that are currently being
660 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
662 struct EvaluatingConstructorRAII {
664 EvaluatingObject Object;
666 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
667 : EI(EI), Object(Object) {
668 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
670 ~EvaluatingConstructorRAII() {
671 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
675 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
677 return EvaluatingConstructors.count(
678 EvaluatingObject(Decl, {CallIndex, Version}));
681 /// The current array initialization index, if we're performing array
683 uint64_t ArrayInitIndex = -1;
685 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
686 /// notes attached to it will also be stored, otherwise they will not be.
687 bool HasActiveDiagnostic;
689 /// Have we emitted a diagnostic explaining why we couldn't constant
690 /// fold (not just why it's not strictly a constant expression)?
691 bool HasFoldFailureDiagnostic;
693 /// Whether or not we're currently speculatively evaluating.
694 bool IsSpeculativelyEvaluating;
696 enum EvaluationMode {
697 /// Evaluate as a constant expression. Stop if we find that the expression
698 /// is not a constant expression.
699 EM_ConstantExpression,
701 /// Evaluate as a potential constant expression. Keep going if we hit a
702 /// construct that we can't evaluate yet (because we don't yet know the
703 /// value of something) but stop if we hit something that could never be
704 /// a constant expression.
705 EM_PotentialConstantExpression,
707 /// Fold the expression to a constant. Stop if we hit a side-effect that
711 /// Evaluate the expression looking for integer overflow and similar
712 /// issues. Don't worry about side-effects, and try to visit all
714 EM_EvaluateForOverflow,
716 /// Evaluate in any way we know how. Don't worry about side-effects that
717 /// can't be modeled.
718 EM_IgnoreSideEffects,
720 /// Evaluate as a constant expression. Stop if we find that the expression
721 /// is not a constant expression. Some expressions can be retried in the
722 /// optimizer if we don't constant fold them here, but in an unevaluated
723 /// context we try to fold them immediately since the optimizer never
724 /// gets a chance to look at it.
725 EM_ConstantExpressionUnevaluated,
727 /// Evaluate as a potential constant expression. Keep going if we hit a
728 /// construct that we can't evaluate yet (because we don't yet know the
729 /// value of something) but stop if we hit something that could never be
730 /// a constant expression. Some expressions can be retried in the
731 /// optimizer if we don't constant fold them here, but in an unevaluated
732 /// context we try to fold them immediately since the optimizer never
733 /// gets a chance to look at it.
734 EM_PotentialConstantExpressionUnevaluated,
736 /// Evaluate as a constant expression. In certain scenarios, if:
737 /// - we find a MemberExpr with a base that can't be evaluated, or
738 /// - we find a variable initialized with a call to a function that has
739 /// the alloc_size attribute on it
740 /// then we may consider evaluation to have succeeded.
742 /// In either case, the LValue returned shall have an invalid base; in the
743 /// former, the base will be the invalid MemberExpr, in the latter, the
744 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
749 /// Are we checking whether the expression is a potential constant
751 bool checkingPotentialConstantExpression() const {
752 return EvalMode == EM_PotentialConstantExpression ||
753 EvalMode == EM_PotentialConstantExpressionUnevaluated;
756 /// Are we checking an expression for overflow?
757 // FIXME: We should check for any kind of undefined or suspicious behavior
758 // in such constructs, not just overflow.
759 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
761 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
762 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
763 CallStackDepth(0), NextCallIndex(1),
764 StepsLeft(getLangOpts().ConstexprStepLimit),
765 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
766 EvaluatingDecl((const ValueDecl *)nullptr),
767 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
768 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
771 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
772 EvaluatingDecl = Base;
773 EvaluatingDeclValue = &Value;
774 EvaluatingConstructors.insert({Base, {0, 0}});
777 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
779 bool CheckCallLimit(SourceLocation Loc) {
780 // Don't perform any constexpr calls (other than the call we're checking)
781 // when checking a potential constant expression.
782 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
784 if (NextCallIndex == 0) {
785 // NextCallIndex has wrapped around.
786 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
789 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
791 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
792 << getLangOpts().ConstexprCallDepth;
796 CallStackFrame *getCallFrame(unsigned CallIndex) {
797 assert(CallIndex && "no call index in getCallFrame");
798 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
799 // be null in this loop.
800 CallStackFrame *Frame = CurrentCall;
801 while (Frame->Index > CallIndex)
802 Frame = Frame->Caller;
803 return (Frame->Index == CallIndex) ? Frame : nullptr;
806 bool nextStep(const Stmt *S) {
808 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
816 /// Add a diagnostic to the diagnostics list.
817 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
818 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
819 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
820 return EvalStatus.Diag->back().second;
823 /// Add notes containing a call stack to the current point of evaluation.
824 void addCallStack(unsigned Limit);
827 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
828 unsigned ExtraNotes, bool IsCCEDiag) {
830 if (EvalStatus.Diag) {
831 // If we have a prior diagnostic, it will be noting that the expression
832 // isn't a constant expression. This diagnostic is more important,
833 // unless we require this evaluation to produce a constant expression.
835 // FIXME: We might want to show both diagnostics to the user in
836 // EM_ConstantFold mode.
837 if (!EvalStatus.Diag->empty()) {
839 case EM_ConstantFold:
840 case EM_IgnoreSideEffects:
841 case EM_EvaluateForOverflow:
842 if (!HasFoldFailureDiagnostic)
844 // We've already failed to fold something. Keep that diagnostic.
846 case EM_ConstantExpression:
847 case EM_PotentialConstantExpression:
848 case EM_ConstantExpressionUnevaluated:
849 case EM_PotentialConstantExpressionUnevaluated:
851 HasActiveDiagnostic = false;
852 return OptionalDiagnostic();
856 unsigned CallStackNotes = CallStackDepth - 1;
857 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
859 CallStackNotes = std::min(CallStackNotes, Limit + 1);
860 if (checkingPotentialConstantExpression())
863 HasActiveDiagnostic = true;
864 HasFoldFailureDiagnostic = !IsCCEDiag;
865 EvalStatus.Diag->clear();
866 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
867 addDiag(Loc, DiagId);
868 if (!checkingPotentialConstantExpression())
870 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
872 HasActiveDiagnostic = false;
873 return OptionalDiagnostic();
876 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
878 FFDiag(SourceLocation Loc,
879 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
880 unsigned ExtraNotes = 0) {
881 return Diag(Loc, DiagId, ExtraNotes, false);
884 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
885 = diag::note_invalid_subexpr_in_const_expr,
886 unsigned ExtraNotes = 0) {
888 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
889 HasActiveDiagnostic = false;
890 return OptionalDiagnostic();
893 /// Diagnose that the evaluation does not produce a C++11 core constant
896 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
897 /// EM_PotentialConstantExpression mode and we produce one of these.
898 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
899 = diag::note_invalid_subexpr_in_const_expr,
900 unsigned ExtraNotes = 0) {
901 // Don't override a previous diagnostic. Don't bother collecting
902 // diagnostics if we're evaluating for overflow.
903 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
904 HasActiveDiagnostic = false;
905 return OptionalDiagnostic();
907 return Diag(Loc, DiagId, ExtraNotes, true);
909 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
910 = diag::note_invalid_subexpr_in_const_expr,
911 unsigned ExtraNotes = 0) {
912 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
914 /// Add a note to a prior diagnostic.
915 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
916 if (!HasActiveDiagnostic)
917 return OptionalDiagnostic();
918 return OptionalDiagnostic(&addDiag(Loc, DiagId));
921 /// Add a stack of notes to a prior diagnostic.
922 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
923 if (HasActiveDiagnostic) {
924 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
925 Diags.begin(), Diags.end());
929 /// Should we continue evaluation after encountering a side-effect that we
931 bool keepEvaluatingAfterSideEffect() {
933 case EM_PotentialConstantExpression:
934 case EM_PotentialConstantExpressionUnevaluated:
935 case EM_EvaluateForOverflow:
936 case EM_IgnoreSideEffects:
939 case EM_ConstantExpression:
940 case EM_ConstantExpressionUnevaluated:
941 case EM_ConstantFold:
945 llvm_unreachable("Missed EvalMode case");
948 /// Note that we have had a side-effect, and determine whether we should
950 bool noteSideEffect() {
951 EvalStatus.HasSideEffects = true;
952 return keepEvaluatingAfterSideEffect();
955 /// Should we continue evaluation after encountering undefined behavior?
956 bool keepEvaluatingAfterUndefinedBehavior() {
958 case EM_EvaluateForOverflow:
959 case EM_IgnoreSideEffects:
960 case EM_ConstantFold:
964 case EM_PotentialConstantExpression:
965 case EM_PotentialConstantExpressionUnevaluated:
966 case EM_ConstantExpression:
967 case EM_ConstantExpressionUnevaluated:
970 llvm_unreachable("Missed EvalMode case");
973 /// Note that we hit something that was technically undefined behavior, but
974 /// that we can evaluate past it (such as signed overflow or floating-point
975 /// division by zero.)
976 bool noteUndefinedBehavior() {
977 EvalStatus.HasUndefinedBehavior = true;
978 return keepEvaluatingAfterUndefinedBehavior();
981 /// Should we continue evaluation as much as possible after encountering a
982 /// construct which can't be reduced to a value?
983 bool keepEvaluatingAfterFailure() {
988 case EM_PotentialConstantExpression:
989 case EM_PotentialConstantExpressionUnevaluated:
990 case EM_EvaluateForOverflow:
993 case EM_ConstantExpression:
994 case EM_ConstantExpressionUnevaluated:
995 case EM_ConstantFold:
996 case EM_IgnoreSideEffects:
1000 llvm_unreachable("Missed EvalMode case");
1003 /// Notes that we failed to evaluate an expression that other expressions
1004 /// directly depend on, and determine if we should keep evaluating. This
1005 /// should only be called if we actually intend to keep evaluating.
1007 /// Call noteSideEffect() instead if we may be able to ignore the value that
1008 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1010 /// (Foo(), 1) // use noteSideEffect
1011 /// (Foo() || true) // use noteSideEffect
1012 /// Foo() + 1 // use noteFailure
1013 LLVM_NODISCARD bool noteFailure() {
1014 // Failure when evaluating some expression often means there is some
1015 // subexpression whose evaluation was skipped. Therefore, (because we
1016 // don't track whether we skipped an expression when unwinding after an
1017 // evaluation failure) every evaluation failure that bubbles up from a
1018 // subexpression implies that a side-effect has potentially happened. We
1019 // skip setting the HasSideEffects flag to true until we decide to
1020 // continue evaluating after that point, which happens here.
1021 bool KeepGoing = keepEvaluatingAfterFailure();
1022 EvalStatus.HasSideEffects |= KeepGoing;
1026 class ArrayInitLoopIndex {
1028 uint64_t OuterIndex;
1031 ArrayInitLoopIndex(EvalInfo &Info)
1032 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1033 Info.ArrayInitIndex = 0;
1035 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1037 operator uint64_t&() { return Info.ArrayInitIndex; }
1041 /// Object used to treat all foldable expressions as constant expressions.
1042 struct FoldConstant {
1045 bool HadNoPriorDiags;
1046 EvalInfo::EvaluationMode OldMode;
1048 explicit FoldConstant(EvalInfo &Info, bool Enabled)
1051 HadNoPriorDiags(Info.EvalStatus.Diag &&
1052 Info.EvalStatus.Diag->empty() &&
1053 !Info.EvalStatus.HasSideEffects),
1054 OldMode(Info.EvalMode) {
1056 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1057 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1058 Info.EvalMode = EvalInfo::EM_ConstantFold;
1060 void keepDiagnostics() { Enabled = false; }
1062 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1063 !Info.EvalStatus.HasSideEffects)
1064 Info.EvalStatus.Diag->clear();
1065 Info.EvalMode = OldMode;
1069 /// RAII object used to treat the current evaluation as the correct pointer
1070 /// offset fold for the current EvalMode
1071 struct FoldOffsetRAII {
1073 EvalInfo::EvaluationMode OldMode;
1074 explicit FoldOffsetRAII(EvalInfo &Info)
1075 : Info(Info), OldMode(Info.EvalMode) {
1076 if (!Info.checkingPotentialConstantExpression())
1077 Info.EvalMode = EvalInfo::EM_OffsetFold;
1080 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1083 /// RAII object used to optionally suppress diagnostics and side-effects from
1084 /// a speculative evaluation.
1085 class SpeculativeEvaluationRAII {
1086 EvalInfo *Info = nullptr;
1087 Expr::EvalStatus OldStatus;
1088 bool OldIsSpeculativelyEvaluating;
1090 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1092 OldStatus = Other.OldStatus;
1093 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1094 Other.Info = nullptr;
1097 void maybeRestoreState() {
1101 Info->EvalStatus = OldStatus;
1102 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1106 SpeculativeEvaluationRAII() = default;
1108 SpeculativeEvaluationRAII(
1109 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1110 : Info(&Info), OldStatus(Info.EvalStatus),
1111 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1112 Info.EvalStatus.Diag = NewDiag;
1113 Info.IsSpeculativelyEvaluating = true;
1116 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1117 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1118 moveFromAndCancel(std::move(Other));
1121 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1122 maybeRestoreState();
1123 moveFromAndCancel(std::move(Other));
1127 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1130 /// RAII object wrapping a full-expression or block scope, and handling
1131 /// the ending of the lifetime of temporaries created within it.
1132 template<bool IsFullExpression>
1135 unsigned OldStackSize;
1137 ScopeRAII(EvalInfo &Info)
1138 : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1139 // Push a new temporary version. This is needed to distinguish between
1140 // temporaries created in different iterations of a loop.
1141 Info.CurrentCall->pushTempVersion();
1144 // Body moved to a static method to encourage the compiler to inline away
1145 // instances of this class.
1146 cleanup(Info, OldStackSize);
1147 Info.CurrentCall->popTempVersion();
1150 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1151 unsigned NewEnd = OldStackSize;
1152 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1154 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1155 // Full-expression cleanup of a lifetime-extended temporary: nothing
1156 // to do, just move this cleanup to the right place in the stack.
1157 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1160 // End the lifetime of the object.
1161 Info.CleanupStack[I].endLifetime();
1164 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1165 Info.CleanupStack.end());
1168 typedef ScopeRAII<false> BlockScopeRAII;
1169 typedef ScopeRAII<true> FullExpressionRAII;
1172 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1173 CheckSubobjectKind CSK) {
1176 if (isOnePastTheEnd()) {
1177 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1182 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1183 // must actually be at least one array element; even a VLA cannot have a
1184 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1188 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1190 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1191 // Do not set the designator as invalid: we can represent this situation,
1192 // and correct handling of __builtin_object_size requires us to do so.
1195 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1198 // If we're complaining, we must be able to statically determine the size of
1199 // the most derived array.
1200 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1201 Info.CCEDiag(E, diag::note_constexpr_array_index)
1203 << static_cast<unsigned>(getMostDerivedArraySize());
1205 Info.CCEDiag(E, diag::note_constexpr_array_index)
1206 << N << /*non-array*/ 1;
1210 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1211 const FunctionDecl *Callee, const LValue *This,
1213 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1214 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1215 Info.CurrentCall = this;
1216 ++Info.CallStackDepth;
1219 CallStackFrame::~CallStackFrame() {
1220 assert(Info.CurrentCall == this && "calls retired out of order");
1221 --Info.CallStackDepth;
1222 Info.CurrentCall = Caller;
1225 APValue &CallStackFrame::createTemporary(const void *Key,
1226 bool IsLifetimeExtended) {
1227 unsigned Version = Info.CurrentCall->getTempVersion();
1228 APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1229 assert(Result.isUninit() && "temporary created multiple times");
1230 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1234 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1236 void EvalInfo::addCallStack(unsigned Limit) {
1237 // Determine which calls to skip, if any.
1238 unsigned ActiveCalls = CallStackDepth - 1;
1239 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1240 if (Limit && Limit < ActiveCalls) {
1241 SkipStart = Limit / 2 + Limit % 2;
1242 SkipEnd = ActiveCalls - Limit / 2;
1245 // Walk the call stack and add the diagnostics.
1246 unsigned CallIdx = 0;
1247 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1248 Frame = Frame->Caller, ++CallIdx) {
1250 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1251 if (CallIdx == SkipStart) {
1252 // Note that we're skipping calls.
1253 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1254 << unsigned(ActiveCalls - Limit);
1259 // Use a different note for an inheriting constructor, because from the
1260 // user's perspective it's not really a function at all.
1261 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1262 if (CD->isInheritingConstructor()) {
1263 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1269 SmallVector<char, 128> Buffer;
1270 llvm::raw_svector_ostream Out(Buffer);
1271 describeCall(Frame, Out);
1272 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1277 struct ComplexValue {
1282 APSInt IntReal, IntImag;
1283 APFloat FloatReal, FloatImag;
1285 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1287 void makeComplexFloat() { IsInt = false; }
1288 bool isComplexFloat() const { return !IsInt; }
1289 APFloat &getComplexFloatReal() { return FloatReal; }
1290 APFloat &getComplexFloatImag() { return FloatImag; }
1292 void makeComplexInt() { IsInt = true; }
1293 bool isComplexInt() const { return IsInt; }
1294 APSInt &getComplexIntReal() { return IntReal; }
1295 APSInt &getComplexIntImag() { return IntImag; }
1297 void moveInto(APValue &v) const {
1298 if (isComplexFloat())
1299 v = APValue(FloatReal, FloatImag);
1301 v = APValue(IntReal, IntImag);
1303 void setFrom(const APValue &v) {
1304 assert(v.isComplexFloat() || v.isComplexInt());
1305 if (v.isComplexFloat()) {
1307 FloatReal = v.getComplexFloatReal();
1308 FloatImag = v.getComplexFloatImag();
1311 IntReal = v.getComplexIntReal();
1312 IntImag = v.getComplexIntImag();
1318 APValue::LValueBase Base;
1320 SubobjectDesignator Designator;
1322 bool InvalidBase : 1;
1324 const APValue::LValueBase getLValueBase() const { return Base; }
1325 CharUnits &getLValueOffset() { return Offset; }
1326 const CharUnits &getLValueOffset() const { return Offset; }
1327 SubobjectDesignator &getLValueDesignator() { return Designator; }
1328 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1329 bool isNullPointer() const { return IsNullPtr;}
1331 unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1332 unsigned getLValueVersion() const { return Base.getVersion(); }
1334 void moveInto(APValue &V) const {
1335 if (Designator.Invalid)
1336 V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1338 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1339 V = APValue(Base, Offset, Designator.Entries,
1340 Designator.IsOnePastTheEnd, IsNullPtr);
1343 void setFrom(ASTContext &Ctx, const APValue &V) {
1344 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1345 Base = V.getLValueBase();
1346 Offset = V.getLValueOffset();
1347 InvalidBase = false;
1348 Designator = SubobjectDesignator(Ctx, V);
1349 IsNullPtr = V.isNullPointer();
1352 void set(APValue::LValueBase B, bool BInvalid = false) {
1354 // We only allow a few types of invalid bases. Enforce that here.
1356 const auto *E = B.get<const Expr *>();
1357 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1358 "Unexpected type of invalid base");
1363 Offset = CharUnits::fromQuantity(0);
1364 InvalidBase = BInvalid;
1365 Designator = SubobjectDesignator(getType(B));
1369 void setNull(QualType PointerTy, uint64_t TargetVal) {
1370 Base = (Expr *)nullptr;
1371 Offset = CharUnits::fromQuantity(TargetVal);
1372 InvalidBase = false;
1373 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1377 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1381 // Check that this LValue is not based on a null pointer. If it is, produce
1382 // a diagnostic and mark the designator as invalid.
1383 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1384 CheckSubobjectKind CSK) {
1385 if (Designator.Invalid)
1388 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1390 Designator.setInvalid();
1396 // Check this LValue refers to an object. If not, set the designator to be
1397 // invalid and emit a diagnostic.
1398 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1399 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1400 Designator.checkSubobject(Info, E, CSK);
1403 void addDecl(EvalInfo &Info, const Expr *E,
1404 const Decl *D, bool Virtual = false) {
1405 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1406 Designator.addDeclUnchecked(D, Virtual);
1408 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1409 if (!Designator.Entries.empty()) {
1410 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1411 Designator.setInvalid();
1414 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1415 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1416 Designator.FirstEntryIsAnUnsizedArray = true;
1417 Designator.addUnsizedArrayUnchecked(ElemTy);
1420 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1421 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1422 Designator.addArrayUnchecked(CAT);
1424 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1425 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1426 Designator.addComplexUnchecked(EltTy, Imag);
1428 void clearIsNullPointer() {
1431 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1432 const APSInt &Index, CharUnits ElementSize) {
1433 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1434 // but we're not required to diagnose it and it's valid in C++.)
1438 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1439 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1441 uint64_t Offset64 = Offset.getQuantity();
1442 uint64_t ElemSize64 = ElementSize.getQuantity();
1443 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1444 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1446 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1447 Designator.adjustIndex(Info, E, Index);
1448 clearIsNullPointer();
1450 void adjustOffset(CharUnits N) {
1452 if (N.getQuantity())
1453 clearIsNullPointer();
1459 explicit MemberPtr(const ValueDecl *Decl) :
1460 DeclAndIsDerivedMember(Decl, false), Path() {}
1462 /// The member or (direct or indirect) field referred to by this member
1463 /// pointer, or 0 if this is a null member pointer.
1464 const ValueDecl *getDecl() const {
1465 return DeclAndIsDerivedMember.getPointer();
1467 /// Is this actually a member of some type derived from the relevant class?
1468 bool isDerivedMember() const {
1469 return DeclAndIsDerivedMember.getInt();
1471 /// Get the class which the declaration actually lives in.
1472 const CXXRecordDecl *getContainingRecord() const {
1473 return cast<CXXRecordDecl>(
1474 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1477 void moveInto(APValue &V) const {
1478 V = APValue(getDecl(), isDerivedMember(), Path);
1480 void setFrom(const APValue &V) {
1481 assert(V.isMemberPointer());
1482 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1483 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1485 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1486 Path.insert(Path.end(), P.begin(), P.end());
1489 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1490 /// whether the member is a member of some class derived from the class type
1491 /// of the member pointer.
1492 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1493 /// Path - The path of base/derived classes from the member declaration's
1494 /// class (exclusive) to the class type of the member pointer (inclusive).
1495 SmallVector<const CXXRecordDecl*, 4> Path;
1497 /// Perform a cast towards the class of the Decl (either up or down the
1499 bool castBack(const CXXRecordDecl *Class) {
1500 assert(!Path.empty());
1501 const CXXRecordDecl *Expected;
1502 if (Path.size() >= 2)
1503 Expected = Path[Path.size() - 2];
1505 Expected = getContainingRecord();
1506 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1507 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1508 // if B does not contain the original member and is not a base or
1509 // derived class of the class containing the original member, the result
1510 // of the cast is undefined.
1511 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1512 // (D::*). We consider that to be a language defect.
1518 /// Perform a base-to-derived member pointer cast.
1519 bool castToDerived(const CXXRecordDecl *Derived) {
1522 if (!isDerivedMember()) {
1523 Path.push_back(Derived);
1526 if (!castBack(Derived))
1529 DeclAndIsDerivedMember.setInt(false);
1532 /// Perform a derived-to-base member pointer cast.
1533 bool castToBase(const CXXRecordDecl *Base) {
1537 DeclAndIsDerivedMember.setInt(true);
1538 if (isDerivedMember()) {
1539 Path.push_back(Base);
1542 return castBack(Base);
1546 /// Compare two member pointers, which are assumed to be of the same type.
1547 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1548 if (!LHS.getDecl() || !RHS.getDecl())
1549 return !LHS.getDecl() && !RHS.getDecl();
1550 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1552 return LHS.Path == RHS.Path;
1556 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1557 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1558 const LValue &This, const Expr *E,
1559 bool AllowNonLiteralTypes = false);
1560 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1561 bool InvalidBaseOK = false);
1562 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1563 bool InvalidBaseOK = false);
1564 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1566 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1567 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1568 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1570 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1571 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1572 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1574 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1576 //===----------------------------------------------------------------------===//
1578 //===----------------------------------------------------------------------===//
1580 /// A helper function to create a temporary and set an LValue.
1581 template <class KeyTy>
1582 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1583 LValue &LV, CallStackFrame &Frame) {
1584 LV.set({Key, Frame.Info.CurrentCall->Index,
1585 Frame.Info.CurrentCall->getTempVersion()});
1586 return Frame.createTemporary(Key, IsLifetimeExtended);
1589 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1590 /// preserving its value (by extending by up to one bit as needed).
1591 static void negateAsSigned(APSInt &Int) {
1592 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1593 Int = Int.extend(Int.getBitWidth() + 1);
1594 Int.setIsSigned(true);
1599 /// Produce a string describing the given constexpr call.
1600 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1601 unsigned ArgIndex = 0;
1602 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1603 !isa<CXXConstructorDecl>(Frame->Callee) &&
1604 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1607 Out << *Frame->Callee << '(';
1609 if (Frame->This && IsMemberCall) {
1611 Frame->This->moveInto(Val);
1612 Val.printPretty(Out, Frame->Info.Ctx,
1613 Frame->This->Designator.MostDerivedType);
1614 // FIXME: Add parens around Val if needed.
1615 Out << "->" << *Frame->Callee << '(';
1616 IsMemberCall = false;
1619 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1620 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1621 if (ArgIndex > (unsigned)IsMemberCall)
1624 const ParmVarDecl *Param = *I;
1625 const APValue &Arg = Frame->Arguments[ArgIndex];
1626 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1628 if (ArgIndex == 0 && IsMemberCall)
1629 Out << "->" << *Frame->Callee << '(';
1635 /// Evaluate an expression to see if it had side-effects, and discard its
1637 /// \return \c true if the caller should keep evaluating.
1638 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1640 if (!Evaluate(Scratch, Info, E))
1641 // We don't need the value, but we might have skipped a side effect here.
1642 return Info.noteSideEffect();
1646 /// Should this call expression be treated as a string literal?
1647 static bool IsStringLiteralCall(const CallExpr *E) {
1648 unsigned Builtin = E->getBuiltinCallee();
1649 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1650 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1653 static bool IsGlobalLValue(APValue::LValueBase B) {
1654 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1655 // constant expression of pointer type that evaluates to...
1657 // ... a null pointer value, or a prvalue core constant expression of type
1659 if (!B) return true;
1661 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1662 // ... the address of an object with static storage duration,
1663 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1664 return VD->hasGlobalStorage();
1665 // ... the address of a function,
1666 return isa<FunctionDecl>(D);
1669 const Expr *E = B.get<const Expr*>();
1670 switch (E->getStmtClass()) {
1673 case Expr::CompoundLiteralExprClass: {
1674 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1675 return CLE->isFileScope() && CLE->isLValue();
1677 case Expr::MaterializeTemporaryExprClass:
1678 // A materialized temporary might have been lifetime-extended to static
1679 // storage duration.
1680 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1681 // A string literal has static storage duration.
1682 case Expr::StringLiteralClass:
1683 case Expr::PredefinedExprClass:
1684 case Expr::ObjCStringLiteralClass:
1685 case Expr::ObjCEncodeExprClass:
1686 case Expr::CXXTypeidExprClass:
1687 case Expr::CXXUuidofExprClass:
1689 case Expr::CallExprClass:
1690 return IsStringLiteralCall(cast<CallExpr>(E));
1691 // For GCC compatibility, &&label has static storage duration.
1692 case Expr::AddrLabelExprClass:
1694 // A Block literal expression may be used as the initialization value for
1695 // Block variables at global or local static scope.
1696 case Expr::BlockExprClass:
1697 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1698 case Expr::ImplicitValueInitExprClass:
1700 // We can never form an lvalue with an implicit value initialization as its
1701 // base through expression evaluation, so these only appear in one case: the
1702 // implicit variable declaration we invent when checking whether a constexpr
1703 // constructor can produce a constant expression. We must assume that such
1704 // an expression might be a global lvalue.
1709 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1710 assert(Base && "no location for a null lvalue");
1711 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1713 Info.Note(VD->getLocation(), diag::note_declared_at);
1715 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1716 diag::note_constexpr_temporary_here);
1719 /// Check that this reference or pointer core constant expression is a valid
1720 /// value for an address or reference constant expression. Return true if we
1721 /// can fold this expression, whether or not it's a constant expression.
1722 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1723 QualType Type, const LValue &LVal,
1724 Expr::ConstExprUsage Usage) {
1725 bool IsReferenceType = Type->isReferenceType();
1727 APValue::LValueBase Base = LVal.getLValueBase();
1728 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1730 // Check that the object is a global. Note that the fake 'this' object we
1731 // manufacture when checking potential constant expressions is conservatively
1732 // assumed to be global here.
1733 if (!IsGlobalLValue(Base)) {
1734 if (Info.getLangOpts().CPlusPlus11) {
1735 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1736 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1737 << IsReferenceType << !Designator.Entries.empty()
1739 NoteLValueLocation(Info, Base);
1743 // Don't allow references to temporaries to escape.
1746 assert((Info.checkingPotentialConstantExpression() ||
1747 LVal.getLValueCallIndex() == 0) &&
1748 "have call index for global lvalue");
1750 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1751 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1752 // Check if this is a thread-local variable.
1753 if (Var->getTLSKind())
1756 // A dllimport variable never acts like a constant.
1757 if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1760 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1761 // __declspec(dllimport) must be handled very carefully:
1762 // We must never initialize an expression with the thunk in C++.
1763 // Doing otherwise would allow the same id-expression to yield
1764 // different addresses for the same function in different translation
1765 // units. However, this means that we must dynamically initialize the
1766 // expression with the contents of the import address table at runtime.
1768 // The C language has no notion of ODR; furthermore, it has no notion of
1769 // dynamic initialization. This means that we are permitted to
1770 // perform initialization with the address of the thunk.
1771 if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1772 FD->hasAttr<DLLImportAttr>())
1777 // Allow address constant expressions to be past-the-end pointers. This is
1778 // an extension: the standard requires them to point to an object.
1779 if (!IsReferenceType)
1782 // A reference constant expression must refer to an object.
1784 // FIXME: diagnostic
1789 // Does this refer one past the end of some object?
1790 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1791 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1792 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1793 << !Designator.Entries.empty() << !!VD << VD;
1794 NoteLValueLocation(Info, Base);
1800 /// Member pointers are constant expressions unless they point to a
1801 /// non-virtual dllimport member function.
1802 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1805 const APValue &Value,
1806 Expr::ConstExprUsage Usage) {
1807 const ValueDecl *Member = Value.getMemberPointerDecl();
1808 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1811 return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1812 !FD->hasAttr<DLLImportAttr>();
1815 /// Check that this core constant expression is of literal type, and if not,
1816 /// produce an appropriate diagnostic.
1817 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1818 const LValue *This = nullptr) {
1819 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1822 // C++1y: A constant initializer for an object o [...] may also invoke
1823 // constexpr constructors for o and its subobjects even if those objects
1824 // are of non-literal class types.
1826 // C++11 missed this detail for aggregates, so classes like this:
1827 // struct foo_t { union { int i; volatile int j; } u; };
1828 // are not (obviously) initializable like so:
1829 // __attribute__((__require_constant_initialization__))
1830 // static const foo_t x = {{0}};
1831 // because "i" is a subobject with non-literal initialization (due to the
1832 // volatile member of the union). See:
1833 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1834 // Therefore, we use the C++1y behavior.
1835 if (This && Info.EvaluatingDecl == This->getLValueBase())
1838 // Prvalue constant expressions must be of literal types.
1839 if (Info.getLangOpts().CPlusPlus11)
1840 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1843 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1847 /// Check that this core constant expression value is a valid value for a
1848 /// constant expression. If not, report an appropriate diagnostic. Does not
1849 /// check that the expression is of literal type.
1851 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1852 const APValue &Value,
1853 Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1854 if (Value.isUninit()) {
1855 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1860 // We allow _Atomic(T) to be initialized from anything that T can be
1861 // initialized from.
1862 if (const AtomicType *AT = Type->getAs<AtomicType>())
1863 Type = AT->getValueType();
1865 // Core issue 1454: For a literal constant expression of array or class type,
1866 // each subobject of its value shall have been initialized by a constant
1868 if (Value.isArray()) {
1869 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1870 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1871 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1872 Value.getArrayInitializedElt(I), Usage))
1875 if (!Value.hasArrayFiller())
1877 return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1880 if (Value.isUnion() && Value.getUnionField()) {
1881 return CheckConstantExpression(Info, DiagLoc,
1882 Value.getUnionField()->getType(),
1883 Value.getUnionValue(), Usage);
1885 if (Value.isStruct()) {
1886 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1887 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1888 unsigned BaseIndex = 0;
1889 for (const CXXBaseSpecifier &BS : CD->bases()) {
1890 if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1891 Value.getStructBase(BaseIndex), Usage))
1896 for (const auto *I : RD->fields()) {
1897 if (I->isUnnamedBitfield())
1900 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1901 Value.getStructField(I->getFieldIndex()),
1907 if (Value.isLValue()) {
1909 LVal.setFrom(Info.Ctx, Value);
1910 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
1913 if (Value.isMemberPointer())
1914 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
1916 // Everything else is fine.
1920 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1921 return LVal.Base.dyn_cast<const ValueDecl*>();
1924 static bool IsLiteralLValue(const LValue &Value) {
1925 if (Value.getLValueCallIndex())
1927 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1928 return E && !isa<MaterializeTemporaryExpr>(E);
1931 static bool IsWeakLValue(const LValue &Value) {
1932 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1933 return Decl && Decl->isWeak();
1936 static bool isZeroSized(const LValue &Value) {
1937 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1938 if (Decl && isa<VarDecl>(Decl)) {
1939 QualType Ty = Decl->getType();
1940 if (Ty->isArrayType())
1941 return Ty->isIncompleteType() ||
1942 Decl->getASTContext().getTypeSize(Ty) == 0;
1947 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1948 // A null base expression indicates a null pointer. These are always
1949 // evaluatable, and they are false unless the offset is zero.
1950 if (!Value.getLValueBase()) {
1951 Result = !Value.getLValueOffset().isZero();
1955 // We have a non-null base. These are generally known to be true, but if it's
1956 // a weak declaration it can be null at runtime.
1958 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1959 return !Decl || !Decl->isWeak();
1962 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1963 switch (Val.getKind()) {
1964 case APValue::Uninitialized:
1967 Result = Val.getInt().getBoolValue();
1969 case APValue::Float:
1970 Result = !Val.getFloat().isZero();
1972 case APValue::ComplexInt:
1973 Result = Val.getComplexIntReal().getBoolValue() ||
1974 Val.getComplexIntImag().getBoolValue();
1976 case APValue::ComplexFloat:
1977 Result = !Val.getComplexFloatReal().isZero() ||
1978 !Val.getComplexFloatImag().isZero();
1980 case APValue::LValue:
1981 return EvalPointerValueAsBool(Val, Result);
1982 case APValue::MemberPointer:
1983 Result = Val.getMemberPointerDecl();
1985 case APValue::Vector:
1986 case APValue::Array:
1987 case APValue::Struct:
1988 case APValue::Union:
1989 case APValue::AddrLabelDiff:
1993 llvm_unreachable("unknown APValue kind");
1996 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1998 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2000 if (!Evaluate(Val, Info, E))
2002 return HandleConversionToBool(Val, Result);
2005 template<typename T>
2006 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2007 const T &SrcValue, QualType DestType) {
2008 Info.CCEDiag(E, diag::note_constexpr_overflow)
2009 << SrcValue << DestType;
2010 return Info.noteUndefinedBehavior();
2013 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2014 QualType SrcType, const APFloat &Value,
2015 QualType DestType, APSInt &Result) {
2016 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2017 // Determine whether we are converting to unsigned or signed.
2018 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2020 Result = APSInt(DestWidth, !DestSigned);
2022 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2023 & APFloat::opInvalidOp)
2024 return HandleOverflow(Info, E, Value, DestType);
2028 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2029 QualType SrcType, QualType DestType,
2031 APFloat Value = Result;
2033 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2034 APFloat::rmNearestTiesToEven, &ignored)
2035 & APFloat::opOverflow)
2036 return HandleOverflow(Info, E, Value, DestType);
2040 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2041 QualType DestType, QualType SrcType,
2042 const APSInt &Value) {
2043 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2044 APSInt Result = Value;
2045 // Figure out if this is a truncate, extend or noop cast.
2046 // If the input is signed, do a sign extend, noop, or truncate.
2047 Result = Result.extOrTrunc(DestWidth);
2048 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2052 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2053 QualType SrcType, const APSInt &Value,
2054 QualType DestType, APFloat &Result) {
2055 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2056 if (Result.convertFromAPInt(Value, Value.isSigned(),
2057 APFloat::rmNearestTiesToEven)
2058 & APFloat::opOverflow)
2059 return HandleOverflow(Info, E, Value, DestType);
2063 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2064 APValue &Value, const FieldDecl *FD) {
2065 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2067 if (!Value.isInt()) {
2068 // Trying to store a pointer-cast-to-integer into a bitfield.
2069 // FIXME: In this case, we should provide the diagnostic for casting
2070 // a pointer to an integer.
2071 assert(Value.isLValue() && "integral value neither int nor lvalue?");
2076 APSInt &Int = Value.getInt();
2077 unsigned OldBitWidth = Int.getBitWidth();
2078 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2079 if (NewBitWidth < OldBitWidth)
2080 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2084 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2087 if (!Evaluate(SVal, Info, E))
2090 Res = SVal.getInt();
2093 if (SVal.isFloat()) {
2094 Res = SVal.getFloat().bitcastToAPInt();
2097 if (SVal.isVector()) {
2098 QualType VecTy = E->getType();
2099 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2100 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2101 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2102 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2103 Res = llvm::APInt::getNullValue(VecSize);
2104 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2105 APValue &Elt = SVal.getVectorElt(i);
2106 llvm::APInt EltAsInt;
2108 EltAsInt = Elt.getInt();
2109 } else if (Elt.isFloat()) {
2110 EltAsInt = Elt.getFloat().bitcastToAPInt();
2112 // Don't try to handle vectors of anything other than int or float
2113 // (not sure if it's possible to hit this case).
2114 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2117 unsigned BaseEltSize = EltAsInt.getBitWidth();
2119 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2121 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2125 // Give up if the input isn't an int, float, or vector. For example, we
2126 // reject "(v4i16)(intptr_t)&a".
2127 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2131 /// Perform the given integer operation, which is known to need at most BitWidth
2132 /// bits, and check for overflow in the original type (if that type was not an
2134 template<typename Operation>
2135 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2136 const APSInt &LHS, const APSInt &RHS,
2137 unsigned BitWidth, Operation Op,
2139 if (LHS.isUnsigned()) {
2140 Result = Op(LHS, RHS);
2144 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2145 Result = Value.trunc(LHS.getBitWidth());
2146 if (Result.extend(BitWidth) != Value) {
2147 if (Info.checkingForOverflow())
2148 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2149 diag::warn_integer_constant_overflow)
2150 << Result.toString(10) << E->getType();
2152 return HandleOverflow(Info, E, Value, E->getType());
2157 /// Perform the given binary integer operation.
2158 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2159 BinaryOperatorKind Opcode, APSInt RHS,
2166 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2167 std::multiplies<APSInt>(), Result);
2169 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2170 std::plus<APSInt>(), Result);
2172 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2173 std::minus<APSInt>(), Result);
2174 case BO_And: Result = LHS & RHS; return true;
2175 case BO_Xor: Result = LHS ^ RHS; return true;
2176 case BO_Or: Result = LHS | RHS; return true;
2180 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2183 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2184 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2185 // this operation and gives the two's complement result.
2186 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2187 LHS.isSigned() && LHS.isMinSignedValue())
2188 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2192 if (Info.getLangOpts().OpenCL)
2193 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2194 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2195 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2197 else if (RHS.isSigned() && RHS.isNegative()) {
2198 // During constant-folding, a negative shift is an opposite shift. Such
2199 // a shift is not a constant expression.
2200 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2205 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2206 // the shifted type.
2207 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2209 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2210 << RHS << E->getType() << LHS.getBitWidth();
2211 } else if (LHS.isSigned()) {
2212 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2213 // operand, and must not overflow the corresponding unsigned type.
2214 if (LHS.isNegative())
2215 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2216 else if (LHS.countLeadingZeros() < SA)
2217 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2223 if (Info.getLangOpts().OpenCL)
2224 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2225 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2226 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2228 else if (RHS.isSigned() && RHS.isNegative()) {
2229 // During constant-folding, a negative shift is an opposite shift. Such a
2230 // shift is not a constant expression.
2231 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2236 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2238 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2240 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2241 << RHS << E->getType() << LHS.getBitWidth();
2246 case BO_LT: Result = LHS < RHS; return true;
2247 case BO_GT: Result = LHS > RHS; return true;
2248 case BO_LE: Result = LHS <= RHS; return true;
2249 case BO_GE: Result = LHS >= RHS; return true;
2250 case BO_EQ: Result = LHS == RHS; return true;
2251 case BO_NE: Result = LHS != RHS; return true;
2253 llvm_unreachable("BO_Cmp should be handled elsewhere");
2257 /// Perform the given binary floating-point operation, in-place, on LHS.
2258 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2259 APFloat &LHS, BinaryOperatorKind Opcode,
2260 const APFloat &RHS) {
2266 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2269 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2272 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2275 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2279 if (LHS.isInfinity() || LHS.isNaN()) {
2280 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2281 return Info.noteUndefinedBehavior();
2286 /// Cast an lvalue referring to a base subobject to a derived class, by
2287 /// truncating the lvalue's path to the given length.
2288 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2289 const RecordDecl *TruncatedType,
2290 unsigned TruncatedElements) {
2291 SubobjectDesignator &D = Result.Designator;
2293 // Check we actually point to a derived class object.
2294 if (TruncatedElements == D.Entries.size())
2296 assert(TruncatedElements >= D.MostDerivedPathLength &&
2297 "not casting to a derived class");
2298 if (!Result.checkSubobject(Info, E, CSK_Derived))
2301 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2302 const RecordDecl *RD = TruncatedType;
2303 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2304 if (RD->isInvalidDecl()) return false;
2305 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2306 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2307 if (isVirtualBaseClass(D.Entries[I]))
2308 Result.Offset -= Layout.getVBaseClassOffset(Base);
2310 Result.Offset -= Layout.getBaseClassOffset(Base);
2313 D.Entries.resize(TruncatedElements);
2317 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2318 const CXXRecordDecl *Derived,
2319 const CXXRecordDecl *Base,
2320 const ASTRecordLayout *RL = nullptr) {
2322 if (Derived->isInvalidDecl()) return false;
2323 RL = &Info.Ctx.getASTRecordLayout(Derived);
2326 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2327 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2331 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2332 const CXXRecordDecl *DerivedDecl,
2333 const CXXBaseSpecifier *Base) {
2334 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2336 if (!Base->isVirtual())
2337 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2339 SubobjectDesignator &D = Obj.Designator;
2343 // Extract most-derived object and corresponding type.
2344 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2345 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2348 // Find the virtual base class.
2349 if (DerivedDecl->isInvalidDecl()) return false;
2350 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2351 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2352 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2356 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2357 QualType Type, LValue &Result) {
2358 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2359 PathE = E->path_end();
2360 PathI != PathE; ++PathI) {
2361 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2364 Type = (*PathI)->getType();
2369 /// Update LVal to refer to the given field, which must be a member of the type
2370 /// currently described by LVal.
2371 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2372 const FieldDecl *FD,
2373 const ASTRecordLayout *RL = nullptr) {
2375 if (FD->getParent()->isInvalidDecl()) return false;
2376 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2379 unsigned I = FD->getFieldIndex();
2380 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2381 LVal.addDecl(Info, E, FD);
2385 /// Update LVal to refer to the given indirect field.
2386 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2388 const IndirectFieldDecl *IFD) {
2389 for (const auto *C : IFD->chain())
2390 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2395 /// Get the size of the given type in char units.
2396 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2397 QualType Type, CharUnits &Size) {
2398 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2400 if (Type->isVoidType() || Type->isFunctionType()) {
2401 Size = CharUnits::One();
2405 if (Type->isDependentType()) {
2410 if (!Type->isConstantSizeType()) {
2411 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2412 // FIXME: Better diagnostic.
2417 Size = Info.Ctx.getTypeSizeInChars(Type);
2421 /// Update a pointer value to model pointer arithmetic.
2422 /// \param Info - Information about the ongoing evaluation.
2423 /// \param E - The expression being evaluated, for diagnostic purposes.
2424 /// \param LVal - The pointer value to be updated.
2425 /// \param EltTy - The pointee type represented by LVal.
2426 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2427 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2428 LValue &LVal, QualType EltTy,
2429 APSInt Adjustment) {
2430 CharUnits SizeOfPointee;
2431 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2434 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2438 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2439 LValue &LVal, QualType EltTy,
2440 int64_t Adjustment) {
2441 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2442 APSInt::get(Adjustment));
2445 /// Update an lvalue to refer to a component of a complex number.
2446 /// \param Info - Information about the ongoing evaluation.
2447 /// \param LVal - The lvalue to be updated.
2448 /// \param EltTy - The complex number's component type.
2449 /// \param Imag - False for the real component, true for the imaginary.
2450 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2451 LValue &LVal, QualType EltTy,
2454 CharUnits SizeOfComponent;
2455 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2457 LVal.Offset += SizeOfComponent;
2459 LVal.addComplex(Info, E, EltTy, Imag);
2463 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2464 QualType Type, const LValue &LVal,
2467 /// Try to evaluate the initializer for a variable declaration.
2469 /// \param Info Information about the ongoing evaluation.
2470 /// \param E An expression to be used when printing diagnostics.
2471 /// \param VD The variable whose initializer should be obtained.
2472 /// \param Frame The frame in which the variable was created. Must be null
2473 /// if this variable is not local to the evaluation.
2474 /// \param Result Filled in with a pointer to the value of the variable.
2475 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2476 const VarDecl *VD, CallStackFrame *Frame,
2477 APValue *&Result, const LValue *LVal) {
2479 // If this is a parameter to an active constexpr function call, perform
2480 // argument substitution.
2481 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2482 // Assume arguments of a potential constant expression are unknown
2483 // constant expressions.
2484 if (Info.checkingPotentialConstantExpression())
2486 if (!Frame || !Frame->Arguments) {
2487 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2490 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2494 // If this is a local variable, dig out its value.
2496 Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2497 : Frame->getCurrentTemporary(VD);
2499 // Assume variables referenced within a lambda's call operator that were
2500 // not declared within the call operator are captures and during checking
2501 // of a potential constant expression, assume they are unknown constant
2503 assert(isLambdaCallOperator(Frame->Callee) &&
2504 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2505 "missing value for local variable");
2506 if (Info.checkingPotentialConstantExpression())
2508 // FIXME: implement capture evaluation during constant expr evaluation.
2509 Info.FFDiag(E->getLocStart(),
2510 diag::note_unimplemented_constexpr_lambda_feature_ast)
2511 << "captures not currently allowed";
2517 // Dig out the initializer, and use the declaration which it's attached to.
2518 const Expr *Init = VD->getAnyInitializer(VD);
2519 if (!Init || Init->isValueDependent()) {
2520 // If we're checking a potential constant expression, the variable could be
2521 // initialized later.
2522 if (!Info.checkingPotentialConstantExpression())
2523 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2527 // If we're currently evaluating the initializer of this declaration, use that
2529 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2530 Result = Info.EvaluatingDeclValue;
2534 // Never evaluate the initializer of a weak variable. We can't be sure that
2535 // this is the definition which will be used.
2537 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2541 // Check that we can fold the initializer. In C++, we will have already done
2542 // this in the cases where it matters for conformance.
2543 SmallVector<PartialDiagnosticAt, 8> Notes;
2544 if (!VD->evaluateValue(Notes)) {
2545 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2546 Notes.size() + 1) << VD;
2547 Info.Note(VD->getLocation(), diag::note_declared_at);
2548 Info.addNotes(Notes);
2550 } else if (!VD->checkInitIsICE()) {
2551 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2552 Notes.size() + 1) << VD;
2553 Info.Note(VD->getLocation(), diag::note_declared_at);
2554 Info.addNotes(Notes);
2557 Result = VD->getEvaluatedValue();
2561 static bool IsConstNonVolatile(QualType T) {
2562 Qualifiers Quals = T.getQualifiers();
2563 return Quals.hasConst() && !Quals.hasVolatile();
2566 /// Get the base index of the given base class within an APValue representing
2567 /// the given derived class.
2568 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2569 const CXXRecordDecl *Base) {
2570 Base = Base->getCanonicalDecl();
2572 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2573 E = Derived->bases_end(); I != E; ++I, ++Index) {
2574 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2578 llvm_unreachable("base class missing from derived class's bases list");
2581 /// Extract the value of a character from a string literal.
2582 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2584 // FIXME: Support MakeStringConstant
2585 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2587 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2588 assert(Index <= Str.size() && "Index too large");
2589 return APSInt::getUnsigned(Str.c_str()[Index]);
2592 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2593 Lit = PE->getFunctionName();
2594 const StringLiteral *S = cast<StringLiteral>(Lit);
2595 const ConstantArrayType *CAT =
2596 Info.Ctx.getAsConstantArrayType(S->getType());
2597 assert(CAT && "string literal isn't an array");
2598 QualType CharType = CAT->getElementType();
2599 assert(CharType->isIntegerType() && "unexpected character type");
2601 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2602 CharType->isUnsignedIntegerType());
2603 if (Index < S->getLength())
2604 Value = S->getCodeUnit(Index);
2608 // Expand a string literal into an array of characters.
2609 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2611 const StringLiteral *S = cast<StringLiteral>(Lit);
2612 const ConstantArrayType *CAT =
2613 Info.Ctx.getAsConstantArrayType(S->getType());
2614 assert(CAT && "string literal isn't an array");
2615 QualType CharType = CAT->getElementType();
2616 assert(CharType->isIntegerType() && "unexpected character type");
2618 unsigned Elts = CAT->getSize().getZExtValue();
2619 Result = APValue(APValue::UninitArray(),
2620 std::min(S->getLength(), Elts), Elts);
2621 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2622 CharType->isUnsignedIntegerType());
2623 if (Result.hasArrayFiller())
2624 Result.getArrayFiller() = APValue(Value);
2625 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2626 Value = S->getCodeUnit(I);
2627 Result.getArrayInitializedElt(I) = APValue(Value);
2631 // Expand an array so that it has more than Index filled elements.
2632 static void expandArray(APValue &Array, unsigned Index) {
2633 unsigned Size = Array.getArraySize();
2634 assert(Index < Size);
2636 // Always at least double the number of elements for which we store a value.
2637 unsigned OldElts = Array.getArrayInitializedElts();
2638 unsigned NewElts = std::max(Index+1, OldElts * 2);
2639 NewElts = std::min(Size, std::max(NewElts, 8u));
2641 // Copy the data across.
2642 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2643 for (unsigned I = 0; I != OldElts; ++I)
2644 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2645 for (unsigned I = OldElts; I != NewElts; ++I)
2646 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2647 if (NewValue.hasArrayFiller())
2648 NewValue.getArrayFiller() = Array.getArrayFiller();
2649 Array.swap(NewValue);
2652 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2653 /// conversion. If it's of class type, we may assume that the copy operation
2654 /// is trivial. Note that this is never true for a union type with fields
2655 /// (because the copy always "reads" the active member) and always true for
2656 /// a non-class type.
2657 static bool isReadByLvalueToRvalueConversion(QualType T) {
2658 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2659 if (!RD || (RD->isUnion() && !RD->field_empty()))
2664 for (auto *Field : RD->fields())
2665 if (isReadByLvalueToRvalueConversion(Field->getType()))
2668 for (auto &BaseSpec : RD->bases())
2669 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2675 /// Diagnose an attempt to read from any unreadable field within the specified
2676 /// type, which might be a class type.
2677 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2679 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2683 if (!RD->hasMutableFields())
2686 for (auto *Field : RD->fields()) {
2687 // If we're actually going to read this field in some way, then it can't
2688 // be mutable. If we're in a union, then assigning to a mutable field
2689 // (even an empty one) can change the active member, so that's not OK.
2690 // FIXME: Add core issue number for the union case.
2691 if (Field->isMutable() &&
2692 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2693 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2694 Info.Note(Field->getLocation(), diag::note_declared_at);
2698 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2702 for (auto &BaseSpec : RD->bases())
2703 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2706 // All mutable fields were empty, and thus not actually read.
2710 /// Kinds of access we can perform on an object, for diagnostics.
2719 /// A handle to a complete object (an object that is not a subobject of
2720 /// another object).
2721 struct CompleteObject {
2722 /// The value of the complete object.
2724 /// The type of the complete object.
2726 bool LifetimeStartedInEvaluation;
2728 CompleteObject() : Value(nullptr) {}
2729 CompleteObject(APValue *Value, QualType Type,
2730 bool LifetimeStartedInEvaluation)
2731 : Value(Value), Type(Type),
2732 LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2733 assert(Value && "missing value for complete object");
2736 explicit operator bool() const { return Value; }
2738 } // end anonymous namespace
2740 /// Find the designated sub-object of an rvalue.
2741 template<typename SubobjectHandler>
2742 typename SubobjectHandler::result_type
2743 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2744 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2746 // A diagnostic will have already been produced.
2747 return handler.failed();
2748 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2749 if (Info.getLangOpts().CPlusPlus11)
2750 Info.FFDiag(E, Sub.isOnePastTheEnd()
2751 ? diag::note_constexpr_access_past_end
2752 : diag::note_constexpr_access_unsized_array)
2753 << handler.AccessKind;
2756 return handler.failed();
2759 APValue *O = Obj.Value;
2760 QualType ObjType = Obj.Type;
2761 const FieldDecl *LastField = nullptr;
2762 const bool MayReadMutableMembers =
2763 Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2765 // Walk the designator's path to find the subobject.
2766 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2767 if (O->isUninit()) {
2768 if (!Info.checkingPotentialConstantExpression())
2769 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2770 return handler.failed();
2774 // If we are reading an object of class type, there may still be more
2775 // things we need to check: if there are any mutable subobjects, we
2776 // cannot perform this read. (This only happens when performing a trivial
2777 // copy or assignment.)
2778 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2779 !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2780 return handler.failed();
2782 if (!handler.found(*O, ObjType))
2785 // If we modified a bit-field, truncate it to the right width.
2786 if (handler.AccessKind != AK_Read &&
2787 LastField && LastField->isBitField() &&
2788 !truncateBitfieldValue(Info, E, *O, LastField))
2794 LastField = nullptr;
2795 if (ObjType->isArrayType()) {
2796 // Next subobject is an array element.
2797 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2798 assert(CAT && "vla in literal type?");
2799 uint64_t Index = Sub.Entries[I].ArrayIndex;
2800 if (CAT->getSize().ule(Index)) {
2801 // Note, it should not be possible to form a pointer with a valid
2802 // designator which points more than one past the end of the array.
2803 if (Info.getLangOpts().CPlusPlus11)
2804 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2805 << handler.AccessKind;
2808 return handler.failed();
2811 ObjType = CAT->getElementType();
2813 // An array object is represented as either an Array APValue or as an
2814 // LValue which refers to a string literal.
2815 if (O->isLValue()) {
2816 assert(I == N - 1 && "extracting subobject of character?");
2817 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2818 if (handler.AccessKind != AK_Read)
2819 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2822 return handler.foundString(*O, ObjType, Index);
2825 if (O->getArrayInitializedElts() > Index)
2826 O = &O->getArrayInitializedElt(Index);
2827 else if (handler.AccessKind != AK_Read) {
2828 expandArray(*O, Index);
2829 O = &O->getArrayInitializedElt(Index);
2831 O = &O->getArrayFiller();
2832 } else if (ObjType->isAnyComplexType()) {
2833 // Next subobject is a complex number.
2834 uint64_t Index = Sub.Entries[I].ArrayIndex;
2836 if (Info.getLangOpts().CPlusPlus11)
2837 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2838 << handler.AccessKind;
2841 return handler.failed();
2844 bool WasConstQualified = ObjType.isConstQualified();
2845 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2846 if (WasConstQualified)
2849 assert(I == N - 1 && "extracting subobject of scalar?");
2850 if (O->isComplexInt()) {
2851 return handler.found(Index ? O->getComplexIntImag()
2852 : O->getComplexIntReal(), ObjType);
2854 assert(O->isComplexFloat());
2855 return handler.found(Index ? O->getComplexFloatImag()
2856 : O->getComplexFloatReal(), ObjType);
2858 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2859 // In C++14 onwards, it is permitted to read a mutable member whose
2860 // lifetime began within the evaluation.
2861 // FIXME: Should we also allow this in C++11?
2862 if (Field->isMutable() && handler.AccessKind == AK_Read &&
2863 !MayReadMutableMembers) {
2864 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2866 Info.Note(Field->getLocation(), diag::note_declared_at);
2867 return handler.failed();
2870 // Next subobject is a class, struct or union field.
2871 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2872 if (RD->isUnion()) {
2873 const FieldDecl *UnionField = O->getUnionField();
2875 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2876 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2877 << handler.AccessKind << Field << !UnionField << UnionField;
2878 return handler.failed();
2880 O = &O->getUnionValue();
2882 O = &O->getStructField(Field->getFieldIndex());
2884 bool WasConstQualified = ObjType.isConstQualified();
2885 ObjType = Field->getType();
2886 if (WasConstQualified && !Field->isMutable())
2889 if (ObjType.isVolatileQualified()) {
2890 if (Info.getLangOpts().CPlusPlus) {
2891 // FIXME: Include a description of the path to the volatile subobject.
2892 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2893 << handler.AccessKind << 2 << Field;
2894 Info.Note(Field->getLocation(), diag::note_declared_at);
2896 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2898 return handler.failed();
2903 // Next subobject is a base class.
2904 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2905 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2906 O = &O->getStructBase(getBaseIndex(Derived, Base));
2908 bool WasConstQualified = ObjType.isConstQualified();
2909 ObjType = Info.Ctx.getRecordType(Base);
2910 if (WasConstQualified)
2917 struct ExtractSubobjectHandler {
2921 static const AccessKinds AccessKind = AK_Read;
2923 typedef bool result_type;
2924 bool failed() { return false; }
2925 bool found(APValue &Subobj, QualType SubobjType) {
2929 bool found(APSInt &Value, QualType SubobjType) {
2930 Result = APValue(Value);
2933 bool found(APFloat &Value, QualType SubobjType) {
2934 Result = APValue(Value);
2937 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2938 Result = APValue(extractStringLiteralCharacter(
2939 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2943 } // end anonymous namespace
2945 const AccessKinds ExtractSubobjectHandler::AccessKind;
2947 /// Extract the designated sub-object of an rvalue.
2948 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2949 const CompleteObject &Obj,
2950 const SubobjectDesignator &Sub,
2952 ExtractSubobjectHandler Handler = { Info, Result };
2953 return findSubobject(Info, E, Obj, Sub, Handler);
2957 struct ModifySubobjectHandler {
2962 typedef bool result_type;
2963 static const AccessKinds AccessKind = AK_Assign;
2965 bool checkConst(QualType QT) {
2966 // Assigning to a const object has undefined behavior.
2967 if (QT.isConstQualified()) {
2968 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2974 bool failed() { return false; }
2975 bool found(APValue &Subobj, QualType SubobjType) {
2976 if (!checkConst(SubobjType))
2978 // We've been given ownership of NewVal, so just swap it in.
2979 Subobj.swap(NewVal);
2982 bool found(APSInt &Value, QualType SubobjType) {
2983 if (!checkConst(SubobjType))
2985 if (!NewVal.isInt()) {
2986 // Maybe trying to write a cast pointer value into a complex?
2990 Value = NewVal.getInt();
2993 bool found(APFloat &Value, QualType SubobjType) {
2994 if (!checkConst(SubobjType))
2996 Value = NewVal.getFloat();
2999 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3000 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3003 } // end anonymous namespace
3005 const AccessKinds ModifySubobjectHandler::AccessKind;
3007 /// Update the designated sub-object of an rvalue to the given value.
3008 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3009 const CompleteObject &Obj,
3010 const SubobjectDesignator &Sub,
3012 ModifySubobjectHandler Handler = { Info, NewVal, E };
3013 return findSubobject(Info, E, Obj, Sub, Handler);
3016 /// Find the position where two subobject designators diverge, or equivalently
3017 /// the length of the common initial subsequence.
3018 static unsigned FindDesignatorMismatch(QualType ObjType,
3019 const SubobjectDesignator &A,
3020 const SubobjectDesignator &B,
3021 bool &WasArrayIndex) {
3022 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3023 for (/**/; I != N; ++I) {
3024 if (!ObjType.isNull() &&
3025 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3026 // Next subobject is an array element.
3027 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3028 WasArrayIndex = true;
3031 if (ObjType->isAnyComplexType())
3032 ObjType = ObjType->castAs<ComplexType>()->getElementType();
3034 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3036 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3037 WasArrayIndex = false;
3040 if (const FieldDecl *FD = getAsField(A.Entries[I]))
3041 // Next subobject is a field.
3042 ObjType = FD->getType();
3044 // Next subobject is a base class.
3045 ObjType = QualType();
3048 WasArrayIndex = false;
3052 /// Determine whether the given subobject designators refer to elements of the
3053 /// same array object.
3054 static bool AreElementsOfSameArray(QualType ObjType,
3055 const SubobjectDesignator &A,
3056 const SubobjectDesignator &B) {
3057 if (A.Entries.size() != B.Entries.size())
3060 bool IsArray = A.MostDerivedIsArrayElement;
3061 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3062 // A is a subobject of the array element.
3065 // If A (and B) designates an array element, the last entry will be the array
3066 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3067 // of length 1' case, and the entire path must match.
3069 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3070 return CommonLength >= A.Entries.size() - IsArray;
3073 /// Find the complete object to which an LValue refers.
3074 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3075 AccessKinds AK, const LValue &LVal,
3076 QualType LValType) {
3078 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3079 return CompleteObject();
3082 CallStackFrame *Frame = nullptr;
3083 if (LVal.getLValueCallIndex()) {
3084 Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3086 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3087 << AK << LVal.Base.is<const ValueDecl*>();
3088 NoteLValueLocation(Info, LVal.Base);
3089 return CompleteObject();
3093 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3094 // is not a constant expression (even if the object is non-volatile). We also
3095 // apply this rule to C++98, in order to conform to the expected 'volatile'
3097 if (LValType.isVolatileQualified()) {
3098 if (Info.getLangOpts().CPlusPlus)
3099 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3103 return CompleteObject();
3106 // Compute value storage location and type of base object.
3107 APValue *BaseVal = nullptr;
3108 QualType BaseType = getType(LVal.Base);
3109 bool LifetimeStartedInEvaluation = Frame;
3111 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3112 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3113 // In C++11, constexpr, non-volatile variables initialized with constant
3114 // expressions are constant expressions too. Inside constexpr functions,
3115 // parameters are constant expressions even if they're non-const.
3116 // In C++1y, objects local to a constant expression (those with a Frame) are
3117 // both readable and writable inside constant expressions.
3118 // In C, such things can also be folded, although they are not ICEs.
3119 const VarDecl *VD = dyn_cast<VarDecl>(D);
3121 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3124 if (!VD || VD->isInvalidDecl()) {
3126 return CompleteObject();
3129 // Accesses of volatile-qualified objects are not allowed.
3130 if (BaseType.isVolatileQualified()) {
3131 if (Info.getLangOpts().CPlusPlus) {
3132 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3134 Info.Note(VD->getLocation(), diag::note_declared_at);
3138 return CompleteObject();
3141 // Unless we're looking at a local variable or argument in a constexpr call,
3142 // the variable we're reading must be const.
3144 if (Info.getLangOpts().CPlusPlus14 &&
3145 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3146 // OK, we can read and modify an object if we're in the process of
3147 // evaluating its initializer, because its lifetime began in this
3149 } else if (AK != AK_Read) {
3150 // All the remaining cases only permit reading.
3151 Info.FFDiag(E, diag::note_constexpr_modify_global);
3152 return CompleteObject();
3153 } else if (VD->isConstexpr()) {
3154 // OK, we can read this variable.
3155 } else if (BaseType->isIntegralOrEnumerationType()) {
3156 // In OpenCL if a variable is in constant address space it is a const value.
3157 if (!(BaseType.isConstQualified() ||
3158 (Info.getLangOpts().OpenCL &&
3159 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3160 if (Info.getLangOpts().CPlusPlus) {
3161 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3162 Info.Note(VD->getLocation(), diag::note_declared_at);
3166 return CompleteObject();
3168 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3169 // We support folding of const floating-point types, in order to make
3170 // static const data members of such types (supported as an extension)
3172 if (Info.getLangOpts().CPlusPlus11) {
3173 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3174 Info.Note(VD->getLocation(), diag::note_declared_at);
3178 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3179 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3180 // Keep evaluating to see what we can do.
3182 // FIXME: Allow folding of values of any literal type in all languages.
3183 if (Info.checkingPotentialConstantExpression() &&
3184 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3185 // The definition of this variable could be constexpr. We can't
3186 // access it right now, but may be able to in future.
3187 } else if (Info.getLangOpts().CPlusPlus11) {
3188 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3189 Info.Note(VD->getLocation(), diag::note_declared_at);
3193 return CompleteObject();
3197 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3198 return CompleteObject();
3200 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3203 if (const MaterializeTemporaryExpr *MTE =
3204 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3205 assert(MTE->getStorageDuration() == SD_Static &&
3206 "should have a frame for a non-global materialized temporary");
3208 // Per C++1y [expr.const]p2:
3209 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3210 // - a [...] glvalue of integral or enumeration type that refers to
3211 // a non-volatile const object [...]
3213 // - a [...] glvalue of literal type that refers to a non-volatile
3214 // object whose lifetime began within the evaluation of e.
3216 // C++11 misses the 'began within the evaluation of e' check and
3217 // instead allows all temporaries, including things like:
3220 // constexpr int k = r;
3221 // Therefore we use the C++14 rules in C++11 too.
3222 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3223 const ValueDecl *ED = MTE->getExtendingDecl();
3224 if (!(BaseType.isConstQualified() &&
3225 BaseType->isIntegralOrEnumerationType()) &&
3226 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3227 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3228 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3229 return CompleteObject();
3232 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3233 assert(BaseVal && "got reference to unevaluated temporary");
3234 LifetimeStartedInEvaluation = true;
3237 return CompleteObject();
3240 BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3241 assert(BaseVal && "missing value for temporary");
3244 // Volatile temporary objects cannot be accessed in constant expressions.
3245 if (BaseType.isVolatileQualified()) {
3246 if (Info.getLangOpts().CPlusPlus) {
3247 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3249 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3253 return CompleteObject();
3257 // During the construction of an object, it is not yet 'const'.
3258 // FIXME: This doesn't do quite the right thing for const subobjects of the
3259 // object under construction.
3260 if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3261 LVal.getLValueCallIndex(),
3262 LVal.getLValueVersion())) {
3263 BaseType = Info.Ctx.getCanonicalType(BaseType);
3264 BaseType.removeLocalConst();
3265 LifetimeStartedInEvaluation = true;
3268 // In C++14, we can't safely access any mutable state when we might be
3269 // evaluating after an unmodeled side effect.
3271 // FIXME: Not all local state is mutable. Allow local constant subobjects
3272 // to be read here (but take care with 'mutable' fields).
3273 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3274 Info.EvalStatus.HasSideEffects) ||
3275 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3276 return CompleteObject();
3278 return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3281 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3282 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3283 /// glvalue referred to by an entity of reference type.
3285 /// \param Info - Information about the ongoing evaluation.
3286 /// \param Conv - The expression for which we are performing the conversion.
3287 /// Used for diagnostics.
3288 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3289 /// case of a non-class type).
3290 /// \param LVal - The glvalue on which we are attempting to perform this action.
3291 /// \param RVal - The produced value will be placed here.
3292 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3294 const LValue &LVal, APValue &RVal) {
3295 if (LVal.Designator.Invalid)
3298 // Check for special cases where there is no existing APValue to look at.
3299 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3300 if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3301 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3302 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3303 // initializer until now for such expressions. Such an expression can't be
3304 // an ICE in C, so this only matters for fold.
3305 if (Type.isVolatileQualified()) {
3310 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3312 CompleteObject LitObj(&Lit, Base->getType(), false);
3313 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3314 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3315 // We represent a string literal array as an lvalue pointing at the
3316 // corresponding expression, rather than building an array of chars.
3317 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3318 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3319 CompleteObject StrObj(&Str, Base->getType(), false);
3320 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3324 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3325 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3328 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3329 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3330 QualType LValType, APValue &Val) {
3331 if (LVal.Designator.Invalid)
3334 if (!Info.getLangOpts().CPlusPlus14) {
3339 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3340 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3344 struct CompoundAssignSubobjectHandler {
3347 QualType PromotedLHSType;
3348 BinaryOperatorKind Opcode;
3351 static const AccessKinds AccessKind = AK_Assign;
3353 typedef bool result_type;
3355 bool checkConst(QualType QT) {
3356 // Assigning to a const object has undefined behavior.
3357 if (QT.isConstQualified()) {
3358 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3364 bool failed() { return false; }
3365 bool found(APValue &Subobj, QualType SubobjType) {
3366 switch (Subobj.getKind()) {
3368 return found(Subobj.getInt(), SubobjType);
3369 case APValue::Float:
3370 return found(Subobj.getFloat(), SubobjType);
3371 case APValue::ComplexInt:
3372 case APValue::ComplexFloat:
3373 // FIXME: Implement complex compound assignment.
3376 case APValue::LValue:
3377 return foundPointer(Subobj, SubobjType);
3379 // FIXME: can this happen?
3384 bool found(APSInt &Value, QualType SubobjType) {
3385 if (!checkConst(SubobjType))
3388 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3389 // We don't support compound assignment on integer-cast-to-pointer
3395 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3397 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3399 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3402 bool found(APFloat &Value, QualType SubobjType) {
3403 return checkConst(SubobjType) &&
3404 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3406 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3407 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3409 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3410 if (!checkConst(SubobjType))
3413 QualType PointeeType;
3414 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3415 PointeeType = PT->getPointeeType();
3417 if (PointeeType.isNull() || !RHS.isInt() ||
3418 (Opcode != BO_Add && Opcode != BO_Sub)) {
3423 APSInt Offset = RHS.getInt();
3424 if (Opcode == BO_Sub)
3425 negateAsSigned(Offset);
3428 LVal.setFrom(Info.Ctx, Subobj);
3429 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3431 LVal.moveInto(Subobj);
3434 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3435 llvm_unreachable("shouldn't encounter string elements here");
3438 } // end anonymous namespace
3440 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3442 /// Perform a compound assignment of LVal <op>= RVal.
3443 static bool handleCompoundAssignment(
3444 EvalInfo &Info, const Expr *E,
3445 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3446 BinaryOperatorKind Opcode, const APValue &RVal) {
3447 if (LVal.Designator.Invalid)
3450 if (!Info.getLangOpts().CPlusPlus14) {
3455 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3456 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3458 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3462 struct IncDecSubobjectHandler {
3464 const UnaryOperator *E;
3465 AccessKinds AccessKind;
3468 typedef bool result_type;
3470 bool checkConst(QualType QT) {
3471 // Assigning to a const object has undefined behavior.
3472 if (QT.isConstQualified()) {
3473 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3479 bool failed() { return false; }
3480 bool found(APValue &Subobj, QualType SubobjType) {
3481 // Stash the old value. Also clear Old, so we don't clobber it later
3482 // if we're post-incrementing a complex.
3488 switch (Subobj.getKind()) {
3490 return found(Subobj.getInt(), SubobjType);
3491 case APValue::Float:
3492 return found(Subobj.getFloat(), SubobjType);
3493 case APValue::ComplexInt:
3494 return found(Subobj.getComplexIntReal(),
3495 SubobjType->castAs<ComplexType>()->getElementType()
3496 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3497 case APValue::ComplexFloat:
3498 return found(Subobj.getComplexFloatReal(),
3499 SubobjType->castAs<ComplexType>()->getElementType()
3500 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3501 case APValue::LValue:
3502 return foundPointer(Subobj, SubobjType);
3504 // FIXME: can this happen?
3509 bool found(APSInt &Value, QualType SubobjType) {
3510 if (!checkConst(SubobjType))
3513 if (!SubobjType->isIntegerType()) {
3514 // We don't support increment / decrement on integer-cast-to-pointer
3520 if (Old) *Old = APValue(Value);
3522 // bool arithmetic promotes to int, and the conversion back to bool
3523 // doesn't reduce mod 2^n, so special-case it.
3524 if (SubobjType->isBooleanType()) {
3525 if (AccessKind == AK_Increment)
3532 bool WasNegative = Value.isNegative();
3533 if (AccessKind == AK_Increment) {
3536 if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3537 APSInt ActualValue(Value, /*IsUnsigned*/true);
3538 return HandleOverflow(Info, E, ActualValue, SubobjType);
3543 if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3544 unsigned BitWidth = Value.getBitWidth();
3545 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3546 ActualValue.setBit(BitWidth);
3547 return HandleOverflow(Info, E, ActualValue, SubobjType);
3552 bool found(APFloat &Value, QualType SubobjType) {
3553 if (!checkConst(SubobjType))
3556 if (Old) *Old = APValue(Value);
3558 APFloat One(Value.getSemantics(), 1);
3559 if (AccessKind == AK_Increment)
3560 Value.add(One, APFloat::rmNearestTiesToEven);
3562 Value.subtract(One, APFloat::rmNearestTiesToEven);
3565 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3566 if (!checkConst(SubobjType))
3569 QualType PointeeType;
3570 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3571 PointeeType = PT->getPointeeType();
3578 LVal.setFrom(Info.Ctx, Subobj);
3579 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3580 AccessKind == AK_Increment ? 1 : -1))
3582 LVal.moveInto(Subobj);
3585 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3586 llvm_unreachable("shouldn't encounter string elements here");
3589 } // end anonymous namespace
3591 /// Perform an increment or decrement on LVal.
3592 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3593 QualType LValType, bool IsIncrement, APValue *Old) {
3594 if (LVal.Designator.Invalid)
3597 if (!Info.getLangOpts().CPlusPlus14) {
3602 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3603 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3604 IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3605 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3608 /// Build an lvalue for the object argument of a member function call.
3609 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3611 if (Object->getType()->isPointerType())
3612 return EvaluatePointer(Object, This, Info);
3614 if (Object->isGLValue())
3615 return EvaluateLValue(Object, This, Info);
3617 if (Object->getType()->isLiteralType(Info.Ctx))
3618 return EvaluateTemporary(Object, This, Info);
3620 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3624 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3625 /// lvalue referring to the result.
3627 /// \param Info - Information about the ongoing evaluation.
3628 /// \param LV - An lvalue referring to the base of the member pointer.
3629 /// \param RHS - The member pointer expression.
3630 /// \param IncludeMember - Specifies whether the member itself is included in
3631 /// the resulting LValue subobject designator. This is not possible when
3632 /// creating a bound member function.
3633 /// \return The field or method declaration to which the member pointer refers,
3634 /// or 0 if evaluation fails.
3635 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3639 bool IncludeMember = true) {
3641 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3644 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3645 // member value, the behavior is undefined.
3646 if (!MemPtr.getDecl()) {
3647 // FIXME: Specific diagnostic.
3652 if (MemPtr.isDerivedMember()) {
3653 // This is a member of some derived class. Truncate LV appropriately.
3654 // The end of the derived-to-base path for the base object must match the
3655 // derived-to-base path for the member pointer.
3656 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3657 LV.Designator.Entries.size()) {
3661 unsigned PathLengthToMember =
3662 LV.Designator.Entries.size() - MemPtr.Path.size();
3663 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3664 const CXXRecordDecl *LVDecl = getAsBaseClass(
3665 LV.Designator.Entries[PathLengthToMember + I]);
3666 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3667 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3673 // Truncate the lvalue to the appropriate derived class.
3674 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3675 PathLengthToMember))
3677 } else if (!MemPtr.Path.empty()) {
3678 // Extend the LValue path with the member pointer's path.
3679 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3680 MemPtr.Path.size() + IncludeMember);
3682 // Walk down to the appropriate base class.
3683 if (const PointerType *PT = LVType->getAs<PointerType>())
3684 LVType = PT->getPointeeType();
3685 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3686 assert(RD && "member pointer access on non-class-type expression");
3687 // The first class in the path is that of the lvalue.
3688 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3689 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3690 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3694 // Finally cast to the class containing the member.
3695 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3696 MemPtr.getContainingRecord()))
3700 // Add the member. Note that we cannot build bound member functions here.
3701 if (IncludeMember) {
3702 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3703 if (!HandleLValueMember(Info, RHS, LV, FD))
3705 } else if (const IndirectFieldDecl *IFD =
3706 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3707 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3710 llvm_unreachable("can't construct reference to bound member function");
3714 return MemPtr.getDecl();
3717 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3718 const BinaryOperator *BO,
3720 bool IncludeMember = true) {
3721 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3723 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3724 if (Info.noteFailure()) {
3726 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3731 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3732 BO->getRHS(), IncludeMember);
3735 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3736 /// the provided lvalue, which currently refers to the base object.
3737 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3739 SubobjectDesignator &D = Result.Designator;
3740 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3743 QualType TargetQT = E->getType();
3744 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3745 TargetQT = PT->getPointeeType();
3747 // Check this cast lands within the final derived-to-base subobject path.
3748 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3749 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3750 << D.MostDerivedType << TargetQT;
3754 // Check the type of the final cast. We don't need to check the path,
3755 // since a cast can only be formed if the path is unique.
3756 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3757 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3758 const CXXRecordDecl *FinalType;
3759 if (NewEntriesSize == D.MostDerivedPathLength)
3760 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3762 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3763 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3764 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3765 << D.MostDerivedType << TargetQT;
3769 // Truncate the lvalue to the appropriate derived class.
3770 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3774 enum EvalStmtResult {
3775 /// Evaluation failed.
3777 /// Hit a 'return' statement.
3779 /// Evaluation succeeded.
3781 /// Hit a 'continue' statement.
3783 /// Hit a 'break' statement.
3785 /// Still scanning for 'case' or 'default' statement.
3790 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3791 // We don't need to evaluate the initializer for a static local.
3792 if (!VD->hasLocalStorage())
3796 APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3798 const Expr *InitE = VD->getInit();
3800 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3801 << false << VD->getType();
3806 if (InitE->isValueDependent())
3809 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3810 // Wipe out any partially-computed value, to allow tracking that this
3811 // evaluation failed.
3819 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3822 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3823 OK &= EvaluateVarDecl(Info, VD);
3825 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3826 for (auto *BD : DD->bindings())
3827 if (auto *VD = BD->getHoldingVar())
3828 OK &= EvaluateDecl(Info, VD);
3834 /// Evaluate a condition (either a variable declaration or an expression).
3835 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3836 const Expr *Cond, bool &Result) {
3837 FullExpressionRAII Scope(Info);
3838 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3840 return EvaluateAsBooleanCondition(Cond, Result, Info);
3844 /// A location where the result (returned value) of evaluating a
3845 /// statement should be stored.
3847 /// The APValue that should be filled in with the returned value.
3849 /// The location containing the result, if any (used to support RVO).
3853 struct TempVersionRAII {
3854 CallStackFrame &Frame;
3856 TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3857 Frame.pushTempVersion();
3860 ~TempVersionRAII() {
3861 Frame.popTempVersion();
3867 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3869 const SwitchCase *SC = nullptr);
3871 /// Evaluate the body of a loop, and translate the result as appropriate.
3872 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3874 const SwitchCase *Case = nullptr) {
3875 BlockScopeRAII Scope(Info);
3876 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3878 return ESR_Succeeded;
3881 return ESR_Continue;
3884 case ESR_CaseNotFound:
3887 llvm_unreachable("Invalid EvalStmtResult!");
3890 /// Evaluate a switch statement.
3891 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3892 const SwitchStmt *SS) {
3893 BlockScopeRAII Scope(Info);
3895 // Evaluate the switch condition.
3898 FullExpressionRAII Scope(Info);
3899 if (const Stmt *Init = SS->getInit()) {
3900 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3901 if (ESR != ESR_Succeeded)
3904 if (SS->getConditionVariable() &&
3905 !EvaluateDecl(Info, SS->getConditionVariable()))
3907 if (!EvaluateInteger(SS->getCond(), Value, Info))
3911 // Find the switch case corresponding to the value of the condition.
3912 // FIXME: Cache this lookup.
3913 const SwitchCase *Found = nullptr;
3914 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3915 SC = SC->getNextSwitchCase()) {
3916 if (isa<DefaultStmt>(SC)) {
3921 const CaseStmt *CS = cast<CaseStmt>(SC);
3922 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3923 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3925 if (LHS <= Value && Value <= RHS) {
3932 return ESR_Succeeded;
3934 // Search the switch body for the switch case and evaluate it from there.
3935 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3937 return ESR_Succeeded;
3943 case ESR_CaseNotFound:
3944 // This can only happen if the switch case is nested within a statement
3945 // expression. We have no intention of supporting that.
3946 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3949 llvm_unreachable("Invalid EvalStmtResult!");
3952 // Evaluate a statement.
3953 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3954 const Stmt *S, const SwitchCase *Case) {
3955 if (!Info.nextStep(S))
3958 // If we're hunting down a 'case' or 'default' label, recurse through
3959 // substatements until we hit the label.
3961 // FIXME: We don't start the lifetime of objects whose initialization we
3962 // jump over. However, such objects must be of class type with a trivial
3963 // default constructor that initialize all subobjects, so must be empty,
3964 // so this almost never matters.
3965 switch (S->getStmtClass()) {
3966 case Stmt::CompoundStmtClass:
3967 // FIXME: Precompute which substatement of a compound statement we
3968 // would jump to, and go straight there rather than performing a
3969 // linear scan each time.
3970 case Stmt::LabelStmtClass:
3971 case Stmt::AttributedStmtClass:
3972 case Stmt::DoStmtClass:
3975 case Stmt::CaseStmtClass:
3976 case Stmt::DefaultStmtClass:
3981 case Stmt::IfStmtClass: {
3982 // FIXME: Precompute which side of an 'if' we would jump to, and go
3983 // straight there rather than scanning both sides.
3984 const IfStmt *IS = cast<IfStmt>(S);
3986 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3987 // preceded by our switch label.
3988 BlockScopeRAII Scope(Info);
3990 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3991 if (ESR != ESR_CaseNotFound || !IS->getElse())
3993 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3996 case Stmt::WhileStmtClass: {
3997 EvalStmtResult ESR =
3998 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3999 if (ESR != ESR_Continue)
4004 case Stmt::ForStmtClass: {
4005 const ForStmt *FS = cast<ForStmt>(S);
4006 EvalStmtResult ESR =
4007 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4008 if (ESR != ESR_Continue)
4011 FullExpressionRAII IncScope(Info);
4012 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4018 case Stmt::DeclStmtClass:
4019 // FIXME: If the variable has initialization that can't be jumped over,
4020 // bail out of any immediately-surrounding compound-statement too.
4022 return ESR_CaseNotFound;
4026 switch (S->getStmtClass()) {
4028 if (const Expr *E = dyn_cast<Expr>(S)) {
4029 // Don't bother evaluating beyond an expression-statement which couldn't
4031 FullExpressionRAII Scope(Info);
4032 if (!EvaluateIgnoredValue(Info, E))
4034 return ESR_Succeeded;
4037 Info.FFDiag(S->getLocStart());
4040 case Stmt::NullStmtClass:
4041 return ESR_Succeeded;
4043 case Stmt::DeclStmtClass: {
4044 const DeclStmt *DS = cast<DeclStmt>(S);
4045 for (const auto *DclIt : DS->decls()) {
4046 // Each declaration initialization is its own full-expression.
4047 // FIXME: This isn't quite right; if we're performing aggregate
4048 // initialization, each braced subexpression is its own full-expression.
4049 FullExpressionRAII Scope(Info);
4050 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4053 return ESR_Succeeded;
4056 case Stmt::ReturnStmtClass: {
4057 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4058 FullExpressionRAII Scope(Info);
4061 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4062 : Evaluate(Result.Value, Info, RetExpr)))
4064 return ESR_Returned;
4067 case Stmt::CompoundStmtClass: {
4068 BlockScopeRAII Scope(Info);
4070 const CompoundStmt *CS = cast<CompoundStmt>(S);
4071 for (const auto *BI : CS->body()) {
4072 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4073 if (ESR == ESR_Succeeded)
4075 else if (ESR != ESR_CaseNotFound)
4078 return Case ? ESR_CaseNotFound : ESR_Succeeded;
4081 case Stmt::IfStmtClass: {
4082 const IfStmt *IS = cast<IfStmt>(S);
4084 // Evaluate the condition, as either a var decl or as an expression.
4085 BlockScopeRAII Scope(Info);
4086 if (const Stmt *Init = IS->getInit()) {
4087 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4088 if (ESR != ESR_Succeeded)
4092 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4095 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4096 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4097 if (ESR != ESR_Succeeded)
4100 return ESR_Succeeded;
4103 case Stmt::WhileStmtClass: {
4104 const WhileStmt *WS = cast<WhileStmt>(S);
4106 BlockScopeRAII Scope(Info);
4108 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4114 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4115 if (ESR != ESR_Continue)
4118 return ESR_Succeeded;
4121 case Stmt::DoStmtClass: {
4122 const DoStmt *DS = cast<DoStmt>(S);
4125 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4126 if (ESR != ESR_Continue)
4130 FullExpressionRAII CondScope(Info);
4131 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4134 return ESR_Succeeded;
4137 case Stmt::ForStmtClass: {
4138 const ForStmt *FS = cast<ForStmt>(S);
4139 BlockScopeRAII Scope(Info);
4140 if (FS->getInit()) {
4141 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4142 if (ESR != ESR_Succeeded)
4146 BlockScopeRAII Scope(Info);
4147 bool Continue = true;
4148 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4149 FS->getCond(), Continue))
4154 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4155 if (ESR != ESR_Continue)
4159 FullExpressionRAII IncScope(Info);
4160 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4164 return ESR_Succeeded;
4167 case Stmt::CXXForRangeStmtClass: {
4168 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4169 BlockScopeRAII Scope(Info);
4171 // Initialize the __range variable.
4172 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4173 if (ESR != ESR_Succeeded)
4176 // Create the __begin and __end iterators.
4177 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4178 if (ESR != ESR_Succeeded)
4180 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4181 if (ESR != ESR_Succeeded)
4185 // Condition: __begin != __end.
4187 bool Continue = true;
4188 FullExpressionRAII CondExpr(Info);
4189 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4195 // User's variable declaration, initialized by *__begin.
4196 BlockScopeRAII InnerScope(Info);
4197 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4198 if (ESR != ESR_Succeeded)
4202 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4203 if (ESR != ESR_Continue)
4206 // Increment: ++__begin
4207 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4211 return ESR_Succeeded;
4214 case Stmt::SwitchStmtClass:
4215 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4217 case Stmt::ContinueStmtClass:
4218 return ESR_Continue;
4220 case Stmt::BreakStmtClass:
4223 case Stmt::LabelStmtClass:
4224 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4226 case Stmt::AttributedStmtClass:
4227 // As a general principle, C++11 attributes can be ignored without
4228 // any semantic impact.
4229 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4232 case Stmt::CaseStmtClass:
4233 case Stmt::DefaultStmtClass:
4234 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4238 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4239 /// default constructor. If so, we'll fold it whether or not it's marked as
4240 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4241 /// so we need special handling.
4242 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4243 const CXXConstructorDecl *CD,
4244 bool IsValueInitialization) {
4245 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4248 // Value-initialization does not call a trivial default constructor, so such a
4249 // call is a core constant expression whether or not the constructor is
4251 if (!CD->isConstexpr() && !IsValueInitialization) {
4252 if (Info.getLangOpts().CPlusPlus11) {
4253 // FIXME: If DiagDecl is an implicitly-declared special member function,
4254 // we should be much more explicit about why it's not constexpr.
4255 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4256 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4257 Info.Note(CD->getLocation(), diag::note_declared_at);
4259 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4265 /// CheckConstexprFunction - Check that a function can be called in a constant
4267 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4268 const FunctionDecl *Declaration,
4269 const FunctionDecl *Definition,
4271 // Potential constant expressions can contain calls to declared, but not yet
4272 // defined, constexpr functions.
4273 if (Info.checkingPotentialConstantExpression() && !Definition &&
4274 Declaration->isConstexpr())
4277 // Bail out with no diagnostic if the function declaration itself is invalid.
4278 // We will have produced a relevant diagnostic while parsing it.
4279 if (Declaration->isInvalidDecl())
4282 // Can we evaluate this function call?
4283 if (Definition && Definition->isConstexpr() &&
4284 !Definition->isInvalidDecl() && Body)
4287 if (Info.getLangOpts().CPlusPlus11) {
4288 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4290 // If this function is not constexpr because it is an inherited
4291 // non-constexpr constructor, diagnose that directly.
4292 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4293 if (CD && CD->isInheritingConstructor()) {
4294 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4295 if (!Inherited->isConstexpr())
4296 DiagDecl = CD = Inherited;
4299 // FIXME: If DiagDecl is an implicitly-declared special member function
4300 // or an inheriting constructor, we should be much more explicit about why
4301 // it's not constexpr.
4302 if (CD && CD->isInheritingConstructor())
4303 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4304 << CD->getInheritedConstructor().getConstructor()->getParent();
4306 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4307 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4308 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4310 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4315 /// Determine if a class has any fields that might need to be copied by a
4316 /// trivial copy or move operation.
4317 static bool hasFields(const CXXRecordDecl *RD) {
4318 if (!RD || RD->isEmpty())
4320 for (auto *FD : RD->fields()) {
4321 if (FD->isUnnamedBitfield())
4325 for (auto &Base : RD->bases())
4326 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4332 typedef SmallVector<APValue, 8> ArgVector;
4335 /// EvaluateArgs - Evaluate the arguments to a function call.
4336 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4338 bool Success = true;
4339 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4341 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4342 // If we're checking for a potential constant expression, evaluate all
4343 // initializers even if some of them fail.
4344 if (!Info.noteFailure())
4352 /// Evaluate a function call.
4353 static bool HandleFunctionCall(SourceLocation CallLoc,
4354 const FunctionDecl *Callee, const LValue *This,
4355 ArrayRef<const Expr*> Args, const Stmt *Body,
4356 EvalInfo &Info, APValue &Result,
4357 const LValue *ResultSlot) {
4358 ArgVector ArgValues(Args.size());
4359 if (!EvaluateArgs(Args, ArgValues, Info))
4362 if (!Info.CheckCallLimit(CallLoc))
4365 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4367 // For a trivial copy or move assignment, perform an APValue copy. This is
4368 // essential for unions, where the operations performed by the assignment
4369 // operator cannot be represented as statements.
4371 // Skip this for non-union classes with no fields; in that case, the defaulted
4372 // copy/move does not actually read the object.
4373 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4374 if (MD && MD->isDefaulted() &&
4375 (MD->getParent()->isUnion() ||
4376 (MD->isTrivial() && hasFields(MD->getParent())))) {
4378 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4380 RHS.setFrom(Info.Ctx, ArgValues[0]);
4382 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4385 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4388 This->moveInto(Result);
4390 } else if (MD && isLambdaCallOperator(MD)) {
4391 // We're in a lambda; determine the lambda capture field maps unless we're
4392 // just constexpr checking a lambda's call operator. constexpr checking is
4393 // done before the captures have been added to the closure object (unless
4394 // we're inferring constexpr-ness), so we don't have access to them in this
4395 // case. But since we don't need the captures to constexpr check, we can
4396 // just ignore them.
4397 if (!Info.checkingPotentialConstantExpression())
4398 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4399 Frame.LambdaThisCaptureField);
4402 StmtResult Ret = {Result, ResultSlot};
4403 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4404 if (ESR == ESR_Succeeded) {
4405 if (Callee->getReturnType()->isVoidType())
4407 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4409 return ESR == ESR_Returned;
4412 /// Evaluate a constructor call.
4413 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4415 const CXXConstructorDecl *Definition,
4416 EvalInfo &Info, APValue &Result) {
4417 SourceLocation CallLoc = E->getExprLoc();
4418 if (!Info.CheckCallLimit(CallLoc))
4421 const CXXRecordDecl *RD = Definition->getParent();
4422 if (RD->getNumVBases()) {
4423 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4427 EvalInfo::EvaluatingConstructorRAII EvalObj(
4428 Info, {This.getLValueBase(),
4429 {This.getLValueCallIndex(), This.getLValueVersion()}});
4430 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4432 // FIXME: Creating an APValue just to hold a nonexistent return value is
4435 StmtResult Ret = {RetVal, nullptr};
4437 // If it's a delegating constructor, delegate.
4438 if (Definition->isDelegatingConstructor()) {
4439 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4441 FullExpressionRAII InitScope(Info);
4442 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4445 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4448 // For a trivial copy or move constructor, perform an APValue copy. This is
4449 // essential for unions (or classes with anonymous union members), where the
4450 // operations performed by the constructor cannot be represented by
4451 // ctor-initializers.
4453 // Skip this for empty non-union classes; we should not perform an
4454 // lvalue-to-rvalue conversion on them because their copy constructor does not
4455 // actually read them.
4456 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4457 (Definition->getParent()->isUnion() ||
4458 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4460 RHS.setFrom(Info.Ctx, ArgValues[0]);
4461 return handleLValueToRValueConversion(
4462 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4466 // Reserve space for the struct members.
4467 if (!RD->isUnion() && Result.isUninit())
4468 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4469 std::distance(RD->field_begin(), RD->field_end()));
4471 if (RD->isInvalidDecl()) return false;
4472 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4474 // A scope for temporaries lifetime-extended by reference members.
4475 BlockScopeRAII LifetimeExtendedScope(Info);
4477 bool Success = true;
4478 unsigned BasesSeen = 0;
4480 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4482 for (const auto *I : Definition->inits()) {
4483 LValue Subobject = This;
4484 LValue SubobjectParent = This;
4485 APValue *Value = &Result;
4487 // Determine the subobject to initialize.
4488 FieldDecl *FD = nullptr;
4489 if (I->isBaseInitializer()) {
4490 QualType BaseType(I->getBaseClass(), 0);
4492 // Non-virtual base classes are initialized in the order in the class
4493 // definition. We have already checked for virtual base classes.
4494 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4495 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4496 "base class initializers not in expected order");
4499 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4500 BaseType->getAsCXXRecordDecl(), &Layout))
4502 Value = &Result.getStructBase(BasesSeen++);
4503 } else if ((FD = I->getMember())) {
4504 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4506 if (RD->isUnion()) {
4507 Result = APValue(FD);
4508 Value = &Result.getUnionValue();
4510 Value = &Result.getStructField(FD->getFieldIndex());
4512 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4513 // Walk the indirect field decl's chain to find the object to initialize,
4514 // and make sure we've initialized every step along it.
4515 auto IndirectFieldChain = IFD->chain();
4516 for (auto *C : IndirectFieldChain) {
4517 FD = cast<FieldDecl>(C);
4518 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4519 // Switch the union field if it differs. This happens if we had
4520 // preceding zero-initialization, and we're now initializing a union
4521 // subobject other than the first.
4522 // FIXME: In this case, the values of the other subobjects are
4523 // specified, since zero-initialization sets all padding bits to zero.
4524 if (Value->isUninit() ||
4525 (Value->isUnion() && Value->getUnionField() != FD)) {
4527 *Value = APValue(FD);
4529 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4530 std::distance(CD->field_begin(), CD->field_end()));
4532 // Store Subobject as its parent before updating it for the last element
4534 if (C == IndirectFieldChain.back())
4535 SubobjectParent = Subobject;
4536 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4539 Value = &Value->getUnionValue();
4541 Value = &Value->getStructField(FD->getFieldIndex());
4544 llvm_unreachable("unknown base initializer kind");
4547 // Need to override This for implicit field initializers as in this case
4548 // This refers to innermost anonymous struct/union containing initializer,
4549 // not to currently constructed class.
4550 const Expr *Init = I->getInit();
4551 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4552 isa<CXXDefaultInitExpr>(Init));
4553 FullExpressionRAII InitScope(Info);
4554 if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4555 (FD && FD->isBitField() &&
4556 !truncateBitfieldValue(Info, Init, *Value, FD))) {
4557 // If we're checking for a potential constant expression, evaluate all
4558 // initializers even if some of them fail.
4559 if (!Info.noteFailure())
4566 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4569 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4570 ArrayRef<const Expr*> Args,
4571 const CXXConstructorDecl *Definition,
4572 EvalInfo &Info, APValue &Result) {
4573 ArgVector ArgValues(Args.size());
4574 if (!EvaluateArgs(Args, ArgValues, Info))
4577 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4581 //===----------------------------------------------------------------------===//
4582 // Generic Evaluation
4583 //===----------------------------------------------------------------------===//
4586 template <class Derived>
4587 class ExprEvaluatorBase
4588 : public ConstStmtVisitor<Derived, bool> {
4590 Derived &getDerived() { return static_cast<Derived&>(*this); }
4591 bool DerivedSuccess(const APValue &V, const Expr *E) {
4592 return getDerived().Success(V, E);
4594 bool DerivedZeroInitialization(const Expr *E) {
4595 return getDerived().ZeroInitialization(E);
4598 // Check whether a conditional operator with a non-constant condition is a
4599 // potential constant expression. If neither arm is a potential constant
4600 // expression, then the conditional operator is not either.
4601 template<typename ConditionalOperator>
4602 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4603 assert(Info.checkingPotentialConstantExpression());
4605 // Speculatively evaluate both arms.
4606 SmallVector<PartialDiagnosticAt, 8> Diag;
4608 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4609 StmtVisitorTy::Visit(E->getFalseExpr());
4615 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4617 StmtVisitorTy::Visit(E->getTrueExpr());
4622 Error(E, diag::note_constexpr_conditional_never_const);
4626 template<typename ConditionalOperator>
4627 bool HandleConditionalOperator(const ConditionalOperator *E) {
4629 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4630 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4631 CheckPotentialConstantConditional(E);
4634 if (Info.noteFailure()) {
4635 StmtVisitorTy::Visit(E->getTrueExpr());
4636 StmtVisitorTy::Visit(E->getFalseExpr());
4641 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4642 return StmtVisitorTy::Visit(EvalExpr);
4647 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4648 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4650 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4651 return Info.CCEDiag(E, D);
4654 bool ZeroInitialization(const Expr *E) { return Error(E); }
4657 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4659 EvalInfo &getEvalInfo() { return Info; }
4661 /// Report an evaluation error. This should only be called when an error is
4662 /// first discovered. When propagating an error, just return false.
4663 bool Error(const Expr *E, diag::kind D) {
4667 bool Error(const Expr *E) {
4668 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4671 bool VisitStmt(const Stmt *) {
4672 llvm_unreachable("Expression evaluator should not be called on stmts");
4674 bool VisitExpr(const Expr *E) {
4678 bool VisitParenExpr(const ParenExpr *E)
4679 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4680 bool VisitUnaryExtension(const UnaryOperator *E)
4681 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4682 bool VisitUnaryPlus(const UnaryOperator *E)
4683 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4684 bool VisitChooseExpr(const ChooseExpr *E)
4685 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4686 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4687 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4688 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4689 { return StmtVisitorTy::Visit(E->getReplacement()); }
4690 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4691 TempVersionRAII RAII(*Info.CurrentCall);
4692 return StmtVisitorTy::Visit(E->getExpr());
4694 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4695 TempVersionRAII RAII(*Info.CurrentCall);
4696 // The initializer may not have been parsed yet, or might be erroneous.
4699 return StmtVisitorTy::Visit(E->getExpr());
4701 // We cannot create any objects for which cleanups are required, so there is
4702 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4703 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4704 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4706 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4707 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4708 return static_cast<Derived*>(this)->VisitCastExpr(E);
4710 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4711 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4712 return static_cast<Derived*>(this)->VisitCastExpr(E);
4715 bool VisitBinaryOperator(const BinaryOperator *E) {
4716 switch (E->getOpcode()) {
4721 VisitIgnoredValue(E->getLHS());
4722 return StmtVisitorTy::Visit(E->getRHS());
4727 if (!HandleMemberPointerAccess(Info, E, Obj))
4730 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4732 return DerivedSuccess(Result, E);
4737 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4738 // Evaluate and cache the common expression. We treat it as a temporary,
4739 // even though it's not quite the same thing.
4740 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4741 Info, E->getCommon()))
4744 return HandleConditionalOperator(E);
4747 bool VisitConditionalOperator(const ConditionalOperator *E) {
4748 bool IsBcpCall = false;
4749 // If the condition (ignoring parens) is a __builtin_constant_p call,
4750 // the result is a constant expression if it can be folded without
4751 // side-effects. This is an important GNU extension. See GCC PR38377
4753 if (const CallExpr *CallCE =
4754 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4755 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4758 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4759 // constant expression; we can't check whether it's potentially foldable.
4760 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4763 FoldConstant Fold(Info, IsBcpCall);
4764 if (!HandleConditionalOperator(E)) {
4765 Fold.keepDiagnostics();
4772 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4773 if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4774 return DerivedSuccess(*Value, E);
4776 const Expr *Source = E->getSourceExpr();
4779 if (Source == E) { // sanity checking.
4780 assert(0 && "OpaqueValueExpr recursively refers to itself");
4783 return StmtVisitorTy::Visit(Source);
4786 bool VisitCallExpr(const CallExpr *E) {
4788 if (!handleCallExpr(E, Result, nullptr))
4790 return DerivedSuccess(Result, E);
4793 bool handleCallExpr(const CallExpr *E, APValue &Result,
4794 const LValue *ResultSlot) {
4795 const Expr *Callee = E->getCallee()->IgnoreParens();
4796 QualType CalleeType = Callee->getType();
4798 const FunctionDecl *FD = nullptr;
4799 LValue *This = nullptr, ThisVal;
4800 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4801 bool HasQualifier = false;
4803 // Extract function decl and 'this' pointer from the callee.
4804 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4805 const ValueDecl *Member = nullptr;
4806 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4807 // Explicit bound member calls, such as x.f() or p->g();
4808 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4810 Member = ME->getMemberDecl();
4812 HasQualifier = ME->hasQualifier();
4813 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4814 // Indirect bound member calls ('.*' or '->*').
4815 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4816 if (!Member) return false;
4819 return Error(Callee);
4821 FD = dyn_cast<FunctionDecl>(Member);
4823 return Error(Callee);
4824 } else if (CalleeType->isFunctionPointerType()) {
4826 if (!EvaluatePointer(Callee, Call, Info))
4829 if (!Call.getLValueOffset().isZero())
4830 return Error(Callee);
4831 FD = dyn_cast_or_null<FunctionDecl>(
4832 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4834 return Error(Callee);
4835 // Don't call function pointers which have been cast to some other type.
4836 // Per DR (no number yet), the caller and callee can differ in noexcept.
4837 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4838 CalleeType->getPointeeType(), FD->getType())) {
4842 // Overloaded operator calls to member functions are represented as normal
4843 // calls with '*this' as the first argument.
4844 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4845 if (MD && !MD->isStatic()) {
4846 // FIXME: When selecting an implicit conversion for an overloaded
4847 // operator delete, we sometimes try to evaluate calls to conversion
4848 // operators without a 'this' parameter!
4852 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4855 Args = Args.slice(1);
4856 } else if (MD && MD->isLambdaStaticInvoker()) {
4857 // Map the static invoker for the lambda back to the call operator.
4858 // Conveniently, we don't have to slice out the 'this' argument (as is
4859 // being done for the non-static case), since a static member function
4860 // doesn't have an implicit argument passed in.
4861 const CXXRecordDecl *ClosureClass = MD->getParent();
4863 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4864 "Number of captures must be zero for conversion to function-ptr");
4866 const CXXMethodDecl *LambdaCallOp =
4867 ClosureClass->getLambdaCallOperator();
4869 // Set 'FD', the function that will be called below, to the call
4870 // operator. If the closure object represents a generic lambda, find
4871 // the corresponding specialization of the call operator.
4873 if (ClosureClass->isGenericLambda()) {
4874 assert(MD->isFunctionTemplateSpecialization() &&
4875 "A generic lambda's static-invoker function must be a "
4876 "template specialization");
4877 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4878 FunctionTemplateDecl *CallOpTemplate =
4879 LambdaCallOp->getDescribedFunctionTemplate();
4880 void *InsertPos = nullptr;
4881 FunctionDecl *CorrespondingCallOpSpecialization =
4882 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4883 assert(CorrespondingCallOpSpecialization &&
4884 "We must always have a function call operator specialization "
4885 "that corresponds to our static invoker specialization");
4886 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4895 if (This && !This->checkSubobject(Info, E, CSK_This))
4898 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4899 // calls to such functions in constant expressions.
4900 if (This && !HasQualifier &&
4901 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4902 return Error(E, diag::note_constexpr_virtual_call);
4904 const FunctionDecl *Definition = nullptr;
4905 Stmt *Body = FD->getBody(Definition);
4907 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4908 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4909 Result, ResultSlot))
4915 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4916 return StmtVisitorTy::Visit(E->getInitializer());
4918 bool VisitInitListExpr(const InitListExpr *E) {
4919 if (E->getNumInits() == 0)
4920 return DerivedZeroInitialization(E);
4921 if (E->getNumInits() == 1)
4922 return StmtVisitorTy::Visit(E->getInit(0));
4925 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4926 return DerivedZeroInitialization(E);
4928 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4929 return DerivedZeroInitialization(E);
4931 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4932 return DerivedZeroInitialization(E);
4935 /// A member expression where the object is a prvalue is itself a prvalue.
4936 bool VisitMemberExpr(const MemberExpr *E) {
4937 assert(!E->isArrow() && "missing call to bound member function?");
4940 if (!Evaluate(Val, Info, E->getBase()))
4943 QualType BaseTy = E->getBase()->getType();
4945 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4946 if (!FD) return Error(E);
4947 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4948 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4949 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4951 CompleteObject Obj(&Val, BaseTy, true);
4952 SubobjectDesignator Designator(BaseTy);
4953 Designator.addDeclUnchecked(FD);
4956 return extractSubobject(Info, E, Obj, Designator, Result) &&
4957 DerivedSuccess(Result, E);
4960 bool VisitCastExpr(const CastExpr *E) {
4961 switch (E->getCastKind()) {
4965 case CK_AtomicToNonAtomic: {
4967 // This does not need to be done in place even for class/array types:
4968 // atomic-to-non-atomic conversion implies copying the object
4970 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4972 return DerivedSuccess(AtomicVal, E);
4976 case CK_UserDefinedConversion:
4977 return StmtVisitorTy::Visit(E->getSubExpr());
4979 case CK_LValueToRValue: {
4981 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4984 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4985 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4988 return DerivedSuccess(RVal, E);
4995 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4996 return VisitUnaryPostIncDec(UO);
4998 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4999 return VisitUnaryPostIncDec(UO);
5001 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5002 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5006 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5009 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5010 UO->isIncrementOp(), &RVal))
5012 return DerivedSuccess(RVal, UO);
5015 bool VisitStmtExpr(const StmtExpr *E) {
5016 // We will have checked the full-expressions inside the statement expression
5017 // when they were completed, and don't need to check them again now.
5018 if (Info.checkingForOverflow())
5021 BlockScopeRAII Scope(Info);
5022 const CompoundStmt *CS = E->getSubStmt();
5023 if (CS->body_empty())
5026 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5027 BE = CS->body_end();
5030 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5032 Info.FFDiag((*BI)->getLocStart(),
5033 diag::note_constexpr_stmt_expr_unsupported);
5036 return this->Visit(FinalExpr);
5039 APValue ReturnValue;
5040 StmtResult Result = { ReturnValue, nullptr };
5041 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5042 if (ESR != ESR_Succeeded) {
5043 // FIXME: If the statement-expression terminated due to 'return',
5044 // 'break', or 'continue', it would be nice to propagate that to
5045 // the outer statement evaluation rather than bailing out.
5046 if (ESR != ESR_Failed)
5047 Info.FFDiag((*BI)->getLocStart(),
5048 diag::note_constexpr_stmt_expr_unsupported);
5053 llvm_unreachable("Return from function from the loop above.");
5056 /// Visit a value which is evaluated, but whose value is ignored.
5057 void VisitIgnoredValue(const Expr *E) {
5058 EvaluateIgnoredValue(Info, E);
5061 /// Potentially visit a MemberExpr's base expression.
5062 void VisitIgnoredBaseExpression(const Expr *E) {
5063 // While MSVC doesn't evaluate the base expression, it does diagnose the
5064 // presence of side-effecting behavior.
5065 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5067 VisitIgnoredValue(E);
5073 //===----------------------------------------------------------------------===//
5074 // Common base class for lvalue and temporary evaluation.
5075 //===----------------------------------------------------------------------===//
5077 template<class Derived>
5078 class LValueExprEvaluatorBase
5079 : public ExprEvaluatorBase<Derived> {
5083 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5084 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5086 bool Success(APValue::LValueBase B) {
5091 bool evaluatePointer(const Expr *E, LValue &Result) {
5092 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5096 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5097 : ExprEvaluatorBaseTy(Info), Result(Result),
5098 InvalidBaseOK(InvalidBaseOK) {}
5100 bool Success(const APValue &V, const Expr *E) {
5101 Result.setFrom(this->Info.Ctx, V);
5105 bool VisitMemberExpr(const MemberExpr *E) {
5106 // Handle non-static data members.
5110 EvalOK = evaluatePointer(E->getBase(), Result);
5111 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5112 } else if (E->getBase()->isRValue()) {
5113 assert(E->getBase()->getType()->isRecordType());
5114 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5115 BaseTy = E->getBase()->getType();
5117 EvalOK = this->Visit(E->getBase());
5118 BaseTy = E->getBase()->getType();
5123 Result.setInvalid(E);
5127 const ValueDecl *MD = E->getMemberDecl();
5128 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5129 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5130 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5132 if (!HandleLValueMember(this->Info, E, Result, FD))
5134 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5135 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5138 return this->Error(E);
5140 if (MD->getType()->isReferenceType()) {
5142 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5145 return Success(RefValue, E);
5150 bool VisitBinaryOperator(const BinaryOperator *E) {
5151 switch (E->getOpcode()) {
5153 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5157 return HandleMemberPointerAccess(this->Info, E, Result);
5161 bool VisitCastExpr(const CastExpr *E) {
5162 switch (E->getCastKind()) {
5164 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5166 case CK_DerivedToBase:
5167 case CK_UncheckedDerivedToBase:
5168 if (!this->Visit(E->getSubExpr()))
5171 // Now figure out the necessary offset to add to the base LV to get from
5172 // the derived class to the base class.
5173 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5180 //===----------------------------------------------------------------------===//
5181 // LValue Evaluation
5183 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5184 // function designators (in C), decl references to void objects (in C), and
5185 // temporaries (if building with -Wno-address-of-temporary).
5187 // LValue evaluation produces values comprising a base expression of one of the
5193 // * CompoundLiteralExpr in C (and in global scope in C++)
5197 // * ObjCStringLiteralExpr
5201 // * CallExpr for a MakeStringConstant builtin
5202 // - Locals and temporaries
5203 // * MaterializeTemporaryExpr
5204 // * Any Expr, with a CallIndex indicating the function in which the temporary
5205 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5206 // from the AST (FIXME).
5207 // * A MaterializeTemporaryExpr that has static storage duration, with no
5208 // CallIndex, for a lifetime-extended temporary.
5209 // plus an offset in bytes.
5210 //===----------------------------------------------------------------------===//
5212 class LValueExprEvaluator
5213 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5215 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5216 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5218 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5219 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5221 bool VisitDeclRefExpr(const DeclRefExpr *E);
5222 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5223 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5224 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5225 bool VisitMemberExpr(const MemberExpr *E);
5226 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5227 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5228 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5229 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5230 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5231 bool VisitUnaryDeref(const UnaryOperator *E);
5232 bool VisitUnaryReal(const UnaryOperator *E);
5233 bool VisitUnaryImag(const UnaryOperator *E);
5234 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5235 return VisitUnaryPreIncDec(UO);
5237 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5238 return VisitUnaryPreIncDec(UO);
5240 bool VisitBinAssign(const BinaryOperator *BO);
5241 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5243 bool VisitCastExpr(const CastExpr *E) {
5244 switch (E->getCastKind()) {
5246 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5248 case CK_LValueBitCast:
5249 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5250 if (!Visit(E->getSubExpr()))
5252 Result.Designator.setInvalid();
5255 case CK_BaseToDerived:
5256 if (!Visit(E->getSubExpr()))
5258 return HandleBaseToDerivedCast(Info, E, Result);
5262 } // end anonymous namespace
5264 /// Evaluate an expression as an lvalue. This can be legitimately called on
5265 /// expressions which are not glvalues, in three cases:
5266 /// * function designators in C, and
5267 /// * "extern void" objects
5268 /// * @selector() expressions in Objective-C
5269 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5270 bool InvalidBaseOK) {
5271 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5272 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5273 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5276 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5277 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5279 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5280 return VisitVarDecl(E, VD);
5281 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5282 return Visit(BD->getBinding());
5287 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5289 // If we are within a lambda's call operator, check whether the 'VD' referred
5290 // to within 'E' actually represents a lambda-capture that maps to a
5291 // data-member/field within the closure object, and if so, evaluate to the
5292 // field or what the field refers to.
5293 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5294 isa<DeclRefExpr>(E) &&
5295 cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5296 // We don't always have a complete capture-map when checking or inferring if
5297 // the function call operator meets the requirements of a constexpr function
5298 // - but we don't need to evaluate the captures to determine constexprness
5299 // (dcl.constexpr C++17).
5300 if (Info.checkingPotentialConstantExpression())
5303 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5304 // Start with 'Result' referring to the complete closure object...
5305 Result = *Info.CurrentCall->This;
5306 // ... then update it to refer to the field of the closure object
5307 // that represents the capture.
5308 if (!HandleLValueMember(Info, E, Result, FD))
5310 // And if the field is of reference type, update 'Result' to refer to what
5311 // the field refers to.
5312 if (FD->getType()->isReferenceType()) {
5314 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5317 Result.setFrom(Info.Ctx, RVal);
5322 CallStackFrame *Frame = nullptr;
5323 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5324 // Only if a local variable was declared in the function currently being
5325 // evaluated, do we expect to be able to find its value in the current
5326 // frame. (Otherwise it was likely declared in an enclosing context and
5327 // could either have a valid evaluatable value (for e.g. a constexpr
5328 // variable) or be ill-formed (and trigger an appropriate evaluation
5330 if (Info.CurrentCall->Callee &&
5331 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5332 Frame = Info.CurrentCall;
5336 if (!VD->getType()->isReferenceType()) {
5338 Result.set({VD, Frame->Index,
5339 Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5346 if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5348 if (V->isUninit()) {
5349 if (!Info.checkingPotentialConstantExpression())
5350 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5353 return Success(*V, E);
5356 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5357 const MaterializeTemporaryExpr *E) {
5358 // Walk through the expression to find the materialized temporary itself.
5359 SmallVector<const Expr *, 2> CommaLHSs;
5360 SmallVector<SubobjectAdjustment, 2> Adjustments;
5361 const Expr *Inner = E->GetTemporaryExpr()->
5362 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5364 // If we passed any comma operators, evaluate their LHSs.
5365 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5366 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5369 // A materialized temporary with static storage duration can appear within the
5370 // result of a constant expression evaluation, so we need to preserve its
5371 // value for use outside this evaluation.
5373 if (E->getStorageDuration() == SD_Static) {
5374 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5378 Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5382 QualType Type = Inner->getType();
5384 // Materialize the temporary itself.
5385 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5386 (E->getStorageDuration() == SD_Static &&
5387 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5392 // Adjust our lvalue to refer to the desired subobject.
5393 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5395 switch (Adjustments[I].Kind) {
5396 case SubobjectAdjustment::DerivedToBaseAdjustment:
5397 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5400 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5403 case SubobjectAdjustment::FieldAdjustment:
5404 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5406 Type = Adjustments[I].Field->getType();
5409 case SubobjectAdjustment::MemberPointerAdjustment:
5410 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5411 Adjustments[I].Ptr.RHS))
5413 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5422 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5423 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5424 "lvalue compound literal in c++?");
5425 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5426 // only see this when folding in C, so there's no standard to follow here.
5430 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5431 if (!E->isPotentiallyEvaluated())
5434 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5435 << E->getExprOperand()->getType()
5436 << E->getExprOperand()->getSourceRange();
5440 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5444 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5445 // Handle static data members.
5446 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5447 VisitIgnoredBaseExpression(E->getBase());
5448 return VisitVarDecl(E, VD);
5451 // Handle static member functions.
5452 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5453 if (MD->isStatic()) {
5454 VisitIgnoredBaseExpression(E->getBase());
5459 // Handle non-static data members.
5460 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5463 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5464 // FIXME: Deal with vectors as array subscript bases.
5465 if (E->getBase()->getType()->isVectorType())
5468 bool Success = true;
5469 if (!evaluatePointer(E->getBase(), Result)) {
5470 if (!Info.noteFailure())
5476 if (!EvaluateInteger(E->getIdx(), Index, Info))
5480 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5483 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5484 return evaluatePointer(E->getSubExpr(), Result);
5487 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5488 if (!Visit(E->getSubExpr()))
5490 // __real is a no-op on scalar lvalues.
5491 if (E->getSubExpr()->getType()->isAnyComplexType())
5492 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5496 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5497 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5498 "lvalue __imag__ on scalar?");
5499 if (!Visit(E->getSubExpr()))
5501 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5505 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5506 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5509 if (!this->Visit(UO->getSubExpr()))
5512 return handleIncDec(
5513 this->Info, UO, Result, UO->getSubExpr()->getType(),
5514 UO->isIncrementOp(), nullptr);
5517 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5518 const CompoundAssignOperator *CAO) {
5519 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5524 // The overall lvalue result is the result of evaluating the LHS.
5525 if (!this->Visit(CAO->getLHS())) {
5526 if (Info.noteFailure())
5527 Evaluate(RHS, this->Info, CAO->getRHS());
5531 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5534 return handleCompoundAssignment(
5536 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5537 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5540 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5541 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5546 if (!this->Visit(E->getLHS())) {
5547 if (Info.noteFailure())
5548 Evaluate(NewVal, this->Info, E->getRHS());
5552 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5555 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5559 //===----------------------------------------------------------------------===//
5560 // Pointer Evaluation
5561 //===----------------------------------------------------------------------===//
5563 /// Attempts to compute the number of bytes available at the pointer
5564 /// returned by a function with the alloc_size attribute. Returns true if we
5565 /// were successful. Places an unsigned number into `Result`.
5567 /// This expects the given CallExpr to be a call to a function with an
5568 /// alloc_size attribute.
5569 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5570 const CallExpr *Call,
5571 llvm::APInt &Result) {
5572 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5574 assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5575 unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5576 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5577 if (Call->getNumArgs() <= SizeArgNo)
5580 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5581 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5583 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5585 Into = Into.zextOrSelf(BitsInSizeT);
5590 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5593 if (!AllocSize->getNumElemsParam().isValid()) {
5594 Result = std::move(SizeOfElem);
5598 APSInt NumberOfElems;
5599 unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5600 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5604 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5608 Result = std::move(BytesAvailable);
5612 /// Convenience function. LVal's base must be a call to an alloc_size
5614 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5616 llvm::APInt &Result) {
5617 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5618 "Can't get the size of a non alloc_size function");
5619 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5620 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5621 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5624 /// Attempts to evaluate the given LValueBase as the result of a call to
5625 /// a function with the alloc_size attribute. If it was possible to do so, this
5626 /// function will return true, make Result's Base point to said function call,
5627 /// and mark Result's Base as invalid.
5628 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5633 // Because we do no form of static analysis, we only support const variables.
5635 // Additionally, we can't support parameters, nor can we support static
5636 // variables (in the latter case, use-before-assign isn't UB; in the former,
5637 // we have no clue what they'll be assigned to).
5639 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5640 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5643 const Expr *Init = VD->getAnyInitializer();
5647 const Expr *E = Init->IgnoreParens();
5648 if (!tryUnwrapAllocSizeCall(E))
5651 // Store E instead of E unwrapped so that the type of the LValue's base is
5652 // what the user wanted.
5653 Result.setInvalid(E);
5655 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5656 Result.addUnsizedArray(Info, E, Pointee);
5661 class PointerExprEvaluator
5662 : public ExprEvaluatorBase<PointerExprEvaluator> {
5666 bool Success(const Expr *E) {
5671 bool evaluateLValue(const Expr *E, LValue &Result) {
5672 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5675 bool evaluatePointer(const Expr *E, LValue &Result) {
5676 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5679 bool visitNonBuiltinCallExpr(const CallExpr *E);
5682 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5683 : ExprEvaluatorBaseTy(info), Result(Result),
5684 InvalidBaseOK(InvalidBaseOK) {}
5686 bool Success(const APValue &V, const Expr *E) {
5687 Result.setFrom(Info.Ctx, V);
5690 bool ZeroInitialization(const Expr *E) {
5691 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5692 Result.setNull(E->getType(), TargetVal);
5696 bool VisitBinaryOperator(const BinaryOperator *E);
5697 bool VisitCastExpr(const CastExpr* E);
5698 bool VisitUnaryAddrOf(const UnaryOperator *E);
5699 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5700 { return Success(E); }
5701 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5702 if (Info.noteFailure())
5703 EvaluateIgnoredValue(Info, E->getSubExpr());
5706 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5707 { return Success(E); }
5708 bool VisitCallExpr(const CallExpr *E);
5709 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5710 bool VisitBlockExpr(const BlockExpr *E) {
5711 if (!E->getBlockDecl()->hasCaptures())
5715 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5716 // Can't look at 'this' when checking a potential constant expression.
5717 if (Info.checkingPotentialConstantExpression())
5719 if (!Info.CurrentCall->This) {
5720 if (Info.getLangOpts().CPlusPlus11)
5721 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5726 Result = *Info.CurrentCall->This;
5727 // If we are inside a lambda's call operator, the 'this' expression refers
5728 // to the enclosing '*this' object (either by value or reference) which is
5729 // either copied into the closure object's field that represents the '*this'
5730 // or refers to '*this'.
5731 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5732 // Update 'Result' to refer to the data member/field of the closure object
5733 // that represents the '*this' capture.
5734 if (!HandleLValueMember(Info, E, Result,
5735 Info.CurrentCall->LambdaThisCaptureField))
5737 // If we captured '*this' by reference, replace the field with its referent.
5738 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5739 ->isPointerType()) {
5741 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5745 Result.setFrom(Info.Ctx, RVal);
5751 // FIXME: Missing: @protocol, @selector
5753 } // end anonymous namespace
5755 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5756 bool InvalidBaseOK) {
5757 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5758 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5761 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5762 if (E->getOpcode() != BO_Add &&
5763 E->getOpcode() != BO_Sub)
5764 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5766 const Expr *PExp = E->getLHS();
5767 const Expr *IExp = E->getRHS();
5768 if (IExp->getType()->isPointerType())
5769 std::swap(PExp, IExp);
5771 bool EvalPtrOK = evaluatePointer(PExp, Result);
5772 if (!EvalPtrOK && !Info.noteFailure())
5775 llvm::APSInt Offset;
5776 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5779 if (E->getOpcode() == BO_Sub)
5780 negateAsSigned(Offset);
5782 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5783 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5786 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5787 return evaluateLValue(E->getSubExpr(), Result);
5790 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5791 const Expr *SubExpr = E->getSubExpr();
5793 switch (E->getCastKind()) {
5798 case CK_CPointerToObjCPointerCast:
5799 case CK_BlockPointerToObjCPointerCast:
5800 case CK_AnyPointerToBlockPointerCast:
5801 case CK_AddressSpaceConversion:
5802 if (!Visit(SubExpr))
5804 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5805 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5806 // also static_casts, but we disallow them as a resolution to DR1312.
5807 if (!E->getType()->isVoidPointerType()) {
5808 // If we changed anything other than cvr-qualifiers, we can't use this
5809 // value for constant folding. FIXME: Qualification conversions should
5810 // always be CK_NoOp, but we get this wrong in C.
5811 if (!Info.Ctx.hasCvrSimilarType(E->getType(), E->getSubExpr()->getType()))
5812 Result.Designator.setInvalid();
5813 if (SubExpr->getType()->isVoidPointerType())
5814 CCEDiag(E, diag::note_constexpr_invalid_cast)
5815 << 3 << SubExpr->getType();
5817 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5819 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5820 ZeroInitialization(E);
5823 case CK_DerivedToBase:
5824 case CK_UncheckedDerivedToBase:
5825 if (!evaluatePointer(E->getSubExpr(), Result))
5827 if (!Result.Base && Result.Offset.isZero())
5830 // Now figure out the necessary offset to add to the base LV to get from
5831 // the derived class to the base class.
5832 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5833 castAs<PointerType>()->getPointeeType(),
5836 case CK_BaseToDerived:
5837 if (!Visit(E->getSubExpr()))
5839 if (!Result.Base && Result.Offset.isZero())
5841 return HandleBaseToDerivedCast(Info, E, Result);
5843 case CK_NullToPointer:
5844 VisitIgnoredValue(E->getSubExpr());
5845 return ZeroInitialization(E);
5847 case CK_IntegralToPointer: {
5848 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5851 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5854 if (Value.isInt()) {
5855 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5856 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5857 Result.Base = (Expr*)nullptr;
5858 Result.InvalidBase = false;
5859 Result.Offset = CharUnits::fromQuantity(N);
5860 Result.Designator.setInvalid();
5861 Result.IsNullPtr = false;
5864 // Cast is of an lvalue, no need to change value.
5865 Result.setFrom(Info.Ctx, Value);
5870 case CK_ArrayToPointerDecay: {
5871 if (SubExpr->isGLValue()) {
5872 if (!evaluateLValue(SubExpr, Result))
5875 APValue &Value = createTemporary(SubExpr, false, Result,
5877 if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5880 // The result is a pointer to the first element of the array.
5881 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5882 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5883 Result.addArray(Info, E, CAT);
5885 Result.addUnsizedArray(Info, E, AT->getElementType());
5889 case CK_FunctionToPointerDecay:
5890 return evaluateLValue(SubExpr, Result);
5892 case CK_LValueToRValue: {
5894 if (!evaluateLValue(E->getSubExpr(), LVal))
5898 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5899 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5901 return InvalidBaseOK &&
5902 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5903 return Success(RVal, E);
5907 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5910 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5911 // C++ [expr.alignof]p3:
5912 // When alignof is applied to a reference type, the result is the
5913 // alignment of the referenced type.
5914 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5915 T = Ref->getPointeeType();
5917 // __alignof is defined to return the preferred alignment.
5918 if (T.getQualifiers().hasUnaligned())
5919 return CharUnits::One();
5920 return Info.Ctx.toCharUnitsFromBits(
5921 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5924 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5925 E = E->IgnoreParens();
5927 // The kinds of expressions that we have special-case logic here for
5928 // should be kept up to date with the special checks for those
5929 // expressions in Sema.
5931 // alignof decl is always accepted, even if it doesn't make sense: we default
5932 // to 1 in those cases.
5933 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5934 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5935 /*RefAsPointee*/true);
5937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5938 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5939 /*RefAsPointee*/true);
5941 return GetAlignOfType(Info, E->getType());
5944 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5945 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5946 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5949 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5952 Result.setInvalid(E);
5953 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5954 Result.addUnsizedArray(Info, E, PointeeTy);
5958 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5959 if (IsStringLiteralCall(E))
5962 if (unsigned BuiltinOp = E->getBuiltinCallee())
5963 return VisitBuiltinCallExpr(E, BuiltinOp);
5965 return visitNonBuiltinCallExpr(E);
5968 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5969 unsigned BuiltinOp) {
5970 switch (BuiltinOp) {
5971 case Builtin::BI__builtin_addressof:
5972 return evaluateLValue(E->getArg(0), Result);
5973 case Builtin::BI__builtin_assume_aligned: {
5974 // We need to be very careful here because: if the pointer does not have the
5975 // asserted alignment, then the behavior is undefined, and undefined
5976 // behavior is non-constant.
5977 if (!evaluatePointer(E->getArg(0), Result))
5980 LValue OffsetResult(Result);
5982 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5984 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5986 if (E->getNumArgs() > 2) {
5988 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5991 int64_t AdditionalOffset = -Offset.getZExtValue();
5992 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5995 // If there is a base object, then it must have the correct alignment.
5996 if (OffsetResult.Base) {
5997 CharUnits BaseAlignment;
5998 if (const ValueDecl *VD =
5999 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6000 BaseAlignment = Info.Ctx.getDeclAlign(VD);
6003 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
6006 if (BaseAlignment < Align) {
6007 Result.Designator.setInvalid();
6008 // FIXME: Add support to Diagnostic for long / long long.
6009 CCEDiag(E->getArg(0),
6010 diag::note_constexpr_baa_insufficient_alignment) << 0
6011 << (unsigned)BaseAlignment.getQuantity()
6012 << (unsigned)Align.getQuantity();
6017 // The offset must also have the correct alignment.
6018 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6019 Result.Designator.setInvalid();
6022 ? CCEDiag(E->getArg(0),
6023 diag::note_constexpr_baa_insufficient_alignment) << 1
6024 : CCEDiag(E->getArg(0),
6025 diag::note_constexpr_baa_value_insufficient_alignment))
6026 << (int)OffsetResult.Offset.getQuantity()
6027 << (unsigned)Align.getQuantity();
6034 case Builtin::BIstrchr:
6035 case Builtin::BIwcschr:
6036 case Builtin::BImemchr:
6037 case Builtin::BIwmemchr:
6038 if (Info.getLangOpts().CPlusPlus11)
6039 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6040 << /*isConstexpr*/0 << /*isConstructor*/0
6041 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6043 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6045 case Builtin::BI__builtin_strchr:
6046 case Builtin::BI__builtin_wcschr:
6047 case Builtin::BI__builtin_memchr:
6048 case Builtin::BI__builtin_char_memchr:
6049 case Builtin::BI__builtin_wmemchr: {
6050 if (!Visit(E->getArg(0)))
6053 if (!EvaluateInteger(E->getArg(1), Desired, Info))
6055 uint64_t MaxLength = uint64_t(-1);
6056 if (BuiltinOp != Builtin::BIstrchr &&
6057 BuiltinOp != Builtin::BIwcschr &&
6058 BuiltinOp != Builtin::BI__builtin_strchr &&
6059 BuiltinOp != Builtin::BI__builtin_wcschr) {
6061 if (!EvaluateInteger(E->getArg(2), N, Info))
6063 MaxLength = N.getExtValue();
6066 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6068 // Figure out what value we're actually looking for (after converting to
6069 // the corresponding unsigned type if necessary).
6070 uint64_t DesiredVal;
6071 bool StopAtNull = false;
6072 switch (BuiltinOp) {
6073 case Builtin::BIstrchr:
6074 case Builtin::BI__builtin_strchr:
6075 // strchr compares directly to the passed integer, and therefore
6076 // always fails if given an int that is not a char.
6077 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6078 E->getArg(1)->getType(),
6081 return ZeroInitialization(E);
6084 case Builtin::BImemchr:
6085 case Builtin::BI__builtin_memchr:
6086 case Builtin::BI__builtin_char_memchr:
6087 // memchr compares by converting both sides to unsigned char. That's also
6088 // correct for strchr if we get this far (to cope with plain char being
6089 // unsigned in the strchr case).
6090 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6093 case Builtin::BIwcschr:
6094 case Builtin::BI__builtin_wcschr:
6097 case Builtin::BIwmemchr:
6098 case Builtin::BI__builtin_wmemchr:
6099 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6100 DesiredVal = Desired.getZExtValue();
6104 for (; MaxLength; --MaxLength) {
6106 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6109 if (Char.getInt().getZExtValue() == DesiredVal)
6111 if (StopAtNull && !Char.getInt())
6113 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6116 // Not found: return nullptr.
6117 return ZeroInitialization(E);
6121 return visitNonBuiltinCallExpr(E);
6125 //===----------------------------------------------------------------------===//
6126 // Member Pointer Evaluation
6127 //===----------------------------------------------------------------------===//
6130 class MemberPointerExprEvaluator
6131 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6134 bool Success(const ValueDecl *D) {
6135 Result = MemberPtr(D);
6140 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6141 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6143 bool Success(const APValue &V, const Expr *E) {
6147 bool ZeroInitialization(const Expr *E) {
6148 return Success((const ValueDecl*)nullptr);
6151 bool VisitCastExpr(const CastExpr *E);
6152 bool VisitUnaryAddrOf(const UnaryOperator *E);
6154 } // end anonymous namespace
6156 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6158 assert(E->isRValue() && E->getType()->isMemberPointerType());
6159 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6162 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6163 switch (E->getCastKind()) {
6165 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6167 case CK_NullToMemberPointer:
6168 VisitIgnoredValue(E->getSubExpr());
6169 return ZeroInitialization(E);
6171 case CK_BaseToDerivedMemberPointer: {
6172 if (!Visit(E->getSubExpr()))
6174 if (E->path_empty())
6176 // Base-to-derived member pointer casts store the path in derived-to-base
6177 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6178 // the wrong end of the derived->base arc, so stagger the path by one class.
6179 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6180 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6181 PathI != PathE; ++PathI) {
6182 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6183 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6184 if (!Result.castToDerived(Derived))
6187 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6188 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6193 case CK_DerivedToBaseMemberPointer:
6194 if (!Visit(E->getSubExpr()))
6196 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6197 PathE = E->path_end(); PathI != PathE; ++PathI) {
6198 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6199 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6200 if (!Result.castToBase(Base))
6207 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6208 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6209 // member can be formed.
6210 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6213 //===----------------------------------------------------------------------===//
6214 // Record Evaluation
6215 //===----------------------------------------------------------------------===//
6218 class RecordExprEvaluator
6219 : public ExprEvaluatorBase<RecordExprEvaluator> {
6224 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6225 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6227 bool Success(const APValue &V, const Expr *E) {
6231 bool ZeroInitialization(const Expr *E) {
6232 return ZeroInitialization(E, E->getType());
6234 bool ZeroInitialization(const Expr *E, QualType T);
6236 bool VisitCallExpr(const CallExpr *E) {
6237 return handleCallExpr(E, Result, &This);
6239 bool VisitCastExpr(const CastExpr *E);
6240 bool VisitInitListExpr(const InitListExpr *E);
6241 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6242 return VisitCXXConstructExpr(E, E->getType());
6244 bool VisitLambdaExpr(const LambdaExpr *E);
6245 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6246 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6247 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6249 bool VisitBinCmp(const BinaryOperator *E);
6253 /// Perform zero-initialization on an object of non-union class type.
6254 /// C++11 [dcl.init]p5:
6255 /// To zero-initialize an object or reference of type T means:
6257 /// -- if T is a (possibly cv-qualified) non-union class type,
6258 /// each non-static data member and each base-class subobject is
6259 /// zero-initialized
6260 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6261 const RecordDecl *RD,
6262 const LValue &This, APValue &Result) {
6263 assert(!RD->isUnion() && "Expected non-union class type");
6264 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6265 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6266 std::distance(RD->field_begin(), RD->field_end()));
6268 if (RD->isInvalidDecl()) return false;
6269 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6273 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6274 End = CD->bases_end(); I != End; ++I, ++Index) {
6275 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6276 LValue Subobject = This;
6277 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6279 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6280 Result.getStructBase(Index)))
6285 for (const auto *I : RD->fields()) {
6286 // -- if T is a reference type, no initialization is performed.
6287 if (I->getType()->isReferenceType())
6290 LValue Subobject = This;
6291 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6294 ImplicitValueInitExpr VIE(I->getType());
6295 if (!EvaluateInPlace(
6296 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6303 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6304 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6305 if (RD->isInvalidDecl()) return false;
6306 if (RD->isUnion()) {
6307 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6308 // object's first non-static named data member is zero-initialized
6309 RecordDecl::field_iterator I = RD->field_begin();
6310 if (I == RD->field_end()) {
6311 Result = APValue((const FieldDecl*)nullptr);
6315 LValue Subobject = This;
6316 if (!HandleLValueMember(Info, E, Subobject, *I))
6318 Result = APValue(*I);
6319 ImplicitValueInitExpr VIE(I->getType());
6320 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6323 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6324 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6328 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6331 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6332 switch (E->getCastKind()) {
6334 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6336 case CK_ConstructorConversion:
6337 return Visit(E->getSubExpr());
6339 case CK_DerivedToBase:
6340 case CK_UncheckedDerivedToBase: {
6341 APValue DerivedObject;
6342 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6344 if (!DerivedObject.isStruct())
6345 return Error(E->getSubExpr());
6347 // Derived-to-base rvalue conversion: just slice off the derived part.
6348 APValue *Value = &DerivedObject;
6349 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6350 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6351 PathE = E->path_end(); PathI != PathE; ++PathI) {
6352 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6353 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6354 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6363 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6364 if (E->isTransparent())
6365 return Visit(E->getInit(0));
6367 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6368 if (RD->isInvalidDecl()) return false;
6369 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6371 if (RD->isUnion()) {
6372 const FieldDecl *Field = E->getInitializedFieldInUnion();
6373 Result = APValue(Field);
6377 // If the initializer list for a union does not contain any elements, the
6378 // first element of the union is value-initialized.
6379 // FIXME: The element should be initialized from an initializer list.
6380 // Is this difference ever observable for initializer lists which
6382 ImplicitValueInitExpr VIE(Field->getType());
6383 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6385 LValue Subobject = This;
6386 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6389 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6390 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6391 isa<CXXDefaultInitExpr>(InitExpr));
6393 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6396 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6397 if (Result.isUninit())
6398 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6399 std::distance(RD->field_begin(), RD->field_end()));
6400 unsigned ElementNo = 0;
6401 bool Success = true;
6403 // Initialize base classes.
6405 for (const auto &Base : CXXRD->bases()) {
6406 assert(ElementNo < E->getNumInits() && "missing init for base class");
6407 const Expr *Init = E->getInit(ElementNo);
6409 LValue Subobject = This;
6410 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6413 APValue &FieldVal = Result.getStructBase(ElementNo);
6414 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6415 if (!Info.noteFailure())
6423 // Initialize members.
6424 for (const auto *Field : RD->fields()) {
6425 // Anonymous bit-fields are not considered members of the class for
6426 // purposes of aggregate initialization.
6427 if (Field->isUnnamedBitfield())
6430 LValue Subobject = This;
6432 bool HaveInit = ElementNo < E->getNumInits();
6434 // FIXME: Diagnostics here should point to the end of the initializer
6435 // list, not the start.
6436 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6437 Subobject, Field, &Layout))
6440 // Perform an implicit value-initialization for members beyond the end of
6441 // the initializer list.
6442 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6443 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6445 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6446 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6447 isa<CXXDefaultInitExpr>(Init));
6449 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6450 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6451 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6452 FieldVal, Field))) {
6453 if (!Info.noteFailure())
6462 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6464 // Note that E's type is not necessarily the type of our class here; we might
6465 // be initializing an array element instead.
6466 const CXXConstructorDecl *FD = E->getConstructor();
6467 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6469 bool ZeroInit = E->requiresZeroInitialization();
6470 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6471 // If we've already performed zero-initialization, we're already done.
6472 if (!Result.isUninit())
6475 // We can get here in two different ways:
6476 // 1) We're performing value-initialization, and should zero-initialize
6478 // 2) We're performing default-initialization of an object with a trivial
6479 // constexpr default constructor, in which case we should start the
6480 // lifetimes of all the base subobjects (there can be no data member
6481 // subobjects in this case) per [basic.life]p1.
6482 // Either way, ZeroInitialization is appropriate.
6483 return ZeroInitialization(E, T);
6486 const FunctionDecl *Definition = nullptr;
6487 auto Body = FD->getBody(Definition);
6489 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6492 // Avoid materializing a temporary for an elidable copy/move constructor.
6493 if (E->isElidable() && !ZeroInit)
6494 if (const MaterializeTemporaryExpr *ME
6495 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6496 return Visit(ME->GetTemporaryExpr());
6498 if (ZeroInit && !ZeroInitialization(E, T))
6501 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6502 return HandleConstructorCall(E, This, Args,
6503 cast<CXXConstructorDecl>(Definition), Info,
6507 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6508 const CXXInheritedCtorInitExpr *E) {
6509 if (!Info.CurrentCall) {
6510 assert(Info.checkingPotentialConstantExpression());
6514 const CXXConstructorDecl *FD = E->getConstructor();
6515 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6518 const FunctionDecl *Definition = nullptr;
6519 auto Body = FD->getBody(Definition);
6521 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6524 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6525 cast<CXXConstructorDecl>(Definition), Info,
6529 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6530 const CXXStdInitializerListExpr *E) {
6531 const ConstantArrayType *ArrayType =
6532 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6535 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6538 // Get a pointer to the first element of the array.
6539 Array.addArray(Info, E, ArrayType);
6541 // FIXME: Perform the checks on the field types in SemaInit.
6542 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6543 RecordDecl::field_iterator Field = Record->field_begin();
6544 if (Field == Record->field_end())
6548 if (!Field->getType()->isPointerType() ||
6549 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6550 ArrayType->getElementType()))
6553 // FIXME: What if the initializer_list type has base classes, etc?
6554 Result = APValue(APValue::UninitStruct(), 0, 2);
6555 Array.moveInto(Result.getStructField(0));
6557 if (++Field == Record->field_end())
6560 if (Field->getType()->isPointerType() &&
6561 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6562 ArrayType->getElementType())) {
6564 if (!HandleLValueArrayAdjustment(Info, E, Array,
6565 ArrayType->getElementType(),
6566 ArrayType->getSize().getZExtValue()))
6568 Array.moveInto(Result.getStructField(1));
6569 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6571 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6575 if (++Field != Record->field_end())
6581 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6582 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6583 if (ClosureClass->isInvalidDecl()) return false;
6585 if (Info.checkingPotentialConstantExpression()) return true;
6587 const size_t NumFields =
6588 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6590 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6591 E->capture_init_end()) &&
6592 "The number of lambda capture initializers should equal the number of "
6593 "fields within the closure type");
6595 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6596 // Iterate through all the lambda's closure object's fields and initialize
6598 auto *CaptureInitIt = E->capture_init_begin();
6599 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6600 bool Success = true;
6601 for (const auto *Field : ClosureClass->fields()) {
6602 assert(CaptureInitIt != E->capture_init_end());
6603 // Get the initializer for this field
6604 Expr *const CurFieldInit = *CaptureInitIt++;
6606 // If there is no initializer, either this is a VLA or an error has
6611 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6612 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6613 if (!Info.keepEvaluatingAfterFailure())
6622 static bool EvaluateRecord(const Expr *E, const LValue &This,
6623 APValue &Result, EvalInfo &Info) {
6624 assert(E->isRValue() && E->getType()->isRecordType() &&
6625 "can't evaluate expression as a record rvalue");
6626 return RecordExprEvaluator(Info, This, Result).Visit(E);
6629 //===----------------------------------------------------------------------===//
6630 // Temporary Evaluation
6632 // Temporaries are represented in the AST as rvalues, but generally behave like
6633 // lvalues. The full-object of which the temporary is a subobject is implicitly
6634 // materialized so that a reference can bind to it.
6635 //===----------------------------------------------------------------------===//
6637 class TemporaryExprEvaluator
6638 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6640 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6641 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6643 /// Visit an expression which constructs the value of this temporary.
6644 bool VisitConstructExpr(const Expr *E) {
6645 APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6646 return EvaluateInPlace(Value, Info, Result, E);
6649 bool VisitCastExpr(const CastExpr *E) {
6650 switch (E->getCastKind()) {
6652 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6654 case CK_ConstructorConversion:
6655 return VisitConstructExpr(E->getSubExpr());
6658 bool VisitInitListExpr(const InitListExpr *E) {
6659 return VisitConstructExpr(E);
6661 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6662 return VisitConstructExpr(E);
6664 bool VisitCallExpr(const CallExpr *E) {
6665 return VisitConstructExpr(E);
6667 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6668 return VisitConstructExpr(E);
6670 bool VisitLambdaExpr(const LambdaExpr *E) {
6671 return VisitConstructExpr(E);
6674 } // end anonymous namespace
6676 /// Evaluate an expression of record type as a temporary.
6677 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6678 assert(E->isRValue() && E->getType()->isRecordType());
6679 return TemporaryExprEvaluator(Info, Result).Visit(E);
6682 //===----------------------------------------------------------------------===//
6683 // Vector Evaluation
6684 //===----------------------------------------------------------------------===//
6687 class VectorExprEvaluator
6688 : public ExprEvaluatorBase<VectorExprEvaluator> {
6692 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6693 : ExprEvaluatorBaseTy(info), Result(Result) {}
6695 bool Success(ArrayRef<APValue> V, const Expr *E) {
6696 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6697 // FIXME: remove this APValue copy.
6698 Result = APValue(V.data(), V.size());
6701 bool Success(const APValue &V, const Expr *E) {
6702 assert(V.isVector());
6706 bool ZeroInitialization(const Expr *E);
6708 bool VisitUnaryReal(const UnaryOperator *E)
6709 { return Visit(E->getSubExpr()); }
6710 bool VisitCastExpr(const CastExpr* E);
6711 bool VisitInitListExpr(const InitListExpr *E);
6712 bool VisitUnaryImag(const UnaryOperator *E);
6713 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6714 // binary comparisons, binary and/or/xor,
6715 // shufflevector, ExtVectorElementExpr
6717 } // end anonymous namespace
6719 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6720 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6721 return VectorExprEvaluator(Info, Result).Visit(E);
6724 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6725 const VectorType *VTy = E->getType()->castAs<VectorType>();
6726 unsigned NElts = VTy->getNumElements();
6728 const Expr *SE = E->getSubExpr();
6729 QualType SETy = SE->getType();
6731 switch (E->getCastKind()) {
6732 case CK_VectorSplat: {
6733 APValue Val = APValue();
6734 if (SETy->isIntegerType()) {
6736 if (!EvaluateInteger(SE, IntResult, Info))
6738 Val = APValue(std::move(IntResult));
6739 } else if (SETy->isRealFloatingType()) {
6740 APFloat FloatResult(0.0);
6741 if (!EvaluateFloat(SE, FloatResult, Info))
6743 Val = APValue(std::move(FloatResult));
6748 // Splat and create vector APValue.
6749 SmallVector<APValue, 4> Elts(NElts, Val);
6750 return Success(Elts, E);
6753 // Evaluate the operand into an APInt we can extract from.
6754 llvm::APInt SValInt;
6755 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6757 // Extract the elements
6758 QualType EltTy = VTy->getElementType();
6759 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6760 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6761 SmallVector<APValue, 4> Elts;
6762 if (EltTy->isRealFloatingType()) {
6763 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6764 unsigned FloatEltSize = EltSize;
6765 if (&Sem == &APFloat::x87DoubleExtended())
6767 for (unsigned i = 0; i < NElts; i++) {
6770 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6772 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6773 Elts.push_back(APValue(APFloat(Sem, Elt)));
6775 } else if (EltTy->isIntegerType()) {
6776 for (unsigned i = 0; i < NElts; i++) {
6779 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6781 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6782 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6787 return Success(Elts, E);
6790 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6795 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6796 const VectorType *VT = E->getType()->castAs<VectorType>();
6797 unsigned NumInits = E->getNumInits();
6798 unsigned NumElements = VT->getNumElements();
6800 QualType EltTy = VT->getElementType();
6801 SmallVector<APValue, 4> Elements;
6803 // The number of initializers can be less than the number of
6804 // vector elements. For OpenCL, this can be due to nested vector
6805 // initialization. For GCC compatibility, missing trailing elements
6806 // should be initialized with zeroes.
6807 unsigned CountInits = 0, CountElts = 0;
6808 while (CountElts < NumElements) {
6809 // Handle nested vector initialization.
6810 if (CountInits < NumInits
6811 && E->getInit(CountInits)->getType()->isVectorType()) {
6813 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6815 unsigned vlen = v.getVectorLength();
6816 for (unsigned j = 0; j < vlen; j++)
6817 Elements.push_back(v.getVectorElt(j));
6819 } else if (EltTy->isIntegerType()) {
6820 llvm::APSInt sInt(32);
6821 if (CountInits < NumInits) {
6822 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6824 } else // trailing integer zero.
6825 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6826 Elements.push_back(APValue(sInt));
6829 llvm::APFloat f(0.0);
6830 if (CountInits < NumInits) {
6831 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6833 } else // trailing float zero.
6834 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6835 Elements.push_back(APValue(f));
6840 return Success(Elements, E);
6844 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6845 const VectorType *VT = E->getType()->getAs<VectorType>();
6846 QualType EltTy = VT->getElementType();
6847 APValue ZeroElement;
6848 if (EltTy->isIntegerType())
6849 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6852 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6854 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6855 return Success(Elements, E);
6858 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6859 VisitIgnoredValue(E->getSubExpr());
6860 return ZeroInitialization(E);
6863 //===----------------------------------------------------------------------===//
6865 //===----------------------------------------------------------------------===//
6868 class ArrayExprEvaluator
6869 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6874 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6875 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6877 bool Success(const APValue &V, const Expr *E) {
6878 assert((V.isArray() || V.isLValue()) &&
6879 "expected array or string literal");
6884 bool ZeroInitialization(const Expr *E) {
6885 const ConstantArrayType *CAT =
6886 Info.Ctx.getAsConstantArrayType(E->getType());
6890 Result = APValue(APValue::UninitArray(), 0,
6891 CAT->getSize().getZExtValue());
6892 if (!Result.hasArrayFiller()) return true;
6894 // Zero-initialize all elements.
6895 LValue Subobject = This;
6896 Subobject.addArray(Info, E, CAT);
6897 ImplicitValueInitExpr VIE(CAT->getElementType());
6898 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6901 bool VisitCallExpr(const CallExpr *E) {
6902 return handleCallExpr(E, Result, &This);
6904 bool VisitInitListExpr(const InitListExpr *E);
6905 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6906 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6907 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6908 const LValue &Subobject,
6909 APValue *Value, QualType Type);
6911 } // end anonymous namespace
6913 static bool EvaluateArray(const Expr *E, const LValue &This,
6914 APValue &Result, EvalInfo &Info) {
6915 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6916 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6919 // Return true iff the given array filler may depend on the element index.
6920 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6921 // For now, just whitelist non-class value-initialization and initialization
6922 // lists comprised of them.
6923 if (isa<ImplicitValueInitExpr>(FillerExpr))
6925 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6926 for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6927 if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6935 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6936 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6940 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6941 // an appropriately-typed string literal enclosed in braces.
6942 if (E->isStringLiteralInit()) {
6944 if (!EvaluateLValue(E->getInit(0), LV, Info))
6948 return Success(Val, E);
6951 bool Success = true;
6953 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6954 "zero-initialized array shouldn't have any initialized elts");
6956 if (Result.isArray() && Result.hasArrayFiller())
6957 Filler = Result.getArrayFiller();
6959 unsigned NumEltsToInit = E->getNumInits();
6960 unsigned NumElts = CAT->getSize().getZExtValue();
6961 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6963 // If the initializer might depend on the array index, run it for each
6965 if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
6966 NumEltsToInit = NumElts;
6968 LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
6969 << NumEltsToInit << ".\n");
6971 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6973 // If the array was previously zero-initialized, preserve the
6974 // zero-initialized values.
6975 if (!Filler.isUninit()) {
6976 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6977 Result.getArrayInitializedElt(I) = Filler;
6978 if (Result.hasArrayFiller())
6979 Result.getArrayFiller() = Filler;
6982 LValue Subobject = This;
6983 Subobject.addArray(Info, E, CAT);
6984 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6986 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6987 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6988 Info, Subobject, Init) ||
6989 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6990 CAT->getElementType(), 1)) {
6991 if (!Info.noteFailure())
6997 if (!Result.hasArrayFiller())
7000 // If we get here, we have a trivial filler, which we can just evaluate
7001 // once and splat over the rest of the array elements.
7002 assert(FillerExpr && "no array filler for incomplete init list");
7003 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7004 FillerExpr) && Success;
7007 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7008 if (E->getCommonExpr() &&
7009 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7010 Info, E->getCommonExpr()->getSourceExpr()))
7013 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7015 uint64_t Elements = CAT->getSize().getZExtValue();
7016 Result = APValue(APValue::UninitArray(), Elements, Elements);
7018 LValue Subobject = This;
7019 Subobject.addArray(Info, E, CAT);
7021 bool Success = true;
7022 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7023 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7024 Info, Subobject, E->getSubExpr()) ||
7025 !HandleLValueArrayAdjustment(Info, E, Subobject,
7026 CAT->getElementType(), 1)) {
7027 if (!Info.noteFailure())
7036 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7037 return VisitCXXConstructExpr(E, This, &Result, E->getType());
7040 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7041 const LValue &Subobject,
7044 bool HadZeroInit = !Value->isUninit();
7046 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7047 unsigned N = CAT->getSize().getZExtValue();
7049 // Preserve the array filler if we had prior zero-initialization.
7051 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7054 *Value = APValue(APValue::UninitArray(), N, N);
7057 for (unsigned I = 0; I != N; ++I)
7058 Value->getArrayInitializedElt(I) = Filler;
7060 // Initialize the elements.
7061 LValue ArrayElt = Subobject;
7062 ArrayElt.addArray(Info, E, CAT);
7063 for (unsigned I = 0; I != N; ++I)
7064 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7065 CAT->getElementType()) ||
7066 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7067 CAT->getElementType(), 1))
7073 if (!Type->isRecordType())
7076 return RecordExprEvaluator(Info, Subobject, *Value)
7077 .VisitCXXConstructExpr(E, Type);
7080 //===----------------------------------------------------------------------===//
7081 // Integer Evaluation
7083 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7084 // types and back in constant folding. Integer values are thus represented
7085 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7086 //===----------------------------------------------------------------------===//
7089 class IntExprEvaluator
7090 : public ExprEvaluatorBase<IntExprEvaluator> {
7093 IntExprEvaluator(EvalInfo &info, APValue &result)
7094 : ExprEvaluatorBaseTy(info), Result(result) {}
7096 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7097 assert(E->getType()->isIntegralOrEnumerationType() &&
7098 "Invalid evaluation result.");
7099 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7100 "Invalid evaluation result.");
7101 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7102 "Invalid evaluation result.");
7103 Result = APValue(SI);
7106 bool Success(const llvm::APSInt &SI, const Expr *E) {
7107 return Success(SI, E, Result);
7110 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7111 assert(E->getType()->isIntegralOrEnumerationType() &&
7112 "Invalid evaluation result.");
7113 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7114 "Invalid evaluation result.");
7115 Result = APValue(APSInt(I));
7116 Result.getInt().setIsUnsigned(
7117 E->getType()->isUnsignedIntegerOrEnumerationType());
7120 bool Success(const llvm::APInt &I, const Expr *E) {
7121 return Success(I, E, Result);
7124 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7125 assert(E->getType()->isIntegralOrEnumerationType() &&
7126 "Invalid evaluation result.");
7127 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7130 bool Success(uint64_t Value, const Expr *E) {
7131 return Success(Value, E, Result);
7134 bool Success(CharUnits Size, const Expr *E) {
7135 return Success(Size.getQuantity(), E);
7138 bool Success(const APValue &V, const Expr *E) {
7139 if (V.isLValue() || V.isAddrLabelDiff()) {
7143 return Success(V.getInt(), E);
7146 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7148 //===--------------------------------------------------------------------===//
7150 //===--------------------------------------------------------------------===//
7152 bool VisitIntegerLiteral(const IntegerLiteral *E) {
7153 return Success(E->getValue(), E);
7155 bool VisitCharacterLiteral(const CharacterLiteral *E) {
7156 return Success(E->getValue(), E);
7159 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7160 bool VisitDeclRefExpr(const DeclRefExpr *E) {
7161 if (CheckReferencedDecl(E, E->getDecl()))
7164 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7166 bool VisitMemberExpr(const MemberExpr *E) {
7167 if (CheckReferencedDecl(E, E->getMemberDecl())) {
7168 VisitIgnoredBaseExpression(E->getBase());
7172 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7175 bool VisitCallExpr(const CallExpr *E);
7176 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7177 bool VisitBinaryOperator(const BinaryOperator *E);
7178 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7179 bool VisitUnaryOperator(const UnaryOperator *E);
7181 bool VisitCastExpr(const CastExpr* E);
7182 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7184 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7185 return Success(E->getValue(), E);
7188 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7189 return Success(E->getValue(), E);
7192 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7193 if (Info.ArrayInitIndex == uint64_t(-1)) {
7194 // We were asked to evaluate this subexpression independent of the
7195 // enclosing ArrayInitLoopExpr. We can't do that.
7199 return Success(Info.ArrayInitIndex, E);
7202 // Note, GNU defines __null as an integer, not a pointer.
7203 bool VisitGNUNullExpr(const GNUNullExpr *E) {
7204 return ZeroInitialization(E);
7207 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7208 return Success(E->getValue(), E);
7211 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7212 return Success(E->getValue(), E);
7215 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7216 return Success(E->getValue(), E);
7219 bool VisitUnaryReal(const UnaryOperator *E);
7220 bool VisitUnaryImag(const UnaryOperator *E);
7222 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7223 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7225 // FIXME: Missing: array subscript of vector, member of vector
7228 class FixedPointExprEvaluator
7229 : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7233 FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7234 : ExprEvaluatorBaseTy(info), Result(result) {}
7236 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7237 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7238 assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7239 "Invalid evaluation result.");
7240 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7241 "Invalid evaluation result.");
7242 Result = APValue(SI);
7245 bool Success(const llvm::APSInt &SI, const Expr *E) {
7246 return Success(SI, E, Result);
7249 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7250 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7251 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7252 "Invalid evaluation result.");
7253 Result = APValue(APSInt(I));
7254 Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7257 bool Success(const llvm::APInt &I, const Expr *E) {
7258 return Success(I, E, Result);
7261 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7262 assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7263 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7266 bool Success(uint64_t Value, const Expr *E) {
7267 return Success(Value, E, Result);
7270 bool Success(CharUnits Size, const Expr *E) {
7271 return Success(Size.getQuantity(), E);
7274 bool Success(const APValue &V, const Expr *E) {
7275 if (V.isLValue() || V.isAddrLabelDiff()) {
7279 return Success(V.getInt(), E);
7282 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7284 //===--------------------------------------------------------------------===//
7286 //===--------------------------------------------------------------------===//
7288 bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7289 return Success(E->getValue(), E);
7292 bool VisitUnaryOperator(const UnaryOperator *E);
7294 } // end anonymous namespace
7296 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7297 /// produce either the integer value or a pointer.
7299 /// GCC has a heinous extension which folds casts between pointer types and
7300 /// pointer-sized integral types. We support this by allowing the evaluation of
7301 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7302 /// Some simple arithmetic on such values is supported (they are treated much
7304 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7306 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7307 return IntExprEvaluator(Info, Result).Visit(E);
7310 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7312 if (!EvaluateIntegerOrLValue(E, Val, Info))
7315 // FIXME: It would be better to produce the diagnostic for casting
7316 // a pointer to an integer.
7317 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7320 Result = Val.getInt();
7324 /// Check whether the given declaration can be directly converted to an integral
7325 /// rvalue. If not, no diagnostic is produced; there are other things we can
7327 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7328 // Enums are integer constant exprs.
7329 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7330 // Check for signedness/width mismatches between E type and ECD value.
7331 bool SameSign = (ECD->getInitVal().isSigned()
7332 == E->getType()->isSignedIntegerOrEnumerationType());
7333 bool SameWidth = (ECD->getInitVal().getBitWidth()
7334 == Info.Ctx.getIntWidth(E->getType()));
7335 if (SameSign && SameWidth)
7336 return Success(ECD->getInitVal(), E);
7338 // Get rid of mismatch (otherwise Success assertions will fail)
7339 // by computing a new value matching the type of E.
7340 llvm::APSInt Val = ECD->getInitVal();
7342 Val.setIsSigned(!ECD->getInitVal().isSigned());
7344 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7345 return Success(Val, E);
7351 /// Values returned by __builtin_classify_type, chosen to match the values
7352 /// produced by GCC's builtin.
7353 enum class GCCTypeClass {
7357 // GCC reserves 2 for character types, but instead classifies them as
7362 // GCC reserves 6 for references, but appears to never use it (because
7363 // expressions never have reference type, presumably).
7364 PointerToDataMember = 7,
7367 // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7368 // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7369 // GCC claims to reserve 11 for pointers to member functions, but *actually*
7370 // uses 12 for that purpose, same as for a class or struct. Maybe it
7371 // internally implements a pointer to member as a struct? Who knows.
7372 PointerToMemberFunction = 12, // Not a bug, see above.
7375 // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7376 // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7377 // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7381 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7384 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7385 assert(!T->isDependentType() && "unexpected dependent type");
7387 QualType CanTy = T.getCanonicalType();
7388 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7390 switch (CanTy->getTypeClass()) {
7391 #define TYPE(ID, BASE)
7392 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7393 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7394 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7395 #include "clang/AST/TypeNodes.def"
7397 case Type::DeducedTemplateSpecialization:
7398 llvm_unreachable("unexpected non-canonical or dependent type");
7401 switch (BT->getKind()) {
7402 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7403 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7404 case BuiltinType::ID: return GCCTypeClass::Integer;
7405 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7406 case BuiltinType::ID: return GCCTypeClass::RealFloat;
7407 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7408 case BuiltinType::ID: break;
7409 #include "clang/AST/BuiltinTypes.def"
7410 case BuiltinType::Void:
7411 return GCCTypeClass::Void;
7413 case BuiltinType::Bool:
7414 return GCCTypeClass::Bool;
7416 case BuiltinType::Char_U:
7417 case BuiltinType::UChar:
7418 case BuiltinType::WChar_U:
7419 case BuiltinType::Char8:
7420 case BuiltinType::Char16:
7421 case BuiltinType::Char32:
7422 case BuiltinType::UShort:
7423 case BuiltinType::UInt:
7424 case BuiltinType::ULong:
7425 case BuiltinType::ULongLong:
7426 case BuiltinType::UInt128:
7427 return GCCTypeClass::Integer;
7429 case BuiltinType::UShortAccum:
7430 case BuiltinType::UAccum:
7431 case BuiltinType::ULongAccum:
7432 case BuiltinType::UShortFract:
7433 case BuiltinType::UFract:
7434 case BuiltinType::ULongFract:
7435 case BuiltinType::SatUShortAccum:
7436 case BuiltinType::SatUAccum:
7437 case BuiltinType::SatULongAccum:
7438 case BuiltinType::SatUShortFract:
7439 case BuiltinType::SatUFract:
7440 case BuiltinType::SatULongFract:
7441 return GCCTypeClass::None;
7443 case BuiltinType::NullPtr:
7445 case BuiltinType::ObjCId:
7446 case BuiltinType::ObjCClass:
7447 case BuiltinType::ObjCSel:
7448 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7449 case BuiltinType::Id:
7450 #include "clang/Basic/OpenCLImageTypes.def"
7451 case BuiltinType::OCLSampler:
7452 case BuiltinType::OCLEvent:
7453 case BuiltinType::OCLClkEvent:
7454 case BuiltinType::OCLQueue:
7455 case BuiltinType::OCLReserveID:
7456 return GCCTypeClass::None;
7458 case BuiltinType::Dependent:
7459 llvm_unreachable("unexpected dependent type");
7461 llvm_unreachable("unexpected placeholder type");
7464 return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7467 case Type::ConstantArray:
7468 case Type::VariableArray:
7469 case Type::IncompleteArray:
7470 case Type::FunctionNoProto:
7471 case Type::FunctionProto:
7472 return GCCTypeClass::Pointer;
7474 case Type::MemberPointer:
7475 return CanTy->isMemberDataPointerType()
7476 ? GCCTypeClass::PointerToDataMember
7477 : GCCTypeClass::PointerToMemberFunction;
7480 return GCCTypeClass::Complex;
7483 return CanTy->isUnionType() ? GCCTypeClass::Union
7484 : GCCTypeClass::ClassOrStruct;
7487 // GCC classifies _Atomic T the same as T.
7488 return EvaluateBuiltinClassifyType(
7489 CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7491 case Type::BlockPointer:
7493 case Type::ExtVector:
7494 case Type::ObjCObject:
7495 case Type::ObjCInterface:
7496 case Type::ObjCObjectPointer:
7498 // GCC classifies vectors as None. We follow its lead and classify all
7499 // other types that don't fit into the regular classification the same way.
7500 return GCCTypeClass::None;
7502 case Type::LValueReference:
7503 case Type::RValueReference:
7504 llvm_unreachable("invalid type for expression");
7507 llvm_unreachable("unexpected type class");
7510 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7513 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7514 // If no argument was supplied, default to None. This isn't
7515 // ideal, however it is what gcc does.
7516 if (E->getNumArgs() == 0)
7517 return GCCTypeClass::None;
7519 // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7520 // being an ICE, but still folds it to a constant using the type of the first
7522 return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7525 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7526 /// __builtin_constant_p when applied to the given lvalue.
7528 /// An lvalue is only "constant" if it is a pointer or reference to the first
7529 /// character of a string literal.
7530 template<typename LValue>
7531 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7532 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7533 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7536 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7537 /// GCC as we can manage.
7538 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7539 QualType ArgType = Arg->getType();
7541 // __builtin_constant_p always has one operand. The rules which gcc follows
7542 // are not precisely documented, but are as follows:
7544 // - If the operand is of integral, floating, complex or enumeration type,
7545 // and can be folded to a known value of that type, it returns 1.
7546 // - If the operand and can be folded to a pointer to the first character
7547 // of a string literal (or such a pointer cast to an integral type), it
7550 // Otherwise, it returns 0.
7552 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7553 // its support for this does not currently work.
7554 if (ArgType->isIntegralOrEnumerationType()) {
7555 Expr::EvalResult Result;
7556 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7559 APValue &V = Result.Val;
7560 if (V.getKind() == APValue::Int)
7562 if (V.getKind() == APValue::LValue)
7563 return EvaluateBuiltinConstantPForLValue(V);
7564 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7565 return Arg->isEvaluatable(Ctx);
7566 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7568 Expr::EvalStatus Status;
7569 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7570 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7571 : EvaluatePointer(Arg, LV, Info)) &&
7572 !Status.HasSideEffects)
7573 return EvaluateBuiltinConstantPForLValue(LV);
7576 // Anything else isn't considered to be sufficiently constant.
7580 /// Retrieves the "underlying object type" of the given expression,
7581 /// as used by __builtin_object_size.
7582 static QualType getObjectType(APValue::LValueBase B) {
7583 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7584 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7585 return VD->getType();
7586 } else if (const Expr *E = B.get<const Expr*>()) {
7587 if (isa<CompoundLiteralExpr>(E))
7588 return E->getType();
7594 /// A more selective version of E->IgnoreParenCasts for
7595 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7596 /// to change the type of E.
7597 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7599 /// Always returns an RValue with a pointer representation.
7600 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7601 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7603 auto *NoParens = E->IgnoreParens();
7604 auto *Cast = dyn_cast<CastExpr>(NoParens);
7605 if (Cast == nullptr)
7608 // We only conservatively allow a few kinds of casts, because this code is
7609 // inherently a simple solution that seeks to support the common case.
7610 auto CastKind = Cast->getCastKind();
7611 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7612 CastKind != CK_AddressSpaceConversion)
7615 auto *SubExpr = Cast->getSubExpr();
7616 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7618 return ignorePointerCastsAndParens(SubExpr);
7621 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7622 /// record layout. e.g.
7623 /// struct { struct { int a, b; } fst, snd; } obj;
7629 /// obj.snd.b // yes
7631 /// Please note: this function is specialized for how __builtin_object_size
7632 /// views "objects".
7634 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7635 /// correct result, it will always return true.
7636 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7637 assert(!LVal.Designator.Invalid);
7639 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7640 const RecordDecl *Parent = FD->getParent();
7641 Invalid = Parent->isInvalidDecl();
7642 if (Invalid || Parent->isUnion())
7644 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7645 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7648 auto &Base = LVal.getLValueBase();
7649 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7650 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7652 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7654 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7655 for (auto *FD : IFD->chain()) {
7657 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7664 QualType BaseType = getType(Base);
7665 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7666 // If we don't know the array bound, conservatively assume we're looking at
7667 // the final array element.
7669 if (BaseType->isIncompleteArrayType())
7670 BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7672 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7675 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7676 const auto &Entry = LVal.Designator.Entries[I];
7677 if (BaseType->isArrayType()) {
7678 // Because __builtin_object_size treats arrays as objects, we can ignore
7679 // the index iff this is the last array in the Designator.
7682 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7683 uint64_t Index = Entry.ArrayIndex;
7684 if (Index + 1 != CAT->getSize())
7686 BaseType = CAT->getElementType();
7687 } else if (BaseType->isAnyComplexType()) {
7688 const auto *CT = BaseType->castAs<ComplexType>();
7689 uint64_t Index = Entry.ArrayIndex;
7692 BaseType = CT->getElementType();
7693 } else if (auto *FD = getAsField(Entry)) {
7695 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7697 BaseType = FD->getType();
7699 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7706 /// Tests to see if the LValue has a user-specified designator (that isn't
7707 /// necessarily valid). Note that this always returns 'true' if the LValue has
7708 /// an unsized array as its first designator entry, because there's currently no
7709 /// way to tell if the user typed *foo or foo[0].
7710 static bool refersToCompleteObject(const LValue &LVal) {
7711 if (LVal.Designator.Invalid)
7714 if (!LVal.Designator.Entries.empty())
7715 return LVal.Designator.isMostDerivedAnUnsizedArray();
7717 if (!LVal.InvalidBase)
7720 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7722 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7723 return !E || !isa<MemberExpr>(E);
7726 /// Attempts to detect a user writing into a piece of memory that's impossible
7727 /// to figure out the size of by just using types.
7728 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7729 const SubobjectDesignator &Designator = LVal.Designator;
7731 // - Users can only write off of the end when we have an invalid base. Invalid
7732 // bases imply we don't know where the memory came from.
7733 // - We used to be a bit more aggressive here; we'd only be conservative if
7734 // the array at the end was flexible, or if it had 0 or 1 elements. This
7735 // broke some common standard library extensions (PR30346), but was
7736 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7737 // with some sort of whitelist. OTOH, it seems that GCC is always
7738 // conservative with the last element in structs (if it's an array), so our
7739 // current behavior is more compatible than a whitelisting approach would
7741 return LVal.InvalidBase &&
7742 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7743 Designator.MostDerivedIsArrayElement &&
7744 isDesignatorAtObjectEnd(Ctx, LVal);
7747 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7748 /// Fails if the conversion would cause loss of precision.
7749 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7750 CharUnits &Result) {
7751 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7752 if (Int.ugt(CharUnitsMax))
7754 Result = CharUnits::fromQuantity(Int.getZExtValue());
7758 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7759 /// determine how many bytes exist from the beginning of the object to either
7760 /// the end of the current subobject, or the end of the object itself, depending
7761 /// on what the LValue looks like + the value of Type.
7763 /// If this returns false, the value of Result is undefined.
7764 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7765 unsigned Type, const LValue &LVal,
7766 CharUnits &EndOffset) {
7767 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7769 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7770 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7772 return HandleSizeof(Info, ExprLoc, Ty, Result);
7775 // We want to evaluate the size of the entire object. This is a valid fallback
7776 // for when Type=1 and the designator is invalid, because we're asked for an
7778 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7779 // Type=3 wants a lower bound, so we can't fall back to this.
7780 if (Type == 3 && !DetermineForCompleteObject)
7783 llvm::APInt APEndOffset;
7784 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7785 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7786 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7788 if (LVal.InvalidBase)
7791 QualType BaseTy = getObjectType(LVal.getLValueBase());
7792 return CheckedHandleSizeof(BaseTy, EndOffset);
7795 // We want to evaluate the size of a subobject.
7796 const SubobjectDesignator &Designator = LVal.Designator;
7798 // The following is a moderately common idiom in C:
7800 // struct Foo { int a; char c[1]; };
7801 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7802 // strcpy(&F->c[0], Bar);
7804 // In order to not break too much legacy code, we need to support it.
7805 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7806 // If we can resolve this to an alloc_size call, we can hand that back,
7807 // because we know for certain how many bytes there are to write to.
7808 llvm::APInt APEndOffset;
7809 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7810 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7811 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7813 // If we cannot determine the size of the initial allocation, then we can't
7814 // given an accurate upper-bound. However, we are still able to give
7815 // conservative lower-bounds for Type=3.
7820 CharUnits BytesPerElem;
7821 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7824 // According to the GCC documentation, we want the size of the subobject
7825 // denoted by the pointer. But that's not quite right -- what we actually
7826 // want is the size of the immediately-enclosing array, if there is one.
7827 int64_t ElemsRemaining;
7828 if (Designator.MostDerivedIsArrayElement &&
7829 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7830 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7831 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7832 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7834 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7837 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7841 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
7842 /// returns true and stores the result in @p Size.
7844 /// If @p WasError is non-null, this will report whether the failure to evaluate
7845 /// is to be treated as an Error in IntExprEvaluator.
7846 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7847 EvalInfo &Info, uint64_t &Size) {
7848 // Determine the denoted object.
7851 // The operand of __builtin_object_size is never evaluated for side-effects.
7852 // If there are any, but we can determine the pointed-to object anyway, then
7853 // ignore the side-effects.
7854 SpeculativeEvaluationRAII SpeculativeEval(Info);
7855 FoldOffsetRAII Fold(Info);
7857 if (E->isGLValue()) {
7858 // It's possible for us to be given GLValues if we're called via
7859 // Expr::tryEvaluateObjectSize.
7861 if (!EvaluateAsRValue(Info, E, RVal))
7863 LVal.setFrom(Info.Ctx, RVal);
7864 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7865 /*InvalidBaseOK=*/true))
7869 // If we point to before the start of the object, there are no accessible
7871 if (LVal.getLValueOffset().isNegative()) {
7876 CharUnits EndOffset;
7877 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7880 // If we've fallen outside of the end offset, just pretend there's nothing to
7881 // write to/read from.
7882 if (EndOffset <= LVal.getLValueOffset())
7885 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7889 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7890 if (unsigned BuiltinOp = E->getBuiltinCallee())
7891 return VisitBuiltinCallExpr(E, BuiltinOp);
7893 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7896 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7897 unsigned BuiltinOp) {
7898 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7900 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7902 case Builtin::BI__builtin_object_size: {
7903 // The type was checked when we built the expression.
7905 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7906 assert(Type <= 3 && "unexpected type");
7909 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7910 return Success(Size, E);
7912 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7913 return Success((Type & 2) ? 0 : -1, E);
7915 // Expression had no side effects, but we couldn't statically determine the
7916 // size of the referenced object.
7917 switch (Info.EvalMode) {
7918 case EvalInfo::EM_ConstantExpression:
7919 case EvalInfo::EM_PotentialConstantExpression:
7920 case EvalInfo::EM_ConstantFold:
7921 case EvalInfo::EM_EvaluateForOverflow:
7922 case EvalInfo::EM_IgnoreSideEffects:
7923 case EvalInfo::EM_OffsetFold:
7924 // Leave it to IR generation.
7926 case EvalInfo::EM_ConstantExpressionUnevaluated:
7927 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7928 // Reduce it to a constant now.
7929 return Success((Type & 2) ? 0 : -1, E);
7932 llvm_unreachable("unexpected EvalMode");
7935 case Builtin::BI__builtin_bswap16:
7936 case Builtin::BI__builtin_bswap32:
7937 case Builtin::BI__builtin_bswap64: {
7939 if (!EvaluateInteger(E->getArg(0), Val, Info))
7942 return Success(Val.byteSwap(), E);
7945 case Builtin::BI__builtin_classify_type:
7946 return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7948 // FIXME: BI__builtin_clrsb
7949 // FIXME: BI__builtin_clrsbl
7950 // FIXME: BI__builtin_clrsbll
7952 case Builtin::BI__builtin_clz:
7953 case Builtin::BI__builtin_clzl:
7954 case Builtin::BI__builtin_clzll:
7955 case Builtin::BI__builtin_clzs: {
7957 if (!EvaluateInteger(E->getArg(0), Val, Info))
7962 return Success(Val.countLeadingZeros(), E);
7965 case Builtin::BI__builtin_constant_p:
7966 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7968 case Builtin::BI__builtin_ctz:
7969 case Builtin::BI__builtin_ctzl:
7970 case Builtin::BI__builtin_ctzll:
7971 case Builtin::BI__builtin_ctzs: {
7973 if (!EvaluateInteger(E->getArg(0), Val, Info))
7978 return Success(Val.countTrailingZeros(), E);
7981 case Builtin::BI__builtin_eh_return_data_regno: {
7982 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7983 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7984 return Success(Operand, E);
7987 case Builtin::BI__builtin_expect:
7988 return Visit(E->getArg(0));
7990 case Builtin::BI__builtin_ffs:
7991 case Builtin::BI__builtin_ffsl:
7992 case Builtin::BI__builtin_ffsll: {
7994 if (!EvaluateInteger(E->getArg(0), Val, Info))
7997 unsigned N = Val.countTrailingZeros();
7998 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8001 case Builtin::BI__builtin_fpclassify: {
8003 if (!EvaluateFloat(E->getArg(5), Val, Info))
8006 switch (Val.getCategory()) {
8007 case APFloat::fcNaN: Arg = 0; break;
8008 case APFloat::fcInfinity: Arg = 1; break;
8009 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8010 case APFloat::fcZero: Arg = 4; break;
8012 return Visit(E->getArg(Arg));
8015 case Builtin::BI__builtin_isinf_sign: {
8017 return EvaluateFloat(E->getArg(0), Val, Info) &&
8018 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8021 case Builtin::BI__builtin_isinf: {
8023 return EvaluateFloat(E->getArg(0), Val, Info) &&
8024 Success(Val.isInfinity() ? 1 : 0, E);
8027 case Builtin::BI__builtin_isfinite: {
8029 return EvaluateFloat(E->getArg(0), Val, Info) &&
8030 Success(Val.isFinite() ? 1 : 0, E);
8033 case Builtin::BI__builtin_isnan: {
8035 return EvaluateFloat(E->getArg(0), Val, Info) &&
8036 Success(Val.isNaN() ? 1 : 0, E);
8039 case Builtin::BI__builtin_isnormal: {
8041 return EvaluateFloat(E->getArg(0), Val, Info) &&
8042 Success(Val.isNormal() ? 1 : 0, E);
8045 case Builtin::BI__builtin_parity:
8046 case Builtin::BI__builtin_parityl:
8047 case Builtin::BI__builtin_parityll: {
8049 if (!EvaluateInteger(E->getArg(0), Val, Info))
8052 return Success(Val.countPopulation() % 2, E);
8055 case Builtin::BI__builtin_popcount:
8056 case Builtin::BI__builtin_popcountl:
8057 case Builtin::BI__builtin_popcountll: {
8059 if (!EvaluateInteger(E->getArg(0), Val, Info))
8062 return Success(Val.countPopulation(), E);
8065 case Builtin::BIstrlen:
8066 case Builtin::BIwcslen:
8067 // A call to strlen is not a constant expression.
8068 if (Info.getLangOpts().CPlusPlus11)
8069 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8070 << /*isConstexpr*/0 << /*isConstructor*/0
8071 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8073 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8075 case Builtin::BI__builtin_strlen:
8076 case Builtin::BI__builtin_wcslen: {
8077 // As an extension, we support __builtin_strlen() as a constant expression,
8078 // and support folding strlen() to a constant.
8080 if (!EvaluatePointer(E->getArg(0), String, Info))
8083 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8085 // Fast path: if it's a string literal, search the string value.
8086 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8087 String.getLValueBase().dyn_cast<const Expr *>())) {
8088 // The string literal may have embedded null characters. Find the first
8089 // one and truncate there.
8090 StringRef Str = S->getBytes();
8091 int64_t Off = String.Offset.getQuantity();
8092 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8093 S->getCharByteWidth() == 1 &&
8094 // FIXME: Add fast-path for wchar_t too.
8095 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8096 Str = Str.substr(Off);
8098 StringRef::size_type Pos = Str.find(0);
8099 if (Pos != StringRef::npos)
8100 Str = Str.substr(0, Pos);
8102 return Success(Str.size(), E);
8105 // Fall through to slow path to issue appropriate diagnostic.
8108 // Slow path: scan the bytes of the string looking for the terminating 0.
8109 for (uint64_t Strlen = 0; /**/; ++Strlen) {
8111 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8115 return Success(Strlen, E);
8116 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8121 case Builtin::BIstrcmp:
8122 case Builtin::BIwcscmp:
8123 case Builtin::BIstrncmp:
8124 case Builtin::BIwcsncmp:
8125 case Builtin::BImemcmp:
8126 case Builtin::BIwmemcmp:
8127 // A call to strlen is not a constant expression.
8128 if (Info.getLangOpts().CPlusPlus11)
8129 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8130 << /*isConstexpr*/0 << /*isConstructor*/0
8131 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8133 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8135 case Builtin::BI__builtin_strcmp:
8136 case Builtin::BI__builtin_wcscmp:
8137 case Builtin::BI__builtin_strncmp:
8138 case Builtin::BI__builtin_wcsncmp:
8139 case Builtin::BI__builtin_memcmp:
8140 case Builtin::BI__builtin_wmemcmp: {
8141 LValue String1, String2;
8142 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8143 !EvaluatePointer(E->getArg(1), String2, Info))
8146 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8148 uint64_t MaxLength = uint64_t(-1);
8149 if (BuiltinOp != Builtin::BIstrcmp &&
8150 BuiltinOp != Builtin::BIwcscmp &&
8151 BuiltinOp != Builtin::BI__builtin_strcmp &&
8152 BuiltinOp != Builtin::BI__builtin_wcscmp) {
8154 if (!EvaluateInteger(E->getArg(2), N, Info))
8156 MaxLength = N.getExtValue();
8158 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8159 BuiltinOp != Builtin::BIwmemcmp &&
8160 BuiltinOp != Builtin::BI__builtin_memcmp &&
8161 BuiltinOp != Builtin::BI__builtin_wmemcmp);
8162 bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8163 BuiltinOp == Builtin::BIwcsncmp ||
8164 BuiltinOp == Builtin::BIwmemcmp ||
8165 BuiltinOp == Builtin::BI__builtin_wcscmp ||
8166 BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8167 BuiltinOp == Builtin::BI__builtin_wmemcmp;
8168 for (; MaxLength; --MaxLength) {
8169 APValue Char1, Char2;
8170 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8171 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8172 !Char1.isInt() || !Char2.isInt())
8174 if (Char1.getInt() != Char2.getInt()) {
8175 if (IsWide) // wmemcmp compares with wchar_t signedness.
8176 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8177 // memcmp always compares unsigned chars.
8178 return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8180 if (StopAtNull && !Char1.getInt())
8181 return Success(0, E);
8182 assert(!(StopAtNull && !Char2.getInt()));
8183 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8184 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8187 // We hit the strncmp / memcmp limit.
8188 return Success(0, E);
8191 case Builtin::BI__atomic_always_lock_free:
8192 case Builtin::BI__atomic_is_lock_free:
8193 case Builtin::BI__c11_atomic_is_lock_free: {
8195 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8198 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8199 // of two less than the maximum inline atomic width, we know it is
8200 // lock-free. If the size isn't a power of two, or greater than the
8201 // maximum alignment where we promote atomics, we know it is not lock-free
8202 // (at least not in the sense of atomic_is_lock_free). Otherwise,
8203 // the answer can only be determined at runtime; for example, 16-byte
8204 // atomics have lock-free implementations on some, but not all,
8205 // x86-64 processors.
8207 // Check power-of-two.
8208 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8209 if (Size.isPowerOfTwo()) {
8210 // Check against inlining width.
8211 unsigned InlineWidthBits =
8212 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8213 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8214 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8215 Size == CharUnits::One() ||
8216 E->getArg(1)->isNullPointerConstant(Info.Ctx,
8217 Expr::NPC_NeverValueDependent))
8218 // OK, we will inline appropriately-aligned operations of this size,
8219 // and _Atomic(T) is appropriately-aligned.
8220 return Success(1, E);
8222 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8223 castAs<PointerType>()->getPointeeType();
8224 if (!PointeeType->isIncompleteType() &&
8225 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8226 // OK, we will inline operations on this object.
8227 return Success(1, E);
8232 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8233 Success(0, E) : Error(E);
8235 case Builtin::BIomp_is_initial_device:
8236 // We can decide statically which value the runtime would return if called.
8237 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8238 case Builtin::BI__builtin_add_overflow:
8239 case Builtin::BI__builtin_sub_overflow:
8240 case Builtin::BI__builtin_mul_overflow:
8241 case Builtin::BI__builtin_sadd_overflow:
8242 case Builtin::BI__builtin_uadd_overflow:
8243 case Builtin::BI__builtin_uaddl_overflow:
8244 case Builtin::BI__builtin_uaddll_overflow:
8245 case Builtin::BI__builtin_usub_overflow:
8246 case Builtin::BI__builtin_usubl_overflow:
8247 case Builtin::BI__builtin_usubll_overflow:
8248 case Builtin::BI__builtin_umul_overflow:
8249 case Builtin::BI__builtin_umull_overflow:
8250 case Builtin::BI__builtin_umulll_overflow:
8251 case Builtin::BI__builtin_saddl_overflow:
8252 case Builtin::BI__builtin_saddll_overflow:
8253 case Builtin::BI__builtin_ssub_overflow:
8254 case Builtin::BI__builtin_ssubl_overflow:
8255 case Builtin::BI__builtin_ssubll_overflow:
8256 case Builtin::BI__builtin_smul_overflow:
8257 case Builtin::BI__builtin_smull_overflow:
8258 case Builtin::BI__builtin_smulll_overflow: {
8259 LValue ResultLValue;
8262 QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8263 if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8264 !EvaluateInteger(E->getArg(1), RHS, Info) ||
8265 !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8269 bool DidOverflow = false;
8271 // If the types don't have to match, enlarge all 3 to the largest of them.
8272 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8273 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8274 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8275 bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8276 ResultType->isSignedIntegerOrEnumerationType();
8277 bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8278 ResultType->isSignedIntegerOrEnumerationType();
8279 uint64_t LHSSize = LHS.getBitWidth();
8280 uint64_t RHSSize = RHS.getBitWidth();
8281 uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8282 uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8284 // Add an additional bit if the signedness isn't uniformly agreed to. We
8285 // could do this ONLY if there is a signed and an unsigned that both have
8286 // MaxBits, but the code to check that is pretty nasty. The issue will be
8287 // caught in the shrink-to-result later anyway.
8288 if (IsSigned && !AllSigned)
8291 LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8293 RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8295 Result = APSInt(MaxBits, !IsSigned);
8298 // Find largest int.
8299 switch (BuiltinOp) {
8301 llvm_unreachable("Invalid value for BuiltinOp");
8302 case Builtin::BI__builtin_add_overflow:
8303 case Builtin::BI__builtin_sadd_overflow:
8304 case Builtin::BI__builtin_saddl_overflow:
8305 case Builtin::BI__builtin_saddll_overflow:
8306 case Builtin::BI__builtin_uadd_overflow:
8307 case Builtin::BI__builtin_uaddl_overflow:
8308 case Builtin::BI__builtin_uaddll_overflow:
8309 Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8310 : LHS.uadd_ov(RHS, DidOverflow);
8312 case Builtin::BI__builtin_sub_overflow:
8313 case Builtin::BI__builtin_ssub_overflow:
8314 case Builtin::BI__builtin_ssubl_overflow:
8315 case Builtin::BI__builtin_ssubll_overflow:
8316 case Builtin::BI__builtin_usub_overflow:
8317 case Builtin::BI__builtin_usubl_overflow:
8318 case Builtin::BI__builtin_usubll_overflow:
8319 Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8320 : LHS.usub_ov(RHS, DidOverflow);
8322 case Builtin::BI__builtin_mul_overflow:
8323 case Builtin::BI__builtin_smul_overflow:
8324 case Builtin::BI__builtin_smull_overflow:
8325 case Builtin::BI__builtin_smulll_overflow:
8326 case Builtin::BI__builtin_umul_overflow:
8327 case Builtin::BI__builtin_umull_overflow:
8328 case Builtin::BI__builtin_umulll_overflow:
8329 Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8330 : LHS.umul_ov(RHS, DidOverflow);
8334 // In the case where multiple sizes are allowed, truncate and see if
8335 // the values are the same.
8336 if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8337 BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8338 BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8339 // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8340 // since it will give us the behavior of a TruncOrSelf in the case where
8341 // its parameter <= its size. We previously set Result to be at least the
8342 // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8343 // will work exactly like TruncOrSelf.
8344 APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8345 Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8347 if (!APSInt::isSameValue(Temp, Result))
8352 APValue APV{Result};
8353 if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8355 return Success(DidOverflow, E);
8360 static bool HasSameBase(const LValue &A, const LValue &B) {
8361 if (!A.getLValueBase())
8362 return !B.getLValueBase();
8363 if (!B.getLValueBase())
8366 if (A.getLValueBase().getOpaqueValue() !=
8367 B.getLValueBase().getOpaqueValue()) {
8368 const Decl *ADecl = GetLValueBaseDecl(A);
8371 const Decl *BDecl = GetLValueBaseDecl(B);
8372 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
8376 return IsGlobalLValue(A.getLValueBase()) ||
8377 (A.getLValueCallIndex() == B.getLValueCallIndex() &&
8378 A.getLValueVersion() == B.getLValueVersion());
8381 /// Determine whether this is a pointer past the end of the complete
8382 /// object referred to by the lvalue.
8383 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8385 // A null pointer can be viewed as being "past the end" but we don't
8386 // choose to look at it that way here.
8387 if (!LV.getLValueBase())
8390 // If the designator is valid and refers to a subobject, we're not pointing
8392 if (!LV.getLValueDesignator().Invalid &&
8393 !LV.getLValueDesignator().isOnePastTheEnd())
8396 // A pointer to an incomplete type might be past-the-end if the type's size is
8397 // zero. We cannot tell because the type is incomplete.
8398 QualType Ty = getType(LV.getLValueBase());
8399 if (Ty->isIncompleteType())
8402 // We're a past-the-end pointer if we point to the byte after the object,
8403 // no matter what our type or path is.
8404 auto Size = Ctx.getTypeSizeInChars(Ty);
8405 return LV.getLValueOffset() == Size;
8410 /// Data recursive integer evaluator of certain binary operators.
8412 /// We use a data recursive algorithm for binary operators so that we are able
8413 /// to handle extreme cases of chained binary operators without causing stack
8415 class DataRecursiveIntBinOpEvaluator {
8420 EvalResult() : Failed(false) { }
8422 void swap(EvalResult &RHS) {
8424 Failed = RHS.Failed;
8431 EvalResult LHSResult; // meaningful only for binary operator expression.
8432 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8435 Job(Job &&) = default;
8437 void startSpeculativeEval(EvalInfo &Info) {
8438 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8442 SpeculativeEvaluationRAII SpecEvalRAII;
8445 SmallVector<Job, 16> Queue;
8447 IntExprEvaluator &IntEval;
8449 APValue &FinalResult;
8452 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8453 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8455 /// True if \param E is a binary operator that we are going to handle
8456 /// data recursively.
8457 /// We handle binary operators that are comma, logical, or that have operands
8458 /// with integral or enumeration type.
8459 static bool shouldEnqueue(const BinaryOperator *E) {
8460 return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8461 (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8462 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8463 E->getRHS()->getType()->isIntegralOrEnumerationType());
8466 bool Traverse(const BinaryOperator *E) {
8468 EvalResult PrevResult;
8469 while (!Queue.empty())
8470 process(PrevResult);
8472 if (PrevResult.Failed) return false;
8474 FinalResult.swap(PrevResult.Val);
8479 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8480 return IntEval.Success(Value, E, Result);
8482 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8483 return IntEval.Success(Value, E, Result);
8485 bool Error(const Expr *E) {
8486 return IntEval.Error(E);
8488 bool Error(const Expr *E, diag::kind D) {
8489 return IntEval.Error(E, D);
8492 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8493 return Info.CCEDiag(E, D);
8496 // Returns true if visiting the RHS is necessary, false otherwise.
8497 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8498 bool &SuppressRHSDiags);
8500 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8501 const BinaryOperator *E, APValue &Result);
8503 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8504 Result.Failed = !Evaluate(Result.Val, Info, E);
8506 Result.Val = APValue();
8509 void process(EvalResult &Result);
8511 void enqueue(const Expr *E) {
8512 E = E->IgnoreParens();
8513 Queue.resize(Queue.size()+1);
8515 Queue.back().Kind = Job::AnyExprKind;
8521 bool DataRecursiveIntBinOpEvaluator::
8522 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8523 bool &SuppressRHSDiags) {
8524 if (E->getOpcode() == BO_Comma) {
8525 // Ignore LHS but note if we could not evaluate it.
8526 if (LHSResult.Failed)
8527 return Info.noteSideEffect();
8531 if (E->isLogicalOp()) {
8533 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8534 // We were able to evaluate the LHS, see if we can get away with not
8535 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8536 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8537 Success(LHSAsBool, E, LHSResult.Val);
8538 return false; // Ignore RHS
8541 LHSResult.Failed = true;
8543 // Since we weren't able to evaluate the left hand side, it
8544 // might have had side effects.
8545 if (!Info.noteSideEffect())
8548 // We can't evaluate the LHS; however, sometimes the result
8549 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8550 // Don't ignore RHS and suppress diagnostics from this arm.
8551 SuppressRHSDiags = true;
8557 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8558 E->getRHS()->getType()->isIntegralOrEnumerationType());
8560 if (LHSResult.Failed && !Info.noteFailure())
8561 return false; // Ignore RHS;
8566 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8568 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8569 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8571 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8572 CharUnits &Offset = LVal.getLValueOffset();
8573 uint64_t Offset64 = Offset.getQuantity();
8574 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8575 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8576 : Offset64 + Index64);
8579 bool DataRecursiveIntBinOpEvaluator::
8580 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8581 const BinaryOperator *E, APValue &Result) {
8582 if (E->getOpcode() == BO_Comma) {
8583 if (RHSResult.Failed)
8585 Result = RHSResult.Val;
8589 if (E->isLogicalOp()) {
8590 bool lhsResult, rhsResult;
8591 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8592 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8596 if (E->getOpcode() == BO_LOr)
8597 return Success(lhsResult || rhsResult, E, Result);
8599 return Success(lhsResult && rhsResult, E, Result);
8603 // We can't evaluate the LHS; however, sometimes the result
8604 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8605 if (rhsResult == (E->getOpcode() == BO_LOr))
8606 return Success(rhsResult, E, Result);
8613 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8614 E->getRHS()->getType()->isIntegralOrEnumerationType());
8616 if (LHSResult.Failed || RHSResult.Failed)
8619 const APValue &LHSVal = LHSResult.Val;
8620 const APValue &RHSVal = RHSResult.Val;
8622 // Handle cases like (unsigned long)&a + 4.
8623 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8625 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8629 // Handle cases like 4 + (unsigned long)&a
8630 if (E->getOpcode() == BO_Add &&
8631 RHSVal.isLValue() && LHSVal.isInt()) {
8633 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8637 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8638 // Handle (intptr_t)&&A - (intptr_t)&&B.
8639 if (!LHSVal.getLValueOffset().isZero() ||
8640 !RHSVal.getLValueOffset().isZero())
8642 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8643 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8644 if (!LHSExpr || !RHSExpr)
8646 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8647 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8648 if (!LHSAddrExpr || !RHSAddrExpr)
8650 // Make sure both labels come from the same function.
8651 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8652 RHSAddrExpr->getLabel()->getDeclContext())
8654 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8658 // All the remaining cases expect both operands to be an integer
8659 if (!LHSVal.isInt() || !RHSVal.isInt())
8662 // Set up the width and signedness manually, in case it can't be deduced
8663 // from the operation we're performing.
8664 // FIXME: Don't do this in the cases where we can deduce it.
8665 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8666 E->getType()->isUnsignedIntegerOrEnumerationType());
8667 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8668 RHSVal.getInt(), Value))
8670 return Success(Value, E, Result);
8673 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8674 Job &job = Queue.back();
8677 case Job::AnyExprKind: {
8678 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8679 if (shouldEnqueue(Bop)) {
8680 job.Kind = Job::BinOpKind;
8681 enqueue(Bop->getLHS());
8686 EvaluateExpr(job.E, Result);
8691 case Job::BinOpKind: {
8692 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8693 bool SuppressRHSDiags = false;
8694 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8698 if (SuppressRHSDiags)
8699 job.startSpeculativeEval(Info);
8700 job.LHSResult.swap(Result);
8701 job.Kind = Job::BinOpVisitedLHSKind;
8702 enqueue(Bop->getRHS());
8706 case Job::BinOpVisitedLHSKind: {
8707 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8710 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8716 llvm_unreachable("Invalid Job::Kind!");
8720 /// Used when we determine that we should fail, but can keep evaluating prior to
8721 /// noting that we had a failure.
8722 class DelayedNoteFailureRAII {
8727 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8728 : Info(Info), NoteFailure(NoteFailure) {}
8729 ~DelayedNoteFailureRAII() {
8731 bool ContinueAfterFailure = Info.noteFailure();
8732 (void)ContinueAfterFailure;
8733 assert(ContinueAfterFailure &&
8734 "Shouldn't have kept evaluating on failure.");
8740 template <class SuccessCB, class AfterCB>
8742 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8743 SuccessCB &&Success, AfterCB &&DoAfter) {
8744 assert(E->isComparisonOp() && "expected comparison operator");
8745 assert((E->getOpcode() == BO_Cmp ||
8746 E->getType()->isIntegralOrEnumerationType()) &&
8747 "unsupported binary expression evaluation");
8748 auto Error = [&](const Expr *E) {
8749 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8753 using CCR = ComparisonCategoryResult;
8754 bool IsRelational = E->isRelationalOp();
8755 bool IsEquality = E->isEqualityOp();
8756 if (E->getOpcode() == BO_Cmp) {
8757 const ComparisonCategoryInfo &CmpInfo =
8758 Info.Ctx.CompCategories.getInfoForType(E->getType());
8759 IsRelational = CmpInfo.isOrdered();
8760 IsEquality = CmpInfo.isEquality();
8763 QualType LHSTy = E->getLHS()->getType();
8764 QualType RHSTy = E->getRHS()->getType();
8766 if (LHSTy->isIntegralOrEnumerationType() &&
8767 RHSTy->isIntegralOrEnumerationType()) {
8769 bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8770 if (!LHSOK && !Info.noteFailure())
8772 if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8775 return Success(CCR::Less, E);
8777 return Success(CCR::Greater, E);
8778 return Success(CCR::Equal, E);
8781 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8782 ComplexValue LHS, RHS;
8784 if (E->isAssignmentOp()) {
8786 EvaluateLValue(E->getLHS(), LV, Info);
8788 } else if (LHSTy->isRealFloatingType()) {
8789 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8791 LHS.makeComplexFloat();
8792 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8795 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8797 if (!LHSOK && !Info.noteFailure())
8800 if (E->getRHS()->getType()->isRealFloatingType()) {
8801 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8803 RHS.makeComplexFloat();
8804 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8805 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8808 if (LHS.isComplexFloat()) {
8809 APFloat::cmpResult CR_r =
8810 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8811 APFloat::cmpResult CR_i =
8812 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8813 bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
8814 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
8816 assert(IsEquality && "invalid complex comparison");
8817 bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8818 LHS.getComplexIntImag() == RHS.getComplexIntImag();
8819 return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
8823 if (LHSTy->isRealFloatingType() &&
8824 RHSTy->isRealFloatingType()) {
8825 APFloat RHS(0.0), LHS(0.0);
8827 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8828 if (!LHSOK && !Info.noteFailure())
8831 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8834 assert(E->isComparisonOp() && "Invalid binary operator!");
8835 auto GetCmpRes = [&]() {
8836 switch (LHS.compare(RHS)) {
8837 case APFloat::cmpEqual:
8839 case APFloat::cmpLessThan:
8841 case APFloat::cmpGreaterThan:
8842 return CCR::Greater;
8843 case APFloat::cmpUnordered:
8844 return CCR::Unordered;
8846 llvm_unreachable("Unrecognised APFloat::cmpResult enum");
8848 return Success(GetCmpRes(), E);
8851 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8852 LValue LHSValue, RHSValue;
8854 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8855 if (!LHSOK && !Info.noteFailure())
8858 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8861 // Reject differing bases from the normal codepath; we special-case
8862 // comparisons to null.
8863 if (!HasSameBase(LHSValue, RHSValue)) {
8864 // Inequalities and subtractions between unrelated pointers have
8865 // unspecified or undefined behavior.
8868 // A constant address may compare equal to the address of a symbol.
8869 // The one exception is that address of an object cannot compare equal
8870 // to a null pointer constant.
8871 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8872 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8874 // It's implementation-defined whether distinct literals will have
8875 // distinct addresses. In clang, the result of such a comparison is
8876 // unspecified, so it is not a constant expression. However, we do know
8877 // that the address of a literal will be non-null.
8878 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8879 LHSValue.Base && RHSValue.Base)
8881 // We can't tell whether weak symbols will end up pointing to the same
8883 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8885 // We can't compare the address of the start of one object with the
8886 // past-the-end address of another object, per C++ DR1652.
8887 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8888 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8889 (RHSValue.Base && RHSValue.Offset.isZero() &&
8890 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8892 // We can't tell whether an object is at the same address as another
8893 // zero sized object.
8894 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8895 (LHSValue.Base && isZeroSized(RHSValue)))
8897 return Success(CCR::Nonequal, E);
8900 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8901 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8903 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8904 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8906 // C++11 [expr.rel]p3:
8907 // Pointers to void (after pointer conversions) can be compared, with a
8908 // result defined as follows: If both pointers represent the same
8909 // address or are both the null pointer value, the result is true if the
8910 // operator is <= or >= and false otherwise; otherwise the result is
8912 // We interpret this as applying to pointers to *cv* void.
8913 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
8914 Info.CCEDiag(E, diag::note_constexpr_void_comparison);
8916 // C++11 [expr.rel]p2:
8917 // - If two pointers point to non-static data members of the same object,
8918 // or to subobjects or array elements fo such members, recursively, the
8919 // pointer to the later declared member compares greater provided the
8920 // two members have the same access control and provided their class is
8923 // - Otherwise pointer comparisons are unspecified.
8924 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
8926 unsigned Mismatch = FindDesignatorMismatch(
8927 getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
8928 // At the point where the designators diverge, the comparison has a
8929 // specified value if:
8930 // - we are comparing array indices
8931 // - we are comparing fields of a union, or fields with the same access
8932 // Otherwise, the result is unspecified and thus the comparison is not a
8933 // constant expression.
8934 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8935 Mismatch < RHSDesignator.Entries.size()) {
8936 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8937 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8939 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8941 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8942 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8943 << RF->getParent() << RF;
8945 Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8946 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8947 << LF->getParent() << LF;
8948 else if (!LF->getParent()->isUnion() &&
8949 LF->getAccess() != RF->getAccess())
8951 diag::note_constexpr_pointer_comparison_differing_access)
8952 << LF << LF->getAccess() << RF << RF->getAccess()
8957 // The comparison here must be unsigned, and performed with the same
8958 // width as the pointer.
8959 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8960 uint64_t CompareLHS = LHSOffset.getQuantity();
8961 uint64_t CompareRHS = RHSOffset.getQuantity();
8962 assert(PtrSize <= 64 && "Unexpected pointer width");
8963 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8967 // If there is a base and this is a relational operator, we can only
8968 // compare pointers within the object in question; otherwise, the result
8969 // depends on where the object is located in memory.
8970 if (!LHSValue.Base.isNull() && IsRelational) {
8971 QualType BaseTy = getType(LHSValue.Base);
8972 if (BaseTy->isIncompleteType())
8974 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8975 uint64_t OffsetLimit = Size.getQuantity();
8976 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8980 if (CompareLHS < CompareRHS)
8981 return Success(CCR::Less, E);
8982 if (CompareLHS > CompareRHS)
8983 return Success(CCR::Greater, E);
8984 return Success(CCR::Equal, E);
8987 if (LHSTy->isMemberPointerType()) {
8988 assert(IsEquality && "unexpected member pointer operation");
8989 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8991 MemberPtr LHSValue, RHSValue;
8993 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8994 if (!LHSOK && !Info.noteFailure())
8997 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9000 // C++11 [expr.eq]p2:
9001 // If both operands are null, they compare equal. Otherwise if only one is
9002 // null, they compare unequal.
9003 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9004 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9005 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9008 // Otherwise if either is a pointer to a virtual member function, the
9009 // result is unspecified.
9010 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9011 if (MD->isVirtual())
9012 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9013 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9014 if (MD->isVirtual())
9015 Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9017 // Otherwise they compare equal if and only if they would refer to the
9018 // same member of the same most derived object or the same subobject if
9019 // they were dereferenced with a hypothetical object of the associated
9021 bool Equal = LHSValue == RHSValue;
9022 return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9025 if (LHSTy->isNullPtrType()) {
9026 assert(E->isComparisonOp() && "unexpected nullptr operation");
9027 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9028 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9029 // are compared, the result is true of the operator is <=, >= or ==, and
9031 return Success(CCR::Equal, E);
9037 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9038 if (!CheckLiteralType(Info, E))
9041 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9042 const BinaryOperator *E) {
9043 // Evaluation succeeded. Lookup the information for the comparison category
9044 // type and fetch the VarDecl for the result.
9045 const ComparisonCategoryInfo &CmpInfo =
9046 Info.Ctx.CompCategories.getInfoForType(E->getType());
9048 CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9049 // Check and evaluate the result as a constant expression.
9052 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9054 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9056 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9057 return ExprEvaluatorBaseTy::VisitBinCmp(E);
9061 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9062 // We don't call noteFailure immediately because the assignment happens after
9063 // we evaluate LHS and RHS.
9064 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9067 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9068 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9069 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9071 assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9072 !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9073 "DataRecursiveIntBinOpEvaluator should have handled integral types");
9075 if (E->isComparisonOp()) {
9076 // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9077 // comparisons and then translating the result.
9078 auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9079 const BinaryOperator *E) {
9080 using CCR = ComparisonCategoryResult;
9081 bool IsEqual = ResKind == CCR::Equal,
9082 IsLess = ResKind == CCR::Less,
9083 IsGreater = ResKind == CCR::Greater;
9084 auto Op = E->getOpcode();
9087 llvm_unreachable("unsupported binary operator");
9090 return Success(IsEqual == (Op == BO_EQ), E);
9091 case BO_LT: return Success(IsLess, E);
9092 case BO_GT: return Success(IsGreater, E);
9093 case BO_LE: return Success(IsEqual || IsLess, E);
9094 case BO_GE: return Success(IsEqual || IsGreater, E);
9097 return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9098 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9102 QualType LHSTy = E->getLHS()->getType();
9103 QualType RHSTy = E->getRHS()->getType();
9105 if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9106 E->getOpcode() == BO_Sub) {
9107 LValue LHSValue, RHSValue;
9109 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9110 if (!LHSOK && !Info.noteFailure())
9113 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9116 // Reject differing bases from the normal codepath; we special-case
9117 // comparisons to null.
9118 if (!HasSameBase(LHSValue, RHSValue)) {
9119 // Handle &&A - &&B.
9120 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9122 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9123 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9124 if (!LHSExpr || !RHSExpr)
9126 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9127 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9128 if (!LHSAddrExpr || !RHSAddrExpr)
9130 // Make sure both labels come from the same function.
9131 if (LHSAddrExpr->getLabel()->getDeclContext() !=
9132 RHSAddrExpr->getLabel()->getDeclContext())
9134 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9136 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9137 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9139 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9140 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9142 // C++11 [expr.add]p6:
9143 // Unless both pointers point to elements of the same array object, or
9144 // one past the last element of the array object, the behavior is
9146 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9147 !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9149 Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9151 QualType Type = E->getLHS()->getType();
9152 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9154 CharUnits ElementSize;
9155 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9158 // As an extension, a type may have zero size (empty struct or union in
9159 // C, array of zero length). Pointer subtraction in such cases has
9160 // undefined behavior, so is not constant.
9161 if (ElementSize.isZero()) {
9162 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9167 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9168 // and produce incorrect results when it overflows. Such behavior
9169 // appears to be non-conforming, but is common, so perhaps we should
9170 // assume the standard intended for such cases to be undefined behavior
9171 // and check for them.
9173 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9174 // overflow in the final conversion to ptrdiff_t.
9175 APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9176 APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9177 APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9179 APSInt TrueResult = (LHS - RHS) / ElemSize;
9180 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9182 if (Result.extend(65) != TrueResult &&
9183 !HandleOverflow(Info, E, TrueResult, E->getType()))
9185 return Success(Result, E);
9188 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9191 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9192 /// a result as the expression's type.
9193 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9194 const UnaryExprOrTypeTraitExpr *E) {
9195 switch(E->getKind()) {
9196 case UETT_AlignOf: {
9197 if (E->isArgumentType())
9198 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
9200 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
9203 case UETT_VecStep: {
9204 QualType Ty = E->getTypeOfArgument();
9206 if (Ty->isVectorType()) {
9207 unsigned n = Ty->castAs<VectorType>()->getNumElements();
9209 // The vec_step built-in functions that take a 3-component
9210 // vector return 4. (OpenCL 1.1 spec 6.11.12)
9214 return Success(n, E);
9216 return Success(1, E);
9220 QualType SrcTy = E->getTypeOfArgument();
9221 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9222 // the result is the size of the referenced type."
9223 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9224 SrcTy = Ref->getPointeeType();
9227 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9229 return Success(Sizeof, E);
9231 case UETT_OpenMPRequiredSimdAlign:
9232 assert(E->isArgumentType());
9234 Info.Ctx.toCharUnitsFromBits(
9235 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9240 llvm_unreachable("unknown expr/type trait");
9243 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9245 unsigned n = OOE->getNumComponents();
9248 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9249 for (unsigned i = 0; i != n; ++i) {
9250 OffsetOfNode ON = OOE->getComponent(i);
9251 switch (ON.getKind()) {
9252 case OffsetOfNode::Array: {
9253 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9255 if (!EvaluateInteger(Idx, IdxResult, Info))
9257 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9260 CurrentType = AT->getElementType();
9261 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9262 Result += IdxResult.getSExtValue() * ElementSize;
9266 case OffsetOfNode::Field: {
9267 FieldDecl *MemberDecl = ON.getField();
9268 const RecordType *RT = CurrentType->getAs<RecordType>();
9271 RecordDecl *RD = RT->getDecl();
9272 if (RD->isInvalidDecl()) return false;
9273 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9274 unsigned i = MemberDecl->getFieldIndex();
9275 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9276 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9277 CurrentType = MemberDecl->getType().getNonReferenceType();
9281 case OffsetOfNode::Identifier:
9282 llvm_unreachable("dependent __builtin_offsetof");
9284 case OffsetOfNode::Base: {
9285 CXXBaseSpecifier *BaseSpec = ON.getBase();
9286 if (BaseSpec->isVirtual())
9289 // Find the layout of the class whose base we are looking into.
9290 const RecordType *RT = CurrentType->getAs<RecordType>();
9293 RecordDecl *RD = RT->getDecl();
9294 if (RD->isInvalidDecl()) return false;
9295 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9297 // Find the base class itself.
9298 CurrentType = BaseSpec->getType();
9299 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9303 // Add the offset to the base.
9304 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9309 return Success(Result, OOE);
9312 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9313 switch (E->getOpcode()) {
9315 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9319 // FIXME: Should extension allow i-c-e extension expressions in its scope?
9320 // If so, we could clear the diagnostic ID.
9321 return Visit(E->getSubExpr());
9323 // The result is just the value.
9324 return Visit(E->getSubExpr());
9326 if (!Visit(E->getSubExpr()))
9328 if (!Result.isInt()) return Error(E);
9329 const APSInt &Value = Result.getInt();
9330 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9331 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9334 return Success(-Value, E);
9337 if (!Visit(E->getSubExpr()))
9339 if (!Result.isInt()) return Error(E);
9340 return Success(~Result.getInt(), E);
9344 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9346 return Success(!bres, E);
9351 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9352 /// result type is integer.
9353 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9354 const Expr *SubExpr = E->getSubExpr();
9355 QualType DestType = E->getType();
9356 QualType SrcType = SubExpr->getType();
9358 switch (E->getCastKind()) {
9359 case CK_BaseToDerived:
9360 case CK_DerivedToBase:
9361 case CK_UncheckedDerivedToBase:
9364 case CK_ArrayToPointerDecay:
9365 case CK_FunctionToPointerDecay:
9366 case CK_NullToPointer:
9367 case CK_NullToMemberPointer:
9368 case CK_BaseToDerivedMemberPointer:
9369 case CK_DerivedToBaseMemberPointer:
9370 case CK_ReinterpretMemberPointer:
9371 case CK_ConstructorConversion:
9372 case CK_IntegralToPointer:
9374 case CK_VectorSplat:
9375 case CK_IntegralToFloating:
9376 case CK_FloatingCast:
9377 case CK_CPointerToObjCPointerCast:
9378 case CK_BlockPointerToObjCPointerCast:
9379 case CK_AnyPointerToBlockPointerCast:
9380 case CK_ObjCObjectLValueCast:
9381 case CK_FloatingRealToComplex:
9382 case CK_FloatingComplexToReal:
9383 case CK_FloatingComplexCast:
9384 case CK_FloatingComplexToIntegralComplex:
9385 case CK_IntegralRealToComplex:
9386 case CK_IntegralComplexCast:
9387 case CK_IntegralComplexToFloatingComplex:
9388 case CK_BuiltinFnToFnPtr:
9389 case CK_ZeroToOCLEvent:
9390 case CK_ZeroToOCLQueue:
9391 case CK_NonAtomicToAtomic:
9392 case CK_AddressSpaceConversion:
9393 case CK_IntToOCLSampler:
9394 llvm_unreachable("invalid cast kind for integral value");
9398 case CK_LValueBitCast:
9399 case CK_ARCProduceObject:
9400 case CK_ARCConsumeObject:
9401 case CK_ARCReclaimReturnedObject:
9402 case CK_ARCExtendBlockObject:
9403 case CK_CopyAndAutoreleaseBlockObject:
9406 case CK_UserDefinedConversion:
9407 case CK_LValueToRValue:
9408 case CK_AtomicToNonAtomic:
9410 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9412 case CK_MemberPointerToBoolean:
9413 case CK_PointerToBoolean:
9414 case CK_IntegralToBoolean:
9415 case CK_FloatingToBoolean:
9416 case CK_BooleanToSignedIntegral:
9417 case CK_FloatingComplexToBoolean:
9418 case CK_IntegralComplexToBoolean: {
9420 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9422 uint64_t IntResult = BoolResult;
9423 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9424 IntResult = (uint64_t)-1;
9425 return Success(IntResult, E);
9428 case CK_IntegralCast: {
9429 if (!Visit(SubExpr))
9432 if (!Result.isInt()) {
9433 // Allow casts of address-of-label differences if they are no-ops
9434 // or narrowing. (The narrowing case isn't actually guaranteed to
9435 // be constant-evaluatable except in some narrow cases which are hard
9436 // to detect here. We let it through on the assumption the user knows
9437 // what they are doing.)
9438 if (Result.isAddrLabelDiff())
9439 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9440 // Only allow casts of lvalues if they are lossless.
9441 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9444 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9445 Result.getInt()), E);
9448 case CK_PointerToIntegral: {
9449 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9452 if (!EvaluatePointer(SubExpr, LV, Info))
9455 if (LV.getLValueBase()) {
9456 // Only allow based lvalue casts if they are lossless.
9457 // FIXME: Allow a larger integer size than the pointer size, and allow
9458 // narrowing back down to pointer width in subsequent integral casts.
9459 // FIXME: Check integer type's active bits, not its type size.
9460 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9463 LV.Designator.setInvalid();
9464 LV.moveInto(Result);
9469 if (LV.isNullPointer())
9470 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9472 V = LV.getLValueOffset().getQuantity();
9474 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9475 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9478 case CK_IntegralComplexToReal: {
9480 if (!EvaluateComplex(SubExpr, C, Info))
9482 return Success(C.getComplexIntReal(), E);
9485 case CK_FloatingToIntegral: {
9487 if (!EvaluateFloat(SubExpr, F, Info))
9491 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9493 return Success(Value, E);
9497 llvm_unreachable("unknown cast resulting in integral value");
9500 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9501 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9503 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9505 if (!LV.isComplexInt())
9507 return Success(LV.getComplexIntReal(), E);
9510 return Visit(E->getSubExpr());
9513 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9514 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9516 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9518 if (!LV.isComplexInt())
9520 return Success(LV.getComplexIntImag(), E);
9523 VisitIgnoredValue(E->getSubExpr());
9524 return Success(0, E);
9527 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9528 return Success(E->getPackLength(), E);
9531 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9532 return Success(E->getValue(), E);
9535 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9536 switch (E->getOpcode()) {
9538 // Invalid unary operators
9541 // The result is just the value.
9542 return Visit(E->getSubExpr());
9544 if (!Visit(E->getSubExpr())) return false;
9545 if (!Result.isInt()) return Error(E);
9546 const APSInt &Value = Result.getInt();
9547 if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9549 FixedPointValueToString(S, Value,
9550 Info.Ctx.getTypeInfo(E->getType()).Width,
9552 Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9553 if (Info.noteUndefinedBehavior()) return false;
9555 return Success(-Value, E);
9559 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9561 return Success(!bres, E);
9566 //===----------------------------------------------------------------------===//
9568 //===----------------------------------------------------------------------===//
9571 class FloatExprEvaluator
9572 : public ExprEvaluatorBase<FloatExprEvaluator> {
9575 FloatExprEvaluator(EvalInfo &info, APFloat &result)
9576 : ExprEvaluatorBaseTy(info), Result(result) {}
9578 bool Success(const APValue &V, const Expr *e) {
9579 Result = V.getFloat();
9583 bool ZeroInitialization(const Expr *E) {
9584 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9588 bool VisitCallExpr(const CallExpr *E);
9590 bool VisitUnaryOperator(const UnaryOperator *E);
9591 bool VisitBinaryOperator(const BinaryOperator *E);
9592 bool VisitFloatingLiteral(const FloatingLiteral *E);
9593 bool VisitCastExpr(const CastExpr *E);
9595 bool VisitUnaryReal(const UnaryOperator *E);
9596 bool VisitUnaryImag(const UnaryOperator *E);
9598 // FIXME: Missing: array subscript of vector, member of vector
9600 } // end anonymous namespace
9602 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9603 assert(E->isRValue() && E->getType()->isRealFloatingType());
9604 return FloatExprEvaluator(Info, Result).Visit(E);
9607 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9611 llvm::APFloat &Result) {
9612 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9613 if (!S) return false;
9615 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9619 // Treat empty strings as if they were zero.
9620 if (S->getString().empty())
9621 fill = llvm::APInt(32, 0);
9622 else if (S->getString().getAsInteger(0, fill))
9625 if (Context.getTargetInfo().isNan2008()) {
9627 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9629 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9631 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9632 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9633 // a different encoding to what became a standard in 2008, and for pre-
9634 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9635 // sNaN. This is now known as "legacy NaN" encoding.
9637 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9639 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9645 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9646 switch (E->getBuiltinCallee()) {
9648 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9650 case Builtin::BI__builtin_huge_val:
9651 case Builtin::BI__builtin_huge_valf:
9652 case Builtin::BI__builtin_huge_vall:
9653 case Builtin::BI__builtin_huge_valf128:
9654 case Builtin::BI__builtin_inf:
9655 case Builtin::BI__builtin_inff:
9656 case Builtin::BI__builtin_infl:
9657 case Builtin::BI__builtin_inff128: {
9658 const llvm::fltSemantics &Sem =
9659 Info.Ctx.getFloatTypeSemantics(E->getType());
9660 Result = llvm::APFloat::getInf(Sem);
9664 case Builtin::BI__builtin_nans:
9665 case Builtin::BI__builtin_nansf:
9666 case Builtin::BI__builtin_nansl:
9667 case Builtin::BI__builtin_nansf128:
9668 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9673 case Builtin::BI__builtin_nan:
9674 case Builtin::BI__builtin_nanf:
9675 case Builtin::BI__builtin_nanl:
9676 case Builtin::BI__builtin_nanf128:
9677 // If this is __builtin_nan() turn this into a nan, otherwise we
9678 // can't constant fold it.
9679 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9684 case Builtin::BI__builtin_fabs:
9685 case Builtin::BI__builtin_fabsf:
9686 case Builtin::BI__builtin_fabsl:
9687 case Builtin::BI__builtin_fabsf128:
9688 if (!EvaluateFloat(E->getArg(0), Result, Info))
9691 if (Result.isNegative())
9692 Result.changeSign();
9695 // FIXME: Builtin::BI__builtin_powi
9696 // FIXME: Builtin::BI__builtin_powif
9697 // FIXME: Builtin::BI__builtin_powil
9699 case Builtin::BI__builtin_copysign:
9700 case Builtin::BI__builtin_copysignf:
9701 case Builtin::BI__builtin_copysignl:
9702 case Builtin::BI__builtin_copysignf128: {
9704 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9705 !EvaluateFloat(E->getArg(1), RHS, Info))
9707 Result.copySign(RHS);
9713 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9714 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9716 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9718 Result = CV.FloatReal;
9722 return Visit(E->getSubExpr());
9725 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9726 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9728 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9730 Result = CV.FloatImag;
9734 VisitIgnoredValue(E->getSubExpr());
9735 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9736 Result = llvm::APFloat::getZero(Sem);
9740 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9741 switch (E->getOpcode()) {
9742 default: return Error(E);
9744 return EvaluateFloat(E->getSubExpr(), Result, Info);
9746 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9748 Result.changeSign();
9753 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9754 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9755 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9758 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9759 if (!LHSOK && !Info.noteFailure())
9761 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9762 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9765 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9766 Result = E->getValue();
9770 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9771 const Expr* SubExpr = E->getSubExpr();
9773 switch (E->getCastKind()) {
9775 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9777 case CK_IntegralToFloating: {
9779 return EvaluateInteger(SubExpr, IntResult, Info) &&
9780 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9781 E->getType(), Result);
9784 case CK_FloatingCast: {
9785 if (!Visit(SubExpr))
9787 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9791 case CK_FloatingComplexToReal: {
9793 if (!EvaluateComplex(SubExpr, V, Info))
9795 Result = V.getComplexFloatReal();
9801 //===----------------------------------------------------------------------===//
9802 // Complex Evaluation (for float and integer)
9803 //===----------------------------------------------------------------------===//
9806 class ComplexExprEvaluator
9807 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9808 ComplexValue &Result;
9811 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9812 : ExprEvaluatorBaseTy(info), Result(Result) {}
9814 bool Success(const APValue &V, const Expr *e) {
9819 bool ZeroInitialization(const Expr *E);
9821 //===--------------------------------------------------------------------===//
9823 //===--------------------------------------------------------------------===//
9825 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9826 bool VisitCastExpr(const CastExpr *E);
9827 bool VisitBinaryOperator(const BinaryOperator *E);
9828 bool VisitUnaryOperator(const UnaryOperator *E);
9829 bool VisitInitListExpr(const InitListExpr *E);
9831 } // end anonymous namespace
9833 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9835 assert(E->isRValue() && E->getType()->isAnyComplexType());
9836 return ComplexExprEvaluator(Info, Result).Visit(E);
9839 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9840 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9841 if (ElemTy->isRealFloatingType()) {
9842 Result.makeComplexFloat();
9843 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9844 Result.FloatReal = Zero;
9845 Result.FloatImag = Zero;
9847 Result.makeComplexInt();
9848 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9849 Result.IntReal = Zero;
9850 Result.IntImag = Zero;
9855 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9856 const Expr* SubExpr = E->getSubExpr();
9858 if (SubExpr->getType()->isRealFloatingType()) {
9859 Result.makeComplexFloat();
9860 APFloat &Imag = Result.FloatImag;
9861 if (!EvaluateFloat(SubExpr, Imag, Info))
9864 Result.FloatReal = APFloat(Imag.getSemantics());
9867 assert(SubExpr->getType()->isIntegerType() &&
9868 "Unexpected imaginary literal.");
9870 Result.makeComplexInt();
9871 APSInt &Imag = Result.IntImag;
9872 if (!EvaluateInteger(SubExpr, Imag, Info))
9875 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9880 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9882 switch (E->getCastKind()) {
9884 case CK_BaseToDerived:
9885 case CK_DerivedToBase:
9886 case CK_UncheckedDerivedToBase:
9889 case CK_ArrayToPointerDecay:
9890 case CK_FunctionToPointerDecay:
9891 case CK_NullToPointer:
9892 case CK_NullToMemberPointer:
9893 case CK_BaseToDerivedMemberPointer:
9894 case CK_DerivedToBaseMemberPointer:
9895 case CK_MemberPointerToBoolean:
9896 case CK_ReinterpretMemberPointer:
9897 case CK_ConstructorConversion:
9898 case CK_IntegralToPointer:
9899 case CK_PointerToIntegral:
9900 case CK_PointerToBoolean:
9902 case CK_VectorSplat:
9903 case CK_IntegralCast:
9904 case CK_BooleanToSignedIntegral:
9905 case CK_IntegralToBoolean:
9906 case CK_IntegralToFloating:
9907 case CK_FloatingToIntegral:
9908 case CK_FloatingToBoolean:
9909 case CK_FloatingCast:
9910 case CK_CPointerToObjCPointerCast:
9911 case CK_BlockPointerToObjCPointerCast:
9912 case CK_AnyPointerToBlockPointerCast:
9913 case CK_ObjCObjectLValueCast:
9914 case CK_FloatingComplexToReal:
9915 case CK_FloatingComplexToBoolean:
9916 case CK_IntegralComplexToReal:
9917 case CK_IntegralComplexToBoolean:
9918 case CK_ARCProduceObject:
9919 case CK_ARCConsumeObject:
9920 case CK_ARCReclaimReturnedObject:
9921 case CK_ARCExtendBlockObject:
9922 case CK_CopyAndAutoreleaseBlockObject:
9923 case CK_BuiltinFnToFnPtr:
9924 case CK_ZeroToOCLEvent:
9925 case CK_ZeroToOCLQueue:
9926 case CK_NonAtomicToAtomic:
9927 case CK_AddressSpaceConversion:
9928 case CK_IntToOCLSampler:
9929 llvm_unreachable("invalid cast kind for complex value");
9931 case CK_LValueToRValue:
9932 case CK_AtomicToNonAtomic:
9934 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9937 case CK_LValueBitCast:
9938 case CK_UserDefinedConversion:
9941 case CK_FloatingRealToComplex: {
9942 APFloat &Real = Result.FloatReal;
9943 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9946 Result.makeComplexFloat();
9947 Result.FloatImag = APFloat(Real.getSemantics());
9951 case CK_FloatingComplexCast: {
9952 if (!Visit(E->getSubExpr()))
9955 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9957 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9959 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9960 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9963 case CK_FloatingComplexToIntegralComplex: {
9964 if (!Visit(E->getSubExpr()))
9967 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9969 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9970 Result.makeComplexInt();
9971 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9972 To, Result.IntReal) &&
9973 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9974 To, Result.IntImag);
9977 case CK_IntegralRealToComplex: {
9978 APSInt &Real = Result.IntReal;
9979 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9982 Result.makeComplexInt();
9983 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9987 case CK_IntegralComplexCast: {
9988 if (!Visit(E->getSubExpr()))
9991 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9993 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9995 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9996 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10000 case CK_IntegralComplexToFloatingComplex: {
10001 if (!Visit(E->getSubExpr()))
10004 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10006 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10007 Result.makeComplexFloat();
10008 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10009 To, Result.FloatReal) &&
10010 HandleIntToFloatCast(Info, E, From, Result.IntImag,
10011 To, Result.FloatImag);
10015 llvm_unreachable("unknown cast resulting in complex value");
10018 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10019 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10020 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10022 // Track whether the LHS or RHS is real at the type system level. When this is
10023 // the case we can simplify our evaluation strategy.
10024 bool LHSReal = false, RHSReal = false;
10027 if (E->getLHS()->getType()->isRealFloatingType()) {
10029 APFloat &Real = Result.FloatReal;
10030 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10032 Result.makeComplexFloat();
10033 Result.FloatImag = APFloat(Real.getSemantics());
10036 LHSOK = Visit(E->getLHS());
10038 if (!LHSOK && !Info.noteFailure())
10042 if (E->getRHS()->getType()->isRealFloatingType()) {
10044 APFloat &Real = RHS.FloatReal;
10045 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10047 RHS.makeComplexFloat();
10048 RHS.FloatImag = APFloat(Real.getSemantics());
10049 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10052 assert(!(LHSReal && RHSReal) &&
10053 "Cannot have both operands of a complex operation be real.");
10054 switch (E->getOpcode()) {
10055 default: return Error(E);
10057 if (Result.isComplexFloat()) {
10058 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10059 APFloat::rmNearestTiesToEven);
10061 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10063 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10064 APFloat::rmNearestTiesToEven);
10066 Result.getComplexIntReal() += RHS.getComplexIntReal();
10067 Result.getComplexIntImag() += RHS.getComplexIntImag();
10071 if (Result.isComplexFloat()) {
10072 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10073 APFloat::rmNearestTiesToEven);
10075 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10076 Result.getComplexFloatImag().changeSign();
10077 } else if (!RHSReal) {
10078 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10079 APFloat::rmNearestTiesToEven);
10082 Result.getComplexIntReal() -= RHS.getComplexIntReal();
10083 Result.getComplexIntImag() -= RHS.getComplexIntImag();
10087 if (Result.isComplexFloat()) {
10088 // This is an implementation of complex multiplication according to the
10089 // constraints laid out in C11 Annex G. The implemention uses the
10090 // following naming scheme:
10091 // (a + ib) * (c + id)
10092 ComplexValue LHS = Result;
10093 APFloat &A = LHS.getComplexFloatReal();
10094 APFloat &B = LHS.getComplexFloatImag();
10095 APFloat &C = RHS.getComplexFloatReal();
10096 APFloat &D = RHS.getComplexFloatImag();
10097 APFloat &ResR = Result.getComplexFloatReal();
10098 APFloat &ResI = Result.getComplexFloatImag();
10100 assert(!RHSReal && "Cannot have two real operands for a complex op!");
10103 } else if (RHSReal) {
10107 // In the fully general case, we need to handle NaNs and infinities
10109 APFloat AC = A * C;
10110 APFloat BD = B * D;
10111 APFloat AD = A * D;
10112 APFloat BC = B * C;
10115 if (ResR.isNaN() && ResI.isNaN()) {
10116 bool Recalc = false;
10117 if (A.isInfinity() || B.isInfinity()) {
10118 A = APFloat::copySign(
10119 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10120 B = APFloat::copySign(
10121 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10123 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10125 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10128 if (C.isInfinity() || D.isInfinity()) {
10129 C = APFloat::copySign(
10130 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10131 D = APFloat::copySign(
10132 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10134 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10136 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10139 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10140 AD.isInfinity() || BC.isInfinity())) {
10142 A = APFloat::copySign(APFloat(A.getSemantics()), A);
10144 B = APFloat::copySign(APFloat(B.getSemantics()), B);
10146 C = APFloat::copySign(APFloat(C.getSemantics()), C);
10148 D = APFloat::copySign(APFloat(D.getSemantics()), D);
10152 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10153 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10158 ComplexValue LHS = Result;
10159 Result.getComplexIntReal() =
10160 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10161 LHS.getComplexIntImag() * RHS.getComplexIntImag());
10162 Result.getComplexIntImag() =
10163 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10164 LHS.getComplexIntImag() * RHS.getComplexIntReal());
10168 if (Result.isComplexFloat()) {
10169 // This is an implementation of complex division according to the
10170 // constraints laid out in C11 Annex G. The implemention uses the
10171 // following naming scheme:
10172 // (a + ib) / (c + id)
10173 ComplexValue LHS = Result;
10174 APFloat &A = LHS.getComplexFloatReal();
10175 APFloat &B = LHS.getComplexFloatImag();
10176 APFloat &C = RHS.getComplexFloatReal();
10177 APFloat &D = RHS.getComplexFloatImag();
10178 APFloat &ResR = Result.getComplexFloatReal();
10179 APFloat &ResI = Result.getComplexFloatImag();
10185 // No real optimizations we can do here, stub out with zero.
10186 B = APFloat::getZero(A.getSemantics());
10189 APFloat MaxCD = maxnum(abs(C), abs(D));
10190 if (MaxCD.isFinite()) {
10191 DenomLogB = ilogb(MaxCD);
10192 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10193 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10195 APFloat Denom = C * C + D * D;
10196 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10197 APFloat::rmNearestTiesToEven);
10198 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10199 APFloat::rmNearestTiesToEven);
10200 if (ResR.isNaN() && ResI.isNaN()) {
10201 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10202 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10203 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10204 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10206 A = APFloat::copySign(
10207 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10208 B = APFloat::copySign(
10209 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10210 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10211 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10212 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10213 C = APFloat::copySign(
10214 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10215 D = APFloat::copySign(
10216 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10217 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10218 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10223 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10224 return Error(E, diag::note_expr_divide_by_zero);
10226 ComplexValue LHS = Result;
10227 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10228 RHS.getComplexIntImag() * RHS.getComplexIntImag();
10229 Result.getComplexIntReal() =
10230 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10231 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10232 Result.getComplexIntImag() =
10233 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10234 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10242 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10243 // Get the operand value into 'Result'.
10244 if (!Visit(E->getSubExpr()))
10247 switch (E->getOpcode()) {
10253 // The result is always just the subexpr.
10256 if (Result.isComplexFloat()) {
10257 Result.getComplexFloatReal().changeSign();
10258 Result.getComplexFloatImag().changeSign();
10261 Result.getComplexIntReal() = -Result.getComplexIntReal();
10262 Result.getComplexIntImag() = -Result.getComplexIntImag();
10266 if (Result.isComplexFloat())
10267 Result.getComplexFloatImag().changeSign();
10269 Result.getComplexIntImag() = -Result.getComplexIntImag();
10274 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10275 if (E->getNumInits() == 2) {
10276 if (E->getType()->isComplexType()) {
10277 Result.makeComplexFloat();
10278 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10280 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10283 Result.makeComplexInt();
10284 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10286 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10291 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10294 //===----------------------------------------------------------------------===//
10295 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10296 // implicit conversion.
10297 //===----------------------------------------------------------------------===//
10300 class AtomicExprEvaluator :
10301 public ExprEvaluatorBase<AtomicExprEvaluator> {
10302 const LValue *This;
10305 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10306 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10308 bool Success(const APValue &V, const Expr *E) {
10313 bool ZeroInitialization(const Expr *E) {
10314 ImplicitValueInitExpr VIE(
10315 E->getType()->castAs<AtomicType>()->getValueType());
10316 // For atomic-qualified class (and array) types in C++, initialize the
10317 // _Atomic-wrapped subobject directly, in-place.
10318 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10319 : Evaluate(Result, Info, &VIE);
10322 bool VisitCastExpr(const CastExpr *E) {
10323 switch (E->getCastKind()) {
10325 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10326 case CK_NonAtomicToAtomic:
10327 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10328 : Evaluate(Result, Info, E->getSubExpr());
10332 } // end anonymous namespace
10334 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10336 assert(E->isRValue() && E->getType()->isAtomicType());
10337 return AtomicExprEvaluator(Info, This, Result).Visit(E);
10340 //===----------------------------------------------------------------------===//
10341 // Void expression evaluation, primarily for a cast to void on the LHS of a
10343 //===----------------------------------------------------------------------===//
10346 class VoidExprEvaluator
10347 : public ExprEvaluatorBase<VoidExprEvaluator> {
10349 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10351 bool Success(const APValue &V, const Expr *e) { return true; }
10353 bool ZeroInitialization(const Expr *E) { return true; }
10355 bool VisitCastExpr(const CastExpr *E) {
10356 switch (E->getCastKind()) {
10358 return ExprEvaluatorBaseTy::VisitCastExpr(E);
10360 VisitIgnoredValue(E->getSubExpr());
10365 bool VisitCallExpr(const CallExpr *E) {
10366 switch (E->getBuiltinCallee()) {
10368 return ExprEvaluatorBaseTy::VisitCallExpr(E);
10369 case Builtin::BI__assume:
10370 case Builtin::BI__builtin_assume:
10371 // The argument is not evaluated!
10376 } // end anonymous namespace
10378 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10379 assert(E->isRValue() && E->getType()->isVoidType());
10380 return VoidExprEvaluator(Info).Visit(E);
10383 //===----------------------------------------------------------------------===//
10384 // Top level Expr::EvaluateAsRValue method.
10385 //===----------------------------------------------------------------------===//
10387 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10388 // In C, function designators are not lvalues, but we evaluate them as if they
10390 QualType T = E->getType();
10391 if (E->isGLValue() || T->isFunctionType()) {
10393 if (!EvaluateLValue(E, LV, Info))
10395 LV.moveInto(Result);
10396 } else if (T->isVectorType()) {
10397 if (!EvaluateVector(E, Result, Info))
10399 } else if (T->isIntegralOrEnumerationType()) {
10400 if (!IntExprEvaluator(Info, Result).Visit(E))
10402 } else if (T->hasPointerRepresentation()) {
10404 if (!EvaluatePointer(E, LV, Info))
10406 LV.moveInto(Result);
10407 } else if (T->isRealFloatingType()) {
10408 llvm::APFloat F(0.0);
10409 if (!EvaluateFloat(E, F, Info))
10411 Result = APValue(F);
10412 } else if (T->isAnyComplexType()) {
10414 if (!EvaluateComplex(E, C, Info))
10416 C.moveInto(Result);
10417 } else if (T->isFixedPointType()) {
10418 if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10419 } else if (T->isMemberPointerType()) {
10421 if (!EvaluateMemberPointer(E, P, Info))
10423 P.moveInto(Result);
10425 } else if (T->isArrayType()) {
10427 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10428 if (!EvaluateArray(E, LV, Value, Info))
10431 } else if (T->isRecordType()) {
10433 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10434 if (!EvaluateRecord(E, LV, Value, Info))
10437 } else if (T->isVoidType()) {
10438 if (!Info.getLangOpts().CPlusPlus11)
10439 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10441 if (!EvaluateVoid(E, Info))
10443 } else if (T->isAtomicType()) {
10444 QualType Unqual = T.getAtomicUnqualifiedType();
10445 if (Unqual->isArrayType() || Unqual->isRecordType()) {
10447 APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10448 if (!EvaluateAtomic(E, &LV, Value, Info))
10451 if (!EvaluateAtomic(E, nullptr, Result, Info))
10454 } else if (Info.getLangOpts().CPlusPlus11) {
10455 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10465 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10466 /// cases, the in-place evaluation is essential, since later initializers for
10467 /// an object can indirectly refer to subobjects which were initialized earlier.
10468 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10469 const Expr *E, bool AllowNonLiteralTypes) {
10470 assert(!E->isValueDependent());
10472 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10475 if (E->isRValue()) {
10476 // Evaluate arrays and record types in-place, so that later initializers can
10477 // refer to earlier-initialized members of the object.
10478 QualType T = E->getType();
10479 if (T->isArrayType())
10480 return EvaluateArray(E, This, Result, Info);
10481 else if (T->isRecordType())
10482 return EvaluateRecord(E, This, Result, Info);
10483 else if (T->isAtomicType()) {
10484 QualType Unqual = T.getAtomicUnqualifiedType();
10485 if (Unqual->isArrayType() || Unqual->isRecordType())
10486 return EvaluateAtomic(E, &This, Result, Info);
10490 // For any other type, in-place evaluation is unimportant.
10491 return Evaluate(Result, Info, E);
10494 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10495 /// lvalue-to-rvalue cast if it is an lvalue.
10496 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10497 if (E->getType().isNull())
10500 if (!CheckLiteralType(Info, E))
10503 if (!::Evaluate(Result, Info, E))
10506 if (E->isGLValue()) {
10508 LV.setFrom(Info.Ctx, Result);
10509 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10513 // Check this core constant expression is a constant expression.
10514 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10517 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10518 const ASTContext &Ctx, bool &IsConst) {
10519 // Fast-path evaluations of integer literals, since we sometimes see files
10520 // containing vast quantities of these.
10521 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10522 Result.Val = APValue(APSInt(L->getValue(),
10523 L->getType()->isUnsignedIntegerType()));
10528 // This case should be rare, but we need to check it before we check on
10530 if (Exp->getType().isNull()) {
10535 // FIXME: Evaluating values of large array and record types can cause
10536 // performance problems. Only do so in C++11 for now.
10537 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10538 Exp->getType()->isRecordType()) &&
10539 !Ctx.getLangOpts().CPlusPlus11) {
10547 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10548 /// any crazy technique (that has nothing to do with language standards) that
10549 /// we want to. If this function returns true, it returns the folded constant
10550 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10551 /// will be applied to the result.
10552 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10554 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10557 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10558 return ::EvaluateAsRValue(Info, this, Result.Val);
10561 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10562 const ASTContext &Ctx) const {
10563 EvalResult Scratch;
10564 return EvaluateAsRValue(Scratch, Ctx) &&
10565 HandleConversionToBool(Scratch.Val, Result);
10568 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10569 Expr::SideEffectsKind SEK) {
10570 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10571 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10574 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10575 SideEffectsKind AllowSideEffects) const {
10576 if (!getType()->isIntegralOrEnumerationType())
10579 EvalResult ExprResult;
10580 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10581 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10584 Result = ExprResult.Val.getInt();
10588 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10589 SideEffectsKind AllowSideEffects) const {
10590 if (!getType()->isRealFloatingType())
10593 EvalResult ExprResult;
10594 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10595 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10598 Result = ExprResult.Val.getFloat();
10602 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10603 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10606 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10607 !CheckLValueConstantExpression(Info, getExprLoc(),
10608 Ctx.getLValueReferenceType(getType()), LV,
10609 Expr::EvaluateForCodeGen))
10612 LV.moveInto(Result.Val);
10616 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10617 const ASTContext &Ctx) const {
10618 EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10619 EvalInfo Info(Ctx, Result, EM);
10620 if (!::Evaluate(Result.Val, Info, this))
10623 return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10627 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10629 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10630 // FIXME: Evaluating initializers for large array and record types can cause
10631 // performance problems. Only do so in C++11 for now.
10632 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10633 !Ctx.getLangOpts().CPlusPlus11)
10636 Expr::EvalStatus EStatus;
10637 EStatus.Diag = &Notes;
10639 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10640 ? EvalInfo::EM_ConstantExpression
10641 : EvalInfo::EM_ConstantFold);
10642 InitInfo.setEvaluatingDecl(VD, Value);
10647 // C++11 [basic.start.init]p2:
10648 // Variables with static storage duration or thread storage duration shall be
10649 // zero-initialized before any other initialization takes place.
10650 // This behavior is not present in C.
10651 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10652 !VD->getType()->isReferenceType()) {
10653 ImplicitValueInitExpr VIE(VD->getType());
10654 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10655 /*AllowNonLiteralTypes=*/true))
10659 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10660 /*AllowNonLiteralTypes=*/true) ||
10661 EStatus.HasSideEffects)
10664 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10668 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10669 /// constant folded, but discard the result.
10670 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10672 return EvaluateAsRValue(Result, Ctx) &&
10673 !hasUnacceptableSideEffect(Result, SEK);
10676 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10677 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10678 EvalResult EvalResult;
10679 EvalResult.Diag = Diag;
10680 bool Result = EvaluateAsRValue(EvalResult, Ctx);
10682 assert(Result && "Could not evaluate expression");
10683 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10685 return EvalResult.Val.getInt();
10688 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10690 EvalResult EvalResult;
10691 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10692 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10693 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10697 bool Expr::EvalResult::isGlobalLValue() const {
10698 assert(Val.isLValue());
10699 return IsGlobalLValue(Val.getLValueBase());
10703 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10704 /// an integer constant expression.
10706 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10709 // CheckICE - This function does the fundamental ICE checking: the returned
10710 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10711 // and a (possibly null) SourceLocation indicating the location of the problem.
10713 // Note that to reduce code duplication, this helper does no evaluation
10714 // itself; the caller checks whether the expression is evaluatable, and
10715 // in the rare cases where CheckICE actually cares about the evaluated
10716 // value, it calls into Evaluate.
10721 /// This expression is an ICE.
10723 /// This expression is not an ICE, but if it isn't evaluated, it's
10724 /// a legal subexpression for an ICE. This return value is used to handle
10725 /// the comma operator in C99 mode, and non-constant subexpressions.
10726 IK_ICEIfUnevaluated,
10727 /// This expression is not an ICE, and is not a legal subexpression for one.
10733 SourceLocation Loc;
10735 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10740 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10742 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10744 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10745 Expr::EvalResult EVResult;
10746 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10747 !EVResult.Val.isInt())
10748 return ICEDiag(IK_NotICE, E->getLocStart());
10753 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10754 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10755 if (!E->getType()->isIntegralOrEnumerationType())
10756 return ICEDiag(IK_NotICE, E->getLocStart());
10758 switch (E->getStmtClass()) {
10759 #define ABSTRACT_STMT(Node)
10760 #define STMT(Node, Base) case Expr::Node##Class:
10761 #define EXPR(Node, Base)
10762 #include "clang/AST/StmtNodes.inc"
10763 case Expr::PredefinedExprClass:
10764 case Expr::FloatingLiteralClass:
10765 case Expr::ImaginaryLiteralClass:
10766 case Expr::StringLiteralClass:
10767 case Expr::ArraySubscriptExprClass:
10768 case Expr::OMPArraySectionExprClass:
10769 case Expr::MemberExprClass:
10770 case Expr::CompoundAssignOperatorClass:
10771 case Expr::CompoundLiteralExprClass:
10772 case Expr::ExtVectorElementExprClass:
10773 case Expr::DesignatedInitExprClass:
10774 case Expr::ArrayInitLoopExprClass:
10775 case Expr::ArrayInitIndexExprClass:
10776 case Expr::NoInitExprClass:
10777 case Expr::DesignatedInitUpdateExprClass:
10778 case Expr::ImplicitValueInitExprClass:
10779 case Expr::ParenListExprClass:
10780 case Expr::VAArgExprClass:
10781 case Expr::AddrLabelExprClass:
10782 case Expr::StmtExprClass:
10783 case Expr::CXXMemberCallExprClass:
10784 case Expr::CUDAKernelCallExprClass:
10785 case Expr::CXXDynamicCastExprClass:
10786 case Expr::CXXTypeidExprClass:
10787 case Expr::CXXUuidofExprClass:
10788 case Expr::MSPropertyRefExprClass:
10789 case Expr::MSPropertySubscriptExprClass:
10790 case Expr::CXXNullPtrLiteralExprClass:
10791 case Expr::UserDefinedLiteralClass:
10792 case Expr::CXXThisExprClass:
10793 case Expr::CXXThrowExprClass:
10794 case Expr::CXXNewExprClass:
10795 case Expr::CXXDeleteExprClass:
10796 case Expr::CXXPseudoDestructorExprClass:
10797 case Expr::UnresolvedLookupExprClass:
10798 case Expr::TypoExprClass:
10799 case Expr::DependentScopeDeclRefExprClass:
10800 case Expr::CXXConstructExprClass:
10801 case Expr::CXXInheritedCtorInitExprClass:
10802 case Expr::CXXStdInitializerListExprClass:
10803 case Expr::CXXBindTemporaryExprClass:
10804 case Expr::ExprWithCleanupsClass:
10805 case Expr::CXXTemporaryObjectExprClass:
10806 case Expr::CXXUnresolvedConstructExprClass:
10807 case Expr::CXXDependentScopeMemberExprClass:
10808 case Expr::UnresolvedMemberExprClass:
10809 case Expr::ObjCStringLiteralClass:
10810 case Expr::ObjCBoxedExprClass:
10811 case Expr::ObjCArrayLiteralClass:
10812 case Expr::ObjCDictionaryLiteralClass:
10813 case Expr::ObjCEncodeExprClass:
10814 case Expr::ObjCMessageExprClass:
10815 case Expr::ObjCSelectorExprClass:
10816 case Expr::ObjCProtocolExprClass:
10817 case Expr::ObjCIvarRefExprClass:
10818 case Expr::ObjCPropertyRefExprClass:
10819 case Expr::ObjCSubscriptRefExprClass:
10820 case Expr::ObjCIsaExprClass:
10821 case Expr::ObjCAvailabilityCheckExprClass:
10822 case Expr::ShuffleVectorExprClass:
10823 case Expr::ConvertVectorExprClass:
10824 case Expr::BlockExprClass:
10825 case Expr::NoStmtClass:
10826 case Expr::OpaqueValueExprClass:
10827 case Expr::PackExpansionExprClass:
10828 case Expr::SubstNonTypeTemplateParmPackExprClass:
10829 case Expr::FunctionParmPackExprClass:
10830 case Expr::AsTypeExprClass:
10831 case Expr::ObjCIndirectCopyRestoreExprClass:
10832 case Expr::MaterializeTemporaryExprClass:
10833 case Expr::PseudoObjectExprClass:
10834 case Expr::AtomicExprClass:
10835 case Expr::LambdaExprClass:
10836 case Expr::CXXFoldExprClass:
10837 case Expr::CoawaitExprClass:
10838 case Expr::DependentCoawaitExprClass:
10839 case Expr::CoyieldExprClass:
10840 return ICEDiag(IK_NotICE, E->getLocStart());
10842 case Expr::InitListExprClass: {
10843 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10844 // form "T x = { a };" is equivalent to "T x = a;".
10845 // Unless we're initializing a reference, T is a scalar as it is known to be
10846 // of integral or enumeration type.
10848 if (cast<InitListExpr>(E)->getNumInits() == 1)
10849 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10850 return ICEDiag(IK_NotICE, E->getLocStart());
10853 case Expr::SizeOfPackExprClass:
10854 case Expr::GNUNullExprClass:
10855 // GCC considers the GNU __null value to be an integral constant expression.
10858 case Expr::SubstNonTypeTemplateParmExprClass:
10860 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10862 case Expr::ParenExprClass:
10863 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10864 case Expr::GenericSelectionExprClass:
10865 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10866 case Expr::IntegerLiteralClass:
10867 case Expr::FixedPointLiteralClass:
10868 case Expr::CharacterLiteralClass:
10869 case Expr::ObjCBoolLiteralExprClass:
10870 case Expr::CXXBoolLiteralExprClass:
10871 case Expr::CXXScalarValueInitExprClass:
10872 case Expr::TypeTraitExprClass:
10873 case Expr::ArrayTypeTraitExprClass:
10874 case Expr::ExpressionTraitExprClass:
10875 case Expr::CXXNoexceptExprClass:
10877 case Expr::CallExprClass:
10878 case Expr::CXXOperatorCallExprClass: {
10879 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10880 // constant expressions, but they can never be ICEs because an ICE cannot
10881 // contain an operand of (pointer to) function type.
10882 const CallExpr *CE = cast<CallExpr>(E);
10883 if (CE->getBuiltinCallee())
10884 return CheckEvalInICE(E, Ctx);
10885 return ICEDiag(IK_NotICE, E->getLocStart());
10887 case Expr::DeclRefExprClass: {
10888 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10890 const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
10891 if (Ctx.getLangOpts().CPlusPlus &&
10892 D && IsConstNonVolatile(D->getType())) {
10893 // Parameter variables are never constants. Without this check,
10894 // getAnyInitializer() can find a default argument, which leads
10896 if (isa<ParmVarDecl>(D))
10897 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10900 // A variable of non-volatile const-qualified integral or enumeration
10901 // type initialized by an ICE can be used in ICEs.
10902 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10903 if (!Dcl->getType()->isIntegralOrEnumerationType())
10904 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10907 // Look for a declaration of this variable that has an initializer, and
10908 // check whether it is an ICE.
10909 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10912 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10915 return ICEDiag(IK_NotICE, E->getLocStart());
10917 case Expr::UnaryOperatorClass: {
10918 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10919 switch (Exp->getOpcode()) {
10927 // C99 6.6/3 allows increment and decrement within unevaluated
10928 // subexpressions of constant expressions, but they can never be ICEs
10929 // because an ICE cannot contain an lvalue operand.
10930 return ICEDiag(IK_NotICE, E->getLocStart());
10938 return CheckICE(Exp->getSubExpr(), Ctx);
10941 // OffsetOf falls through here.
10944 case Expr::OffsetOfExprClass: {
10945 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10946 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10947 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10948 // compliance: we should warn earlier for offsetof expressions with
10949 // array subscripts that aren't ICEs, and if the array subscripts
10950 // are ICEs, the value of the offsetof must be an integer constant.
10951 return CheckEvalInICE(E, Ctx);
10953 case Expr::UnaryExprOrTypeTraitExprClass: {
10954 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10955 if ((Exp->getKind() == UETT_SizeOf) &&
10956 Exp->getTypeOfArgument()->isVariableArrayType())
10957 return ICEDiag(IK_NotICE, E->getLocStart());
10960 case Expr::BinaryOperatorClass: {
10961 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10962 switch (Exp->getOpcode()) {
10976 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10977 // constant expressions, but they can never be ICEs because an ICE cannot
10978 // contain an lvalue operand.
10979 return ICEDiag(IK_NotICE, E->getLocStart());
10999 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11000 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11001 if (Exp->getOpcode() == BO_Div ||
11002 Exp->getOpcode() == BO_Rem) {
11003 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11004 // we don't evaluate one.
11005 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11006 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11008 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
11009 if (REval.isSigned() && REval.isAllOnesValue()) {
11010 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11011 if (LEval.isMinSignedValue())
11012 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
11016 if (Exp->getOpcode() == BO_Comma) {
11017 if (Ctx.getLangOpts().C99) {
11018 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11019 // if it isn't evaluated.
11020 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11021 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
11023 // In both C89 and C++, commas in ICEs are illegal.
11024 return ICEDiag(IK_NotICE, E->getLocStart());
11027 return Worst(LHSResult, RHSResult);
11031 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11032 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11033 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11034 // Rare case where the RHS has a comma "side-effect"; we need
11035 // to actually check the condition to see whether the side
11036 // with the comma is evaluated.
11037 if ((Exp->getOpcode() == BO_LAnd) !=
11038 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11043 return Worst(LHSResult, RHSResult);
11048 case Expr::ImplicitCastExprClass:
11049 case Expr::CStyleCastExprClass:
11050 case Expr::CXXFunctionalCastExprClass:
11051 case Expr::CXXStaticCastExprClass:
11052 case Expr::CXXReinterpretCastExprClass:
11053 case Expr::CXXConstCastExprClass:
11054 case Expr::ObjCBridgedCastExprClass: {
11055 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11056 if (isa<ExplicitCastExpr>(E)) {
11057 if (const FloatingLiteral *FL
11058 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11059 unsigned DestWidth = Ctx.getIntWidth(E->getType());
11060 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11061 APSInt IgnoredVal(DestWidth, !DestSigned);
11063 // If the value does not fit in the destination type, the behavior is
11064 // undefined, so we are not required to treat it as a constant
11066 if (FL->getValue().convertToInteger(IgnoredVal,
11067 llvm::APFloat::rmTowardZero,
11068 &Ignored) & APFloat::opInvalidOp)
11069 return ICEDiag(IK_NotICE, E->getLocStart());
11073 switch (cast<CastExpr>(E)->getCastKind()) {
11074 case CK_LValueToRValue:
11075 case CK_AtomicToNonAtomic:
11076 case CK_NonAtomicToAtomic:
11078 case CK_IntegralToBoolean:
11079 case CK_IntegralCast:
11080 return CheckICE(SubExpr, Ctx);
11082 return ICEDiag(IK_NotICE, E->getLocStart());
11085 case Expr::BinaryConditionalOperatorClass: {
11086 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11087 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11088 if (CommonResult.Kind == IK_NotICE) return CommonResult;
11089 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11090 if (FalseResult.Kind == IK_NotICE) return FalseResult;
11091 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11092 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11093 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11094 return FalseResult;
11096 case Expr::ConditionalOperatorClass: {
11097 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11098 // If the condition (ignoring parens) is a __builtin_constant_p call,
11099 // then only the true side is actually considered in an integer constant
11100 // expression, and it is fully evaluated. This is an important GNU
11101 // extension. See GCC PR38377 for discussion.
11102 if (const CallExpr *CallCE
11103 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11104 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11105 return CheckEvalInICE(E, Ctx);
11106 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11107 if (CondResult.Kind == IK_NotICE)
11110 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11111 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11113 if (TrueResult.Kind == IK_NotICE)
11115 if (FalseResult.Kind == IK_NotICE)
11116 return FalseResult;
11117 if (CondResult.Kind == IK_ICEIfUnevaluated)
11119 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11121 // Rare case where the diagnostics depend on which side is evaluated
11122 // Note that if we get here, CondResult is 0, and at least one of
11123 // TrueResult and FalseResult is non-zero.
11124 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11125 return FalseResult;
11128 case Expr::CXXDefaultArgExprClass:
11129 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11130 case Expr::CXXDefaultInitExprClass:
11131 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11132 case Expr::ChooseExprClass: {
11133 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11137 llvm_unreachable("Invalid StmtClass!");
11140 /// Evaluate an expression as a C++11 integral constant expression.
11141 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11143 llvm::APSInt *Value,
11144 SourceLocation *Loc) {
11145 if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11146 if (Loc) *Loc = E->getExprLoc();
11151 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11154 if (!Result.isInt()) {
11155 if (Loc) *Loc = E->getExprLoc();
11159 if (Value) *Value = Result.getInt();
11163 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11164 SourceLocation *Loc) const {
11165 if (Ctx.getLangOpts().CPlusPlus11)
11166 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11168 ICEDiag D = CheckICE(this, Ctx);
11169 if (D.Kind != IK_ICE) {
11170 if (Loc) *Loc = D.Loc;
11176 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11177 SourceLocation *Loc, bool isEvaluated) const {
11178 if (Ctx.getLangOpts().CPlusPlus11)
11179 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11181 if (!isIntegerConstantExpr(Ctx, Loc))
11183 // The only possible side-effects here are due to UB discovered in the
11184 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11185 // required to treat the expression as an ICE, so we produce the folded
11187 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
11188 llvm_unreachable("ICE cannot be evaluated!");
11192 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11193 return CheckICE(this, Ctx).Kind == IK_ICE;
11196 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11197 SourceLocation *Loc) const {
11198 // We support this checking in C++98 mode in order to diagnose compatibility
11200 assert(Ctx.getLangOpts().CPlusPlus);
11202 // Build evaluation settings.
11203 Expr::EvalStatus Status;
11204 SmallVector<PartialDiagnosticAt, 8> Diags;
11205 Status.Diag = &Diags;
11206 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11209 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11211 if (!Diags.empty()) {
11212 IsConstExpr = false;
11213 if (Loc) *Loc = Diags[0].first;
11214 } else if (!IsConstExpr) {
11215 // FIXME: This shouldn't happen.
11216 if (Loc) *Loc = getExprLoc();
11219 return IsConstExpr;
11222 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11223 const FunctionDecl *Callee,
11224 ArrayRef<const Expr*> Args,
11225 const Expr *This) const {
11226 Expr::EvalStatus Status;
11227 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11230 const LValue *ThisPtr = nullptr;
11233 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11234 assert(MD && "Don't provide `this` for non-methods.");
11235 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11237 if (EvaluateObjectArgument(Info, This, ThisVal))
11238 ThisPtr = &ThisVal;
11239 if (Info.EvalStatus.HasSideEffects)
11243 ArgVector ArgValues(Args.size());
11244 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11246 if ((*I)->isValueDependent() ||
11247 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11248 // If evaluation fails, throw away the argument entirely.
11249 ArgValues[I - Args.begin()] = APValue();
11250 if (Info.EvalStatus.HasSideEffects)
11254 // Build fake call to Callee.
11255 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11257 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11260 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11262 PartialDiagnosticAt> &Diags) {
11263 // FIXME: It would be useful to check constexpr function templates, but at the
11264 // moment the constant expression evaluator cannot cope with the non-rigorous
11265 // ASTs which we build for dependent expressions.
11266 if (FD->isDependentContext())
11269 Expr::EvalStatus Status;
11270 Status.Diag = &Diags;
11272 EvalInfo Info(FD->getASTContext(), Status,
11273 EvalInfo::EM_PotentialConstantExpression);
11275 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11276 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11278 // Fabricate an arbitrary expression on the stack and pretend that it
11279 // is a temporary being used as the 'this' pointer.
11281 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11282 This.set({&VIE, Info.CurrentCall->Index});
11284 ArrayRef<const Expr*> Args;
11287 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11288 // Evaluate the call as a constant initializer, to allow the construction
11289 // of objects of non-literal types.
11290 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11291 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11293 SourceLocation Loc = FD->getLocation();
11294 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11295 Args, FD->getBody(), Info, Scratch, nullptr);
11298 return Diags.empty();
11301 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11302 const FunctionDecl *FD,
11304 PartialDiagnosticAt> &Diags) {
11305 Expr::EvalStatus Status;
11306 Status.Diag = &Diags;
11308 EvalInfo Info(FD->getASTContext(), Status,
11309 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11311 // Fabricate a call stack frame to give the arguments a plausible cover story.
11312 ArrayRef<const Expr*> Args;
11313 ArgVector ArgValues(0);
11314 bool Success = EvaluateArgs(Args, ArgValues, Info);
11317 "Failed to set up arguments for potential constant evaluation");
11318 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11320 APValue ResultScratch;
11321 Evaluate(ResultScratch, Info, E);
11322 return Diags.empty();
11325 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11326 unsigned Type) const {
11327 if (!getType()->isPointerType())
11330 Expr::EvalStatus Status;
11331 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11332 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);