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 using namespace clang;
55 static bool IsGlobalLValue(APValue::LValueBase B);
59 struct CallStackFrame;
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67 const Expr *Base = B.get<const Expr*>();
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
81 return Inner->getType();
84 return Base->getType();
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
106 /// Determine whether this LValue path entry for a base class names a virtual
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
156 unsigned MostDerivedLength = 0;
157 Type = getType(Base);
159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
171 MostDerivedLength = I + 1;
173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
176 MostDerivedLength = I + 1;
179 // Path[I] describes a base class.
184 return MostDerivedLength;
187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190 CSK_This, CSK_Real, CSK_Imag
193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
198 unsigned Invalid : 1;
200 /// Is this a pointer one past the end of an object?
201 unsigned IsOnePastTheEnd : 1;
203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
206 /// Indicator of whether the most-derived object is an array element.
207 unsigned MostDerivedIsArrayElement : 1;
209 /// The length of the path to the most-derived object of which this is a
211 unsigned MostDerivedPathLength : 28;
213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
218 /// If the current array is an unsized array, the value of this is
220 uint64_t MostDerivedArraySize;
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
225 typedef APValue::LValuePathEntry PathEntry;
227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
230 SubobjectDesignator() : Invalid(true) {}
232 explicit SubobjectDesignator(QualType T)
233 : Invalid(false), IsOnePastTheEnd(false),
234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247 if (V.getLValueBase()) {
248 bool IsArray = false;
249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
252 MostDerivedIsArrayElement = IsArray;
262 /// Determine whether the most derived subobject is an array without a
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
291 return !isOnePastTheEnd();
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
300 Entry.ArrayIndex = 0;
301 Entries.push_back(Entry);
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
305 MostDerivedIsArrayElement = true;
306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
324 /// Update this designator to refer to the given base or member of this
326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
330 Entries.push_back(Entry);
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
335 MostDerivedIsArrayElement = false;
336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
349 MostDerivedIsArrayElement = true;
350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
355 /// Add N to the address of this subobject.
356 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357 if (Invalid || !N) return;
358 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359 if (isMostDerivedAnUnsizedArray()) {
360 // Can't verify -- trust that the user is doing the right thing (or if
361 // not, trust that the caller will catch the bad behavior).
362 // FIXME: Should we reject if this overflows, at least?
363 Entries.back().ArrayIndex += TruncatedN;
367 // [expr.add]p4: For the purposes of these operators, a pointer to a
368 // nonarray object behaves the same as a pointer to the first element of
369 // an array of length one with the type of the object as its element type.
370 bool IsArray = MostDerivedPathLength == Entries.size() &&
371 MostDerivedIsArrayElement;
372 uint64_t ArrayIndex =
373 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
375 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378 // Calculate the actual index in a wide enough type, so we can include
380 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381 (llvm::APInt&)N += ArrayIndex;
382 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383 diagnosePointerArithmetic(Info, E, N);
388 ArrayIndex += TruncatedN;
389 assert(ArrayIndex <= ArraySize &&
390 "bounds check succeeded for out-of-bounds index");
393 Entries.back().ArrayIndex = ArrayIndex;
395 IsOnePastTheEnd = (ArrayIndex != 0);
399 /// A stack frame in the constexpr call stack.
400 struct CallStackFrame {
403 /// Parent - The caller of this stack frame.
404 CallStackFrame *Caller;
406 /// Callee - The function which was called.
407 const FunctionDecl *Callee;
409 /// This - The binding for the this pointer in this call, if any.
412 /// Arguments - Parameter bindings for this function call, indexed by
413 /// parameters' function scope indices.
416 // Note that we intentionally use std::map here so that references to
417 // values are stable.
418 typedef std::map<const void*, APValue> MapTy;
419 typedef MapTy::const_iterator temp_iterator;
420 /// Temporaries - Temporary lvalues materialized within this stack frame.
423 /// CallLoc - The location of the call expression for this call.
424 SourceLocation CallLoc;
426 /// Index - The call index of this call.
429 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430 // on the overall stack usage of deeply-recursing constexpr evaluataions.
431 // (We should cache this map rather than recomputing it repeatedly.)
432 // But let's try this and see how it goes; we can look into caching the map
433 // as a later change.
435 /// LambdaCaptureFields - Mapping from captured variables/this to
436 /// corresponding data members in the closure class.
437 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438 FieldDecl *LambdaThisCaptureField;
440 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441 const FunctionDecl *Callee, const LValue *This,
445 APValue *getTemporary(const void *Key) {
446 MapTy::iterator I = Temporaries.find(Key);
447 return I == Temporaries.end() ? nullptr : &I->second;
449 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
452 /// Temporarily override 'this'.
453 class ThisOverrideRAII {
455 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456 : Frame(Frame), OldThis(Frame.This) {
458 Frame.This = NewThis;
460 ~ThisOverrideRAII() {
461 Frame.This = OldThis;
464 CallStackFrame &Frame;
465 const LValue *OldThis;
468 /// A partial diagnostic which we might know in advance that we are not going
470 class OptionalDiagnostic {
471 PartialDiagnostic *Diag;
474 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
478 OptionalDiagnostic &operator<<(const T &v) {
484 OptionalDiagnostic &operator<<(const APSInt &I) {
486 SmallVector<char, 32> Buffer;
488 *Diag << StringRef(Buffer.data(), Buffer.size());
493 OptionalDiagnostic &operator<<(const APFloat &F) {
495 // FIXME: Force the precision of the source value down so we don't
496 // print digits which are usually useless (we don't really care here if
497 // we truncate a digit by accident in edge cases). Ideally,
498 // APFloat::toString would automatically print the shortest
499 // representation which rounds to the correct value, but it's a bit
500 // tricky to implement.
502 llvm::APFloat::semanticsPrecision(F.getSemantics());
503 precision = (precision * 59 + 195) / 196;
504 SmallVector<char, 32> Buffer;
505 F.toString(Buffer, precision);
506 *Diag << StringRef(Buffer.data(), Buffer.size());
512 /// A cleanup, and a flag indicating whether it is lifetime-extended.
514 llvm::PointerIntPair<APValue*, 1, bool> Value;
517 Cleanup(APValue *Val, bool IsLifetimeExtended)
518 : Value(Val, IsLifetimeExtended) {}
520 bool isLifetimeExtended() const { return Value.getInt(); }
522 *Value.getPointer() = APValue();
526 /// EvalInfo - This is a private struct used by the evaluator to capture
527 /// information about a subexpression as it is folded. It retains information
528 /// about the AST context, but also maintains information about the folded
531 /// If an expression could be evaluated, it is still possible it is not a C
532 /// "integer constant expression" or constant expression. If not, this struct
533 /// captures information about how and why not.
535 /// One bit of information passed *into* the request for constant folding
536 /// indicates whether the subexpression is "evaluated" or not according to C
537 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
538 /// evaluate the expression regardless of what the RHS is, but C only allows
539 /// certain things in certain situations.
540 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
543 /// EvalStatus - Contains information about the evaluation.
544 Expr::EvalStatus &EvalStatus;
546 /// CurrentCall - The top of the constexpr call stack.
547 CallStackFrame *CurrentCall;
549 /// CallStackDepth - The number of calls in the call stack right now.
550 unsigned CallStackDepth;
552 /// NextCallIndex - The next call index to assign.
553 unsigned NextCallIndex;
555 /// StepsLeft - The remaining number of evaluation steps we're permitted
556 /// to perform. This is essentially a limit for the number of statements
557 /// we will evaluate.
560 /// BottomFrame - The frame in which evaluation started. This must be
561 /// initialized after CurrentCall and CallStackDepth.
562 CallStackFrame BottomFrame;
564 /// A stack of values whose lifetimes end at the end of some surrounding
565 /// evaluation frame.
566 llvm::SmallVector<Cleanup, 16> CleanupStack;
568 /// EvaluatingDecl - This is the declaration whose initializer is being
569 /// evaluated, if any.
570 APValue::LValueBase EvaluatingDecl;
572 /// EvaluatingDeclValue - This is the value being constructed for the
573 /// declaration whose initializer is being evaluated, if any.
574 APValue *EvaluatingDeclValue;
576 /// The current array initialization index, if we're performing array
578 uint64_t ArrayInitIndex = -1;
580 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
581 /// notes attached to it will also be stored, otherwise they will not be.
582 bool HasActiveDiagnostic;
584 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
585 /// fold (not just why it's not strictly a constant expression)?
586 bool HasFoldFailureDiagnostic;
588 /// \brief Whether or not we're currently speculatively evaluating.
589 bool IsSpeculativelyEvaluating;
591 enum EvaluationMode {
592 /// Evaluate as a constant expression. Stop if we find that the expression
593 /// is not a constant expression.
594 EM_ConstantExpression,
596 /// Evaluate as a potential constant expression. Keep going if we hit a
597 /// construct that we can't evaluate yet (because we don't yet know the
598 /// value of something) but stop if we hit something that could never be
599 /// a constant expression.
600 EM_PotentialConstantExpression,
602 /// Fold the expression to a constant. Stop if we hit a side-effect that
606 /// Evaluate the expression looking for integer overflow and similar
607 /// issues. Don't worry about side-effects, and try to visit all
609 EM_EvaluateForOverflow,
611 /// Evaluate in any way we know how. Don't worry about side-effects that
612 /// can't be modeled.
613 EM_IgnoreSideEffects,
615 /// Evaluate as a constant expression. Stop if we find that the expression
616 /// is not a constant expression. Some expressions can be retried in the
617 /// optimizer if we don't constant fold them here, but in an unevaluated
618 /// context we try to fold them immediately since the optimizer never
619 /// gets a chance to look at it.
620 EM_ConstantExpressionUnevaluated,
622 /// Evaluate as a potential constant expression. Keep going if we hit a
623 /// construct that we can't evaluate yet (because we don't yet know the
624 /// value of something) but stop if we hit something that could never be
625 /// a constant expression. Some expressions can be retried in the
626 /// optimizer if we don't constant fold them here, but in an unevaluated
627 /// context we try to fold them immediately since the optimizer never
628 /// gets a chance to look at it.
629 EM_PotentialConstantExpressionUnevaluated,
631 /// Evaluate as a constant expression. In certain scenarios, if:
632 /// - we find a MemberExpr with a base that can't be evaluated, or
633 /// - we find a variable initialized with a call to a function that has
634 /// the alloc_size attribute on it
635 /// then we may consider evaluation to have succeeded.
637 /// In either case, the LValue returned shall have an invalid base; in the
638 /// former, the base will be the invalid MemberExpr, in the latter, the
639 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
644 /// Are we checking whether the expression is a potential constant
646 bool checkingPotentialConstantExpression() const {
647 return EvalMode == EM_PotentialConstantExpression ||
648 EvalMode == EM_PotentialConstantExpressionUnevaluated;
651 /// Are we checking an expression for overflow?
652 // FIXME: We should check for any kind of undefined or suspicious behavior
653 // in such constructs, not just overflow.
654 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
656 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
657 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
658 CallStackDepth(0), NextCallIndex(1),
659 StepsLeft(getLangOpts().ConstexprStepLimit),
660 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
661 EvaluatingDecl((const ValueDecl *)nullptr),
662 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
663 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
666 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
667 EvaluatingDecl = Base;
668 EvaluatingDeclValue = &Value;
671 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
673 bool CheckCallLimit(SourceLocation Loc) {
674 // Don't perform any constexpr calls (other than the call we're checking)
675 // when checking a potential constant expression.
676 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
678 if (NextCallIndex == 0) {
679 // NextCallIndex has wrapped around.
680 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
683 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
685 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
686 << getLangOpts().ConstexprCallDepth;
690 CallStackFrame *getCallFrame(unsigned CallIndex) {
691 assert(CallIndex && "no call index in getCallFrame");
692 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
693 // be null in this loop.
694 CallStackFrame *Frame = CurrentCall;
695 while (Frame->Index > CallIndex)
696 Frame = Frame->Caller;
697 return (Frame->Index == CallIndex) ? Frame : nullptr;
700 bool nextStep(const Stmt *S) {
702 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
710 /// Add a diagnostic to the diagnostics list.
711 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
712 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
713 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
714 return EvalStatus.Diag->back().second;
717 /// Add notes containing a call stack to the current point of evaluation.
718 void addCallStack(unsigned Limit);
721 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
722 unsigned ExtraNotes, bool IsCCEDiag) {
724 if (EvalStatus.Diag) {
725 // If we have a prior diagnostic, it will be noting that the expression
726 // isn't a constant expression. This diagnostic is more important,
727 // unless we require this evaluation to produce a constant expression.
729 // FIXME: We might want to show both diagnostics to the user in
730 // EM_ConstantFold mode.
731 if (!EvalStatus.Diag->empty()) {
733 case EM_ConstantFold:
734 case EM_IgnoreSideEffects:
735 case EM_EvaluateForOverflow:
736 if (!HasFoldFailureDiagnostic)
738 // We've already failed to fold something. Keep that diagnostic.
739 case EM_ConstantExpression:
740 case EM_PotentialConstantExpression:
741 case EM_ConstantExpressionUnevaluated:
742 case EM_PotentialConstantExpressionUnevaluated:
744 HasActiveDiagnostic = false;
745 return OptionalDiagnostic();
749 unsigned CallStackNotes = CallStackDepth - 1;
750 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
752 CallStackNotes = std::min(CallStackNotes, Limit + 1);
753 if (checkingPotentialConstantExpression())
756 HasActiveDiagnostic = true;
757 HasFoldFailureDiagnostic = !IsCCEDiag;
758 EvalStatus.Diag->clear();
759 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
760 addDiag(Loc, DiagId);
761 if (!checkingPotentialConstantExpression())
763 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
765 HasActiveDiagnostic = false;
766 return OptionalDiagnostic();
769 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
771 FFDiag(SourceLocation Loc,
772 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
773 unsigned ExtraNotes = 0) {
774 return Diag(Loc, DiagId, ExtraNotes, false);
777 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
778 = diag::note_invalid_subexpr_in_const_expr,
779 unsigned ExtraNotes = 0) {
781 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
782 HasActiveDiagnostic = false;
783 return OptionalDiagnostic();
786 /// Diagnose that the evaluation does not produce a C++11 core constant
789 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
790 /// EM_PotentialConstantExpression mode and we produce one of these.
791 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
792 = diag::note_invalid_subexpr_in_const_expr,
793 unsigned ExtraNotes = 0) {
794 // Don't override a previous diagnostic. Don't bother collecting
795 // diagnostics if we're evaluating for overflow.
796 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
797 HasActiveDiagnostic = false;
798 return OptionalDiagnostic();
800 return Diag(Loc, DiagId, ExtraNotes, true);
802 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
803 = diag::note_invalid_subexpr_in_const_expr,
804 unsigned ExtraNotes = 0) {
805 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
807 /// Add a note to a prior diagnostic.
808 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
809 if (!HasActiveDiagnostic)
810 return OptionalDiagnostic();
811 return OptionalDiagnostic(&addDiag(Loc, DiagId));
814 /// Add a stack of notes to a prior diagnostic.
815 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
816 if (HasActiveDiagnostic) {
817 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
818 Diags.begin(), Diags.end());
822 /// Should we continue evaluation after encountering a side-effect that we
824 bool keepEvaluatingAfterSideEffect() {
826 case EM_PotentialConstantExpression:
827 case EM_PotentialConstantExpressionUnevaluated:
828 case EM_EvaluateForOverflow:
829 case EM_IgnoreSideEffects:
832 case EM_ConstantExpression:
833 case EM_ConstantExpressionUnevaluated:
834 case EM_ConstantFold:
838 llvm_unreachable("Missed EvalMode case");
841 /// Note that we have had a side-effect, and determine whether we should
843 bool noteSideEffect() {
844 EvalStatus.HasSideEffects = true;
845 return keepEvaluatingAfterSideEffect();
848 /// Should we continue evaluation after encountering undefined behavior?
849 bool keepEvaluatingAfterUndefinedBehavior() {
851 case EM_EvaluateForOverflow:
852 case EM_IgnoreSideEffects:
853 case EM_ConstantFold:
857 case EM_PotentialConstantExpression:
858 case EM_PotentialConstantExpressionUnevaluated:
859 case EM_ConstantExpression:
860 case EM_ConstantExpressionUnevaluated:
863 llvm_unreachable("Missed EvalMode case");
866 /// Note that we hit something that was technically undefined behavior, but
867 /// that we can evaluate past it (such as signed overflow or floating-point
868 /// division by zero.)
869 bool noteUndefinedBehavior() {
870 EvalStatus.HasUndefinedBehavior = true;
871 return keepEvaluatingAfterUndefinedBehavior();
874 /// Should we continue evaluation as much as possible after encountering a
875 /// construct which can't be reduced to a value?
876 bool keepEvaluatingAfterFailure() {
881 case EM_PotentialConstantExpression:
882 case EM_PotentialConstantExpressionUnevaluated:
883 case EM_EvaluateForOverflow:
886 case EM_ConstantExpression:
887 case EM_ConstantExpressionUnevaluated:
888 case EM_ConstantFold:
889 case EM_IgnoreSideEffects:
893 llvm_unreachable("Missed EvalMode case");
896 /// Notes that we failed to evaluate an expression that other expressions
897 /// directly depend on, and determine if we should keep evaluating. This
898 /// should only be called if we actually intend to keep evaluating.
900 /// Call noteSideEffect() instead if we may be able to ignore the value that
901 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
903 /// (Foo(), 1) // use noteSideEffect
904 /// (Foo() || true) // use noteSideEffect
905 /// Foo() + 1 // use noteFailure
906 LLVM_NODISCARD bool noteFailure() {
907 // Failure when evaluating some expression often means there is some
908 // subexpression whose evaluation was skipped. Therefore, (because we
909 // don't track whether we skipped an expression when unwinding after an
910 // evaluation failure) every evaluation failure that bubbles up from a
911 // subexpression implies that a side-effect has potentially happened. We
912 // skip setting the HasSideEffects flag to true until we decide to
913 // continue evaluating after that point, which happens here.
914 bool KeepGoing = keepEvaluatingAfterFailure();
915 EvalStatus.HasSideEffects |= KeepGoing;
919 class ArrayInitLoopIndex {
924 ArrayInitLoopIndex(EvalInfo &Info)
925 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
926 Info.ArrayInitIndex = 0;
928 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
930 operator uint64_t&() { return Info.ArrayInitIndex; }
934 /// Object used to treat all foldable expressions as constant expressions.
935 struct FoldConstant {
938 bool HadNoPriorDiags;
939 EvalInfo::EvaluationMode OldMode;
941 explicit FoldConstant(EvalInfo &Info, bool Enabled)
944 HadNoPriorDiags(Info.EvalStatus.Diag &&
945 Info.EvalStatus.Diag->empty() &&
946 !Info.EvalStatus.HasSideEffects),
947 OldMode(Info.EvalMode) {
949 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
950 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
951 Info.EvalMode = EvalInfo::EM_ConstantFold;
953 void keepDiagnostics() { Enabled = false; }
955 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
956 !Info.EvalStatus.HasSideEffects)
957 Info.EvalStatus.Diag->clear();
958 Info.EvalMode = OldMode;
962 /// RAII object used to treat the current evaluation as the correct pointer
963 /// offset fold for the current EvalMode
964 struct FoldOffsetRAII {
966 EvalInfo::EvaluationMode OldMode;
967 explicit FoldOffsetRAII(EvalInfo &Info)
968 : Info(Info), OldMode(Info.EvalMode) {
969 if (!Info.checkingPotentialConstantExpression())
970 Info.EvalMode = EvalInfo::EM_OffsetFold;
973 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
976 /// RAII object used to optionally suppress diagnostics and side-effects from
977 /// a speculative evaluation.
978 class SpeculativeEvaluationRAII {
979 /// Pair of EvalInfo, and a bit that stores whether or not we were
980 /// speculatively evaluating when we created this RAII.
981 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
982 Expr::EvalStatus Old;
984 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
985 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
987 Other.InfoAndOldSpecEval.setPointer(nullptr);
990 void maybeRestoreState() {
991 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
995 Info->EvalStatus = Old;
996 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
1000 SpeculativeEvaluationRAII() = default;
1002 SpeculativeEvaluationRAII(
1003 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1004 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1005 Old(Info.EvalStatus) {
1006 Info.EvalStatus.Diag = NewDiag;
1007 Info.IsSpeculativelyEvaluating = true;
1010 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1011 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1012 moveFromAndCancel(std::move(Other));
1015 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1016 maybeRestoreState();
1017 moveFromAndCancel(std::move(Other));
1021 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1024 /// RAII object wrapping a full-expression or block scope, and handling
1025 /// the ending of the lifetime of temporaries created within it.
1026 template<bool IsFullExpression>
1029 unsigned OldStackSize;
1031 ScopeRAII(EvalInfo &Info)
1032 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1034 // Body moved to a static method to encourage the compiler to inline away
1035 // instances of this class.
1036 cleanup(Info, OldStackSize);
1039 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1040 unsigned NewEnd = OldStackSize;
1041 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1043 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1044 // Full-expression cleanup of a lifetime-extended temporary: nothing
1045 // to do, just move this cleanup to the right place in the stack.
1046 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1049 // End the lifetime of the object.
1050 Info.CleanupStack[I].endLifetime();
1053 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1054 Info.CleanupStack.end());
1057 typedef ScopeRAII<false> BlockScopeRAII;
1058 typedef ScopeRAII<true> FullExpressionRAII;
1061 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1062 CheckSubobjectKind CSK) {
1065 if (isOnePastTheEnd()) {
1066 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1074 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1077 // If we're complaining, we must be able to statically determine the size of
1078 // the most derived array.
1079 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1080 Info.CCEDiag(E, diag::note_constexpr_array_index)
1082 << static_cast<unsigned>(getMostDerivedArraySize());
1084 Info.CCEDiag(E, diag::note_constexpr_array_index)
1085 << N << /*non-array*/ 1;
1089 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1090 const FunctionDecl *Callee, const LValue *This,
1092 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1093 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1094 Info.CurrentCall = this;
1095 ++Info.CallStackDepth;
1098 CallStackFrame::~CallStackFrame() {
1099 assert(Info.CurrentCall == this && "calls retired out of order");
1100 --Info.CallStackDepth;
1101 Info.CurrentCall = Caller;
1104 APValue &CallStackFrame::createTemporary(const void *Key,
1105 bool IsLifetimeExtended) {
1106 APValue &Result = Temporaries[Key];
1107 assert(Result.isUninit() && "temporary created multiple times");
1108 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1112 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1114 void EvalInfo::addCallStack(unsigned Limit) {
1115 // Determine which calls to skip, if any.
1116 unsigned ActiveCalls = CallStackDepth - 1;
1117 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1118 if (Limit && Limit < ActiveCalls) {
1119 SkipStart = Limit / 2 + Limit % 2;
1120 SkipEnd = ActiveCalls - Limit / 2;
1123 // Walk the call stack and add the diagnostics.
1124 unsigned CallIdx = 0;
1125 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1126 Frame = Frame->Caller, ++CallIdx) {
1128 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1129 if (CallIdx == SkipStart) {
1130 // Note that we're skipping calls.
1131 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1132 << unsigned(ActiveCalls - Limit);
1137 // Use a different note for an inheriting constructor, because from the
1138 // user's perspective it's not really a function at all.
1139 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1140 if (CD->isInheritingConstructor()) {
1141 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1147 SmallVector<char, 128> Buffer;
1148 llvm::raw_svector_ostream Out(Buffer);
1149 describeCall(Frame, Out);
1150 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1155 struct ComplexValue {
1160 APSInt IntReal, IntImag;
1161 APFloat FloatReal, FloatImag;
1163 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1165 void makeComplexFloat() { IsInt = false; }
1166 bool isComplexFloat() const { return !IsInt; }
1167 APFloat &getComplexFloatReal() { return FloatReal; }
1168 APFloat &getComplexFloatImag() { return FloatImag; }
1170 void makeComplexInt() { IsInt = true; }
1171 bool isComplexInt() const { return IsInt; }
1172 APSInt &getComplexIntReal() { return IntReal; }
1173 APSInt &getComplexIntImag() { return IntImag; }
1175 void moveInto(APValue &v) const {
1176 if (isComplexFloat())
1177 v = APValue(FloatReal, FloatImag);
1179 v = APValue(IntReal, IntImag);
1181 void setFrom(const APValue &v) {
1182 assert(v.isComplexFloat() || v.isComplexInt());
1183 if (v.isComplexFloat()) {
1185 FloatReal = v.getComplexFloatReal();
1186 FloatImag = v.getComplexFloatImag();
1189 IntReal = v.getComplexIntReal();
1190 IntImag = v.getComplexIntImag();
1196 APValue::LValueBase Base;
1198 unsigned InvalidBase : 1;
1199 unsigned CallIndex : 31;
1200 SubobjectDesignator Designator;
1203 const APValue::LValueBase getLValueBase() const { return Base; }
1204 CharUnits &getLValueOffset() { return Offset; }
1205 const CharUnits &getLValueOffset() const { return Offset; }
1206 unsigned getLValueCallIndex() const { return CallIndex; }
1207 SubobjectDesignator &getLValueDesignator() { return Designator; }
1208 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1209 bool isNullPointer() const { return IsNullPtr;}
1211 void moveInto(APValue &V) const {
1212 if (Designator.Invalid)
1213 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1216 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1217 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1218 "Unsized array with a valid base?");
1219 V = APValue(Base, Offset, Designator.Entries,
1220 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1223 void setFrom(ASTContext &Ctx, const APValue &V) {
1224 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1225 Base = V.getLValueBase();
1226 Offset = V.getLValueOffset();
1227 InvalidBase = false;
1228 CallIndex = V.getLValueCallIndex();
1229 Designator = SubobjectDesignator(Ctx, V);
1230 IsNullPtr = V.isNullPointer();
1233 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1234 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1236 // We only allow a few types of invalid bases. Enforce that here.
1238 const auto *E = B.get<const Expr *>();
1239 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1240 "Unexpected type of invalid base");
1245 Offset = CharUnits::fromQuantity(Offset_);
1246 InvalidBase = BInvalid;
1248 Designator = SubobjectDesignator(getType(B));
1249 IsNullPtr = IsNullPtr_;
1252 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1256 // Check that this LValue is not based on a null pointer. If it is, produce
1257 // a diagnostic and mark the designator as invalid.
1258 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1259 CheckSubobjectKind CSK) {
1260 if (Designator.Invalid)
1263 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1265 Designator.setInvalid();
1271 // Check this LValue refers to an object. If not, set the designator to be
1272 // invalid and emit a diagnostic.
1273 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1274 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1275 Designator.checkSubobject(Info, E, CSK);
1278 void addDecl(EvalInfo &Info, const Expr *E,
1279 const Decl *D, bool Virtual = false) {
1280 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1281 Designator.addDeclUnchecked(D, Virtual);
1283 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1284 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1285 assert(isBaseAnAllocSizeCall(Base) &&
1286 "Only alloc_size bases can have unsized arrays");
1287 Designator.FirstEntryIsAnUnsizedArray = true;
1288 Designator.addUnsizedArrayUnchecked(ElemTy);
1290 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1291 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1292 Designator.addArrayUnchecked(CAT);
1294 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1295 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1296 Designator.addComplexUnchecked(EltTy, Imag);
1298 void clearIsNullPointer() {
1301 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1302 const APSInt &Index, CharUnits ElementSize) {
1303 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1304 // but we're not required to diagnose it and it's valid in C++.)
1308 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1309 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1311 uint64_t Offset64 = Offset.getQuantity();
1312 uint64_t ElemSize64 = ElementSize.getQuantity();
1313 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1314 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1316 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1317 Designator.adjustIndex(Info, E, Index);
1318 clearIsNullPointer();
1320 void adjustOffset(CharUnits N) {
1322 if (N.getQuantity())
1323 clearIsNullPointer();
1329 explicit MemberPtr(const ValueDecl *Decl) :
1330 DeclAndIsDerivedMember(Decl, false), Path() {}
1332 /// The member or (direct or indirect) field referred to by this member
1333 /// pointer, or 0 if this is a null member pointer.
1334 const ValueDecl *getDecl() const {
1335 return DeclAndIsDerivedMember.getPointer();
1337 /// Is this actually a member of some type derived from the relevant class?
1338 bool isDerivedMember() const {
1339 return DeclAndIsDerivedMember.getInt();
1341 /// Get the class which the declaration actually lives in.
1342 const CXXRecordDecl *getContainingRecord() const {
1343 return cast<CXXRecordDecl>(
1344 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1347 void moveInto(APValue &V) const {
1348 V = APValue(getDecl(), isDerivedMember(), Path);
1350 void setFrom(const APValue &V) {
1351 assert(V.isMemberPointer());
1352 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1353 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1355 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1356 Path.insert(Path.end(), P.begin(), P.end());
1359 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1360 /// whether the member is a member of some class derived from the class type
1361 /// of the member pointer.
1362 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1363 /// Path - The path of base/derived classes from the member declaration's
1364 /// class (exclusive) to the class type of the member pointer (inclusive).
1365 SmallVector<const CXXRecordDecl*, 4> Path;
1367 /// Perform a cast towards the class of the Decl (either up or down the
1369 bool castBack(const CXXRecordDecl *Class) {
1370 assert(!Path.empty());
1371 const CXXRecordDecl *Expected;
1372 if (Path.size() >= 2)
1373 Expected = Path[Path.size() - 2];
1375 Expected = getContainingRecord();
1376 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1377 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1378 // if B does not contain the original member and is not a base or
1379 // derived class of the class containing the original member, the result
1380 // of the cast is undefined.
1381 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1382 // (D::*). We consider that to be a language defect.
1388 /// Perform a base-to-derived member pointer cast.
1389 bool castToDerived(const CXXRecordDecl *Derived) {
1392 if (!isDerivedMember()) {
1393 Path.push_back(Derived);
1396 if (!castBack(Derived))
1399 DeclAndIsDerivedMember.setInt(false);
1402 /// Perform a derived-to-base member pointer cast.
1403 bool castToBase(const CXXRecordDecl *Base) {
1407 DeclAndIsDerivedMember.setInt(true);
1408 if (isDerivedMember()) {
1409 Path.push_back(Base);
1412 return castBack(Base);
1416 /// Compare two member pointers, which are assumed to be of the same type.
1417 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1418 if (!LHS.getDecl() || !RHS.getDecl())
1419 return !LHS.getDecl() && !RHS.getDecl();
1420 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1422 return LHS.Path == RHS.Path;
1426 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1427 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1428 const LValue &This, const Expr *E,
1429 bool AllowNonLiteralTypes = false);
1430 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1431 bool InvalidBaseOK = false);
1432 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1433 bool InvalidBaseOK = false);
1434 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1436 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1437 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1438 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1440 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1441 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1442 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1444 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1446 //===----------------------------------------------------------------------===//
1448 //===----------------------------------------------------------------------===//
1450 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1451 /// preserving its value (by extending by up to one bit as needed).
1452 static void negateAsSigned(APSInt &Int) {
1453 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1454 Int = Int.extend(Int.getBitWidth() + 1);
1455 Int.setIsSigned(true);
1460 /// Produce a string describing the given constexpr call.
1461 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1462 unsigned ArgIndex = 0;
1463 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1464 !isa<CXXConstructorDecl>(Frame->Callee) &&
1465 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1468 Out << *Frame->Callee << '(';
1470 if (Frame->This && IsMemberCall) {
1472 Frame->This->moveInto(Val);
1473 Val.printPretty(Out, Frame->Info.Ctx,
1474 Frame->This->Designator.MostDerivedType);
1475 // FIXME: Add parens around Val if needed.
1476 Out << "->" << *Frame->Callee << '(';
1477 IsMemberCall = false;
1480 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1481 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1482 if (ArgIndex > (unsigned)IsMemberCall)
1485 const ParmVarDecl *Param = *I;
1486 const APValue &Arg = Frame->Arguments[ArgIndex];
1487 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1489 if (ArgIndex == 0 && IsMemberCall)
1490 Out << "->" << *Frame->Callee << '(';
1496 /// Evaluate an expression to see if it had side-effects, and discard its
1498 /// \return \c true if the caller should keep evaluating.
1499 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1501 if (!Evaluate(Scratch, Info, E))
1502 // We don't need the value, but we might have skipped a side effect here.
1503 return Info.noteSideEffect();
1507 /// Should this call expression be treated as a string literal?
1508 static bool IsStringLiteralCall(const CallExpr *E) {
1509 unsigned Builtin = E->getBuiltinCallee();
1510 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1511 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1514 static bool IsGlobalLValue(APValue::LValueBase B) {
1515 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1516 // constant expression of pointer type that evaluates to...
1518 // ... a null pointer value, or a prvalue core constant expression of type
1520 if (!B) return true;
1522 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1523 // ... the address of an object with static storage duration,
1524 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1525 return VD->hasGlobalStorage();
1526 // ... the address of a function,
1527 return isa<FunctionDecl>(D);
1530 const Expr *E = B.get<const Expr*>();
1531 switch (E->getStmtClass()) {
1534 case Expr::CompoundLiteralExprClass: {
1535 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1536 return CLE->isFileScope() && CLE->isLValue();
1538 case Expr::MaterializeTemporaryExprClass:
1539 // A materialized temporary might have been lifetime-extended to static
1540 // storage duration.
1541 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1542 // A string literal has static storage duration.
1543 case Expr::StringLiteralClass:
1544 case Expr::PredefinedExprClass:
1545 case Expr::ObjCStringLiteralClass:
1546 case Expr::ObjCEncodeExprClass:
1547 case Expr::CXXTypeidExprClass:
1548 case Expr::CXXUuidofExprClass:
1550 case Expr::CallExprClass:
1551 return IsStringLiteralCall(cast<CallExpr>(E));
1552 // For GCC compatibility, &&label has static storage duration.
1553 case Expr::AddrLabelExprClass:
1555 // A Block literal expression may be used as the initialization value for
1556 // Block variables at global or local static scope.
1557 case Expr::BlockExprClass:
1558 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1559 case Expr::ImplicitValueInitExprClass:
1561 // We can never form an lvalue with an implicit value initialization as its
1562 // base through expression evaluation, so these only appear in one case: the
1563 // implicit variable declaration we invent when checking whether a constexpr
1564 // constructor can produce a constant expression. We must assume that such
1565 // an expression might be a global lvalue.
1570 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1571 assert(Base && "no location for a null lvalue");
1572 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1574 Info.Note(VD->getLocation(), diag::note_declared_at);
1576 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1577 diag::note_constexpr_temporary_here);
1580 /// Check that this reference or pointer core constant expression is a valid
1581 /// value for an address or reference constant expression. Return true if we
1582 /// can fold this expression, whether or not it's a constant expression.
1583 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1584 QualType Type, const LValue &LVal) {
1585 bool IsReferenceType = Type->isReferenceType();
1587 APValue::LValueBase Base = LVal.getLValueBase();
1588 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1590 // Check that the object is a global. Note that the fake 'this' object we
1591 // manufacture when checking potential constant expressions is conservatively
1592 // assumed to be global here.
1593 if (!IsGlobalLValue(Base)) {
1594 if (Info.getLangOpts().CPlusPlus11) {
1595 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1596 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1597 << IsReferenceType << !Designator.Entries.empty()
1599 NoteLValueLocation(Info, Base);
1603 // Don't allow references to temporaries to escape.
1606 assert((Info.checkingPotentialConstantExpression() ||
1607 LVal.getLValueCallIndex() == 0) &&
1608 "have call index for global lvalue");
1610 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1611 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1612 // Check if this is a thread-local variable.
1613 if (Var->getTLSKind())
1616 // A dllimport variable never acts like a constant.
1617 if (Var->hasAttr<DLLImportAttr>())
1620 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1621 // __declspec(dllimport) must be handled very carefully:
1622 // We must never initialize an expression with the thunk in C++.
1623 // Doing otherwise would allow the same id-expression to yield
1624 // different addresses for the same function in different translation
1625 // units. However, this means that we must dynamically initialize the
1626 // expression with the contents of the import address table at runtime.
1628 // The C language has no notion of ODR; furthermore, it has no notion of
1629 // dynamic initialization. This means that we are permitted to
1630 // perform initialization with the address of the thunk.
1631 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1636 // Allow address constant expressions to be past-the-end pointers. This is
1637 // an extension: the standard requires them to point to an object.
1638 if (!IsReferenceType)
1641 // A reference constant expression must refer to an object.
1643 // FIXME: diagnostic
1648 // Does this refer one past the end of some object?
1649 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1650 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1651 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1652 << !Designator.Entries.empty() << !!VD << VD;
1653 NoteLValueLocation(Info, Base);
1659 /// Check that this core constant expression is of literal type, and if not,
1660 /// produce an appropriate diagnostic.
1661 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1662 const LValue *This = nullptr) {
1663 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1666 // C++1y: A constant initializer for an object o [...] may also invoke
1667 // constexpr constructors for o and its subobjects even if those objects
1668 // are of non-literal class types.
1670 // C++11 missed this detail for aggregates, so classes like this:
1671 // struct foo_t { union { int i; volatile int j; } u; };
1672 // are not (obviously) initializable like so:
1673 // __attribute__((__require_constant_initialization__))
1674 // static const foo_t x = {{0}};
1675 // because "i" is a subobject with non-literal initialization (due to the
1676 // volatile member of the union). See:
1677 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1678 // Therefore, we use the C++1y behavior.
1679 if (This && Info.EvaluatingDecl == This->getLValueBase())
1682 // Prvalue constant expressions must be of literal types.
1683 if (Info.getLangOpts().CPlusPlus11)
1684 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1687 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1691 /// Check that this core constant expression value is a valid value for a
1692 /// constant expression. If not, report an appropriate diagnostic. Does not
1693 /// check that the expression is of literal type.
1694 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1695 QualType Type, const APValue &Value) {
1696 if (Value.isUninit()) {
1697 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1702 // We allow _Atomic(T) to be initialized from anything that T can be
1703 // initialized from.
1704 if (const AtomicType *AT = Type->getAs<AtomicType>())
1705 Type = AT->getValueType();
1707 // Core issue 1454: For a literal constant expression of array or class type,
1708 // each subobject of its value shall have been initialized by a constant
1710 if (Value.isArray()) {
1711 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1712 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1713 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1714 Value.getArrayInitializedElt(I)))
1717 if (!Value.hasArrayFiller())
1719 return CheckConstantExpression(Info, DiagLoc, EltTy,
1720 Value.getArrayFiller());
1722 if (Value.isUnion() && Value.getUnionField()) {
1723 return CheckConstantExpression(Info, DiagLoc,
1724 Value.getUnionField()->getType(),
1725 Value.getUnionValue());
1727 if (Value.isStruct()) {
1728 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1729 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1730 unsigned BaseIndex = 0;
1731 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1732 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1733 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1734 Value.getStructBase(BaseIndex)))
1738 for (const auto *I : RD->fields()) {
1739 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1740 Value.getStructField(I->getFieldIndex())))
1745 if (Value.isLValue()) {
1747 LVal.setFrom(Info.Ctx, Value);
1748 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1751 // Everything else is fine.
1755 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1756 return LVal.Base.dyn_cast<const ValueDecl*>();
1759 static bool IsLiteralLValue(const LValue &Value) {
1760 if (Value.CallIndex)
1762 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1763 return E && !isa<MaterializeTemporaryExpr>(E);
1766 static bool IsWeakLValue(const LValue &Value) {
1767 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1768 return Decl && Decl->isWeak();
1771 static bool isZeroSized(const LValue &Value) {
1772 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1773 if (Decl && isa<VarDecl>(Decl)) {
1774 QualType Ty = Decl->getType();
1775 if (Ty->isArrayType())
1776 return Ty->isIncompleteType() ||
1777 Decl->getASTContext().getTypeSize(Ty) == 0;
1782 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1783 // A null base expression indicates a null pointer. These are always
1784 // evaluatable, and they are false unless the offset is zero.
1785 if (!Value.getLValueBase()) {
1786 Result = !Value.getLValueOffset().isZero();
1790 // We have a non-null base. These are generally known to be true, but if it's
1791 // a weak declaration it can be null at runtime.
1793 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1794 return !Decl || !Decl->isWeak();
1797 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1798 switch (Val.getKind()) {
1799 case APValue::Uninitialized:
1802 Result = Val.getInt().getBoolValue();
1804 case APValue::Float:
1805 Result = !Val.getFloat().isZero();
1807 case APValue::ComplexInt:
1808 Result = Val.getComplexIntReal().getBoolValue() ||
1809 Val.getComplexIntImag().getBoolValue();
1811 case APValue::ComplexFloat:
1812 Result = !Val.getComplexFloatReal().isZero() ||
1813 !Val.getComplexFloatImag().isZero();
1815 case APValue::LValue:
1816 return EvalPointerValueAsBool(Val, Result);
1817 case APValue::MemberPointer:
1818 Result = Val.getMemberPointerDecl();
1820 case APValue::Vector:
1821 case APValue::Array:
1822 case APValue::Struct:
1823 case APValue::Union:
1824 case APValue::AddrLabelDiff:
1828 llvm_unreachable("unknown APValue kind");
1831 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1833 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1835 if (!Evaluate(Val, Info, E))
1837 return HandleConversionToBool(Val, Result);
1840 template<typename T>
1841 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1842 const T &SrcValue, QualType DestType) {
1843 Info.CCEDiag(E, diag::note_constexpr_overflow)
1844 << SrcValue << DestType;
1845 return Info.noteUndefinedBehavior();
1848 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1849 QualType SrcType, const APFloat &Value,
1850 QualType DestType, APSInt &Result) {
1851 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1852 // Determine whether we are converting to unsigned or signed.
1853 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1855 Result = APSInt(DestWidth, !DestSigned);
1857 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1858 & APFloat::opInvalidOp)
1859 return HandleOverflow(Info, E, Value, DestType);
1863 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1864 QualType SrcType, QualType DestType,
1866 APFloat Value = Result;
1868 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1869 APFloat::rmNearestTiesToEven, &ignored)
1870 & APFloat::opOverflow)
1871 return HandleOverflow(Info, E, Value, DestType);
1875 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1876 QualType DestType, QualType SrcType,
1877 const APSInt &Value) {
1878 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1879 APSInt Result = Value;
1880 // Figure out if this is a truncate, extend or noop cast.
1881 // If the input is signed, do a sign extend, noop, or truncate.
1882 Result = Result.extOrTrunc(DestWidth);
1883 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1887 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1888 QualType SrcType, const APSInt &Value,
1889 QualType DestType, APFloat &Result) {
1890 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1891 if (Result.convertFromAPInt(Value, Value.isSigned(),
1892 APFloat::rmNearestTiesToEven)
1893 & APFloat::opOverflow)
1894 return HandleOverflow(Info, E, Value, DestType);
1898 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1899 APValue &Value, const FieldDecl *FD) {
1900 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1902 if (!Value.isInt()) {
1903 // Trying to store a pointer-cast-to-integer into a bitfield.
1904 // FIXME: In this case, we should provide the diagnostic for casting
1905 // a pointer to an integer.
1906 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1911 APSInt &Int = Value.getInt();
1912 unsigned OldBitWidth = Int.getBitWidth();
1913 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1914 if (NewBitWidth < OldBitWidth)
1915 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1919 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1922 if (!Evaluate(SVal, Info, E))
1925 Res = SVal.getInt();
1928 if (SVal.isFloat()) {
1929 Res = SVal.getFloat().bitcastToAPInt();
1932 if (SVal.isVector()) {
1933 QualType VecTy = E->getType();
1934 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1935 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1936 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1937 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1938 Res = llvm::APInt::getNullValue(VecSize);
1939 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1940 APValue &Elt = SVal.getVectorElt(i);
1941 llvm::APInt EltAsInt;
1943 EltAsInt = Elt.getInt();
1944 } else if (Elt.isFloat()) {
1945 EltAsInt = Elt.getFloat().bitcastToAPInt();
1947 // Don't try to handle vectors of anything other than int or float
1948 // (not sure if it's possible to hit this case).
1949 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1952 unsigned BaseEltSize = EltAsInt.getBitWidth();
1954 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1956 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1960 // Give up if the input isn't an int, float, or vector. For example, we
1961 // reject "(v4i16)(intptr_t)&a".
1962 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1966 /// Perform the given integer operation, which is known to need at most BitWidth
1967 /// bits, and check for overflow in the original type (if that type was not an
1969 template<typename Operation>
1970 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1971 const APSInt &LHS, const APSInt &RHS,
1972 unsigned BitWidth, Operation Op,
1974 if (LHS.isUnsigned()) {
1975 Result = Op(LHS, RHS);
1979 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1980 Result = Value.trunc(LHS.getBitWidth());
1981 if (Result.extend(BitWidth) != Value) {
1982 if (Info.checkingForOverflow())
1983 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1984 diag::warn_integer_constant_overflow)
1985 << Result.toString(10) << E->getType();
1987 return HandleOverflow(Info, E, Value, E->getType());
1992 /// Perform the given binary integer operation.
1993 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1994 BinaryOperatorKind Opcode, APSInt RHS,
2001 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2002 std::multiplies<APSInt>(), Result);
2004 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2005 std::plus<APSInt>(), Result);
2007 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2008 std::minus<APSInt>(), Result);
2009 case BO_And: Result = LHS & RHS; return true;
2010 case BO_Xor: Result = LHS ^ RHS; return true;
2011 case BO_Or: Result = LHS | RHS; return true;
2015 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2018 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2019 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2020 // this operation and gives the two's complement result.
2021 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2022 LHS.isSigned() && LHS.isMinSignedValue())
2023 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2027 if (Info.getLangOpts().OpenCL)
2028 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2029 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2030 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2032 else if (RHS.isSigned() && RHS.isNegative()) {
2033 // During constant-folding, a negative shift is an opposite shift. Such
2034 // a shift is not a constant expression.
2035 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2040 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2041 // the shifted type.
2042 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2044 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2045 << RHS << E->getType() << LHS.getBitWidth();
2046 } else if (LHS.isSigned()) {
2047 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2048 // operand, and must not overflow the corresponding unsigned type.
2049 if (LHS.isNegative())
2050 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2051 else if (LHS.countLeadingZeros() < SA)
2052 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2058 if (Info.getLangOpts().OpenCL)
2059 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2060 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2061 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2063 else if (RHS.isSigned() && RHS.isNegative()) {
2064 // During constant-folding, a negative shift is an opposite shift. Such a
2065 // shift is not a constant expression.
2066 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2071 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2073 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2075 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2076 << RHS << E->getType() << LHS.getBitWidth();
2081 case BO_LT: Result = LHS < RHS; return true;
2082 case BO_GT: Result = LHS > RHS; return true;
2083 case BO_LE: Result = LHS <= RHS; return true;
2084 case BO_GE: Result = LHS >= RHS; return true;
2085 case BO_EQ: Result = LHS == RHS; return true;
2086 case BO_NE: Result = LHS != RHS; return true;
2090 /// Perform the given binary floating-point operation, in-place, on LHS.
2091 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2092 APFloat &LHS, BinaryOperatorKind Opcode,
2093 const APFloat &RHS) {
2099 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2102 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2105 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2108 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2112 if (LHS.isInfinity() || LHS.isNaN()) {
2113 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2114 return Info.noteUndefinedBehavior();
2119 /// Cast an lvalue referring to a base subobject to a derived class, by
2120 /// truncating the lvalue's path to the given length.
2121 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2122 const RecordDecl *TruncatedType,
2123 unsigned TruncatedElements) {
2124 SubobjectDesignator &D = Result.Designator;
2126 // Check we actually point to a derived class object.
2127 if (TruncatedElements == D.Entries.size())
2129 assert(TruncatedElements >= D.MostDerivedPathLength &&
2130 "not casting to a derived class");
2131 if (!Result.checkSubobject(Info, E, CSK_Derived))
2134 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2135 const RecordDecl *RD = TruncatedType;
2136 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2137 if (RD->isInvalidDecl()) return false;
2138 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2139 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2140 if (isVirtualBaseClass(D.Entries[I]))
2141 Result.Offset -= Layout.getVBaseClassOffset(Base);
2143 Result.Offset -= Layout.getBaseClassOffset(Base);
2146 D.Entries.resize(TruncatedElements);
2150 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2151 const CXXRecordDecl *Derived,
2152 const CXXRecordDecl *Base,
2153 const ASTRecordLayout *RL = nullptr) {
2155 if (Derived->isInvalidDecl()) return false;
2156 RL = &Info.Ctx.getASTRecordLayout(Derived);
2159 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2160 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2164 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2165 const CXXRecordDecl *DerivedDecl,
2166 const CXXBaseSpecifier *Base) {
2167 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2169 if (!Base->isVirtual())
2170 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2172 SubobjectDesignator &D = Obj.Designator;
2176 // Extract most-derived object and corresponding type.
2177 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2178 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2181 // Find the virtual base class.
2182 if (DerivedDecl->isInvalidDecl()) return false;
2183 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2184 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2185 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2189 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2190 QualType Type, LValue &Result) {
2191 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2192 PathE = E->path_end();
2193 PathI != PathE; ++PathI) {
2194 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2197 Type = (*PathI)->getType();
2202 /// Update LVal to refer to the given field, which must be a member of the type
2203 /// currently described by LVal.
2204 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2205 const FieldDecl *FD,
2206 const ASTRecordLayout *RL = nullptr) {
2208 if (FD->getParent()->isInvalidDecl()) return false;
2209 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2212 unsigned I = FD->getFieldIndex();
2213 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2214 LVal.addDecl(Info, E, FD);
2218 /// Update LVal to refer to the given indirect field.
2219 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2221 const IndirectFieldDecl *IFD) {
2222 for (const auto *C : IFD->chain())
2223 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2228 /// Get the size of the given type in char units.
2229 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2230 QualType Type, CharUnits &Size) {
2231 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2233 if (Type->isVoidType() || Type->isFunctionType()) {
2234 Size = CharUnits::One();
2238 if (Type->isDependentType()) {
2243 if (!Type->isConstantSizeType()) {
2244 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2245 // FIXME: Better diagnostic.
2250 Size = Info.Ctx.getTypeSizeInChars(Type);
2254 /// Update a pointer value to model pointer arithmetic.
2255 /// \param Info - Information about the ongoing evaluation.
2256 /// \param E - The expression being evaluated, for diagnostic purposes.
2257 /// \param LVal - The pointer value to be updated.
2258 /// \param EltTy - The pointee type represented by LVal.
2259 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2260 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2261 LValue &LVal, QualType EltTy,
2262 APSInt Adjustment) {
2263 CharUnits SizeOfPointee;
2264 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2267 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2271 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2272 LValue &LVal, QualType EltTy,
2273 int64_t Adjustment) {
2274 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2275 APSInt::get(Adjustment));
2278 /// Update an lvalue to refer to a component of a complex number.
2279 /// \param Info - Information about the ongoing evaluation.
2280 /// \param LVal - The lvalue to be updated.
2281 /// \param EltTy - The complex number's component type.
2282 /// \param Imag - False for the real component, true for the imaginary.
2283 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2284 LValue &LVal, QualType EltTy,
2287 CharUnits SizeOfComponent;
2288 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2290 LVal.Offset += SizeOfComponent;
2292 LVal.addComplex(Info, E, EltTy, Imag);
2296 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2297 QualType Type, const LValue &LVal,
2300 /// Try to evaluate the initializer for a variable declaration.
2302 /// \param Info Information about the ongoing evaluation.
2303 /// \param E An expression to be used when printing diagnostics.
2304 /// \param VD The variable whose initializer should be obtained.
2305 /// \param Frame The frame in which the variable was created. Must be null
2306 /// if this variable is not local to the evaluation.
2307 /// \param Result Filled in with a pointer to the value of the variable.
2308 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2309 const VarDecl *VD, CallStackFrame *Frame,
2312 // If this is a parameter to an active constexpr function call, perform
2313 // argument substitution.
2314 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2315 // Assume arguments of a potential constant expression are unknown
2316 // constant expressions.
2317 if (Info.checkingPotentialConstantExpression())
2319 if (!Frame || !Frame->Arguments) {
2320 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2323 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2327 // If this is a local variable, dig out its value.
2329 Result = Frame->getTemporary(VD);
2331 // Assume variables referenced within a lambda's call operator that were
2332 // not declared within the call operator are captures and during checking
2333 // of a potential constant expression, assume they are unknown constant
2335 assert(isLambdaCallOperator(Frame->Callee) &&
2336 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2337 "missing value for local variable");
2338 if (Info.checkingPotentialConstantExpression())
2340 // FIXME: implement capture evaluation during constant expr evaluation.
2341 Info.FFDiag(E->getLocStart(),
2342 diag::note_unimplemented_constexpr_lambda_feature_ast)
2343 << "captures not currently allowed";
2349 // Dig out the initializer, and use the declaration which it's attached to.
2350 const Expr *Init = VD->getAnyInitializer(VD);
2351 if (!Init || Init->isValueDependent()) {
2352 // If we're checking a potential constant expression, the variable could be
2353 // initialized later.
2354 if (!Info.checkingPotentialConstantExpression())
2355 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2359 // If we're currently evaluating the initializer of this declaration, use that
2361 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2362 Result = Info.EvaluatingDeclValue;
2366 // Never evaluate the initializer of a weak variable. We can't be sure that
2367 // this is the definition which will be used.
2369 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2373 // Check that we can fold the initializer. In C++, we will have already done
2374 // this in the cases where it matters for conformance.
2375 SmallVector<PartialDiagnosticAt, 8> Notes;
2376 if (!VD->evaluateValue(Notes)) {
2377 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2378 Notes.size() + 1) << VD;
2379 Info.Note(VD->getLocation(), diag::note_declared_at);
2380 Info.addNotes(Notes);
2382 } else if (!VD->checkInitIsICE()) {
2383 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2384 Notes.size() + 1) << VD;
2385 Info.Note(VD->getLocation(), diag::note_declared_at);
2386 Info.addNotes(Notes);
2389 Result = VD->getEvaluatedValue();
2393 static bool IsConstNonVolatile(QualType T) {
2394 Qualifiers Quals = T.getQualifiers();
2395 return Quals.hasConst() && !Quals.hasVolatile();
2398 /// Get the base index of the given base class within an APValue representing
2399 /// the given derived class.
2400 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2401 const CXXRecordDecl *Base) {
2402 Base = Base->getCanonicalDecl();
2404 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2405 E = Derived->bases_end(); I != E; ++I, ++Index) {
2406 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2410 llvm_unreachable("base class missing from derived class's bases list");
2413 /// Extract the value of a character from a string literal.
2414 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2416 // FIXME: Support MakeStringConstant
2417 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2419 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2420 assert(Index <= Str.size() && "Index too large");
2421 return APSInt::getUnsigned(Str.c_str()[Index]);
2424 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2425 Lit = PE->getFunctionName();
2426 const StringLiteral *S = cast<StringLiteral>(Lit);
2427 const ConstantArrayType *CAT =
2428 Info.Ctx.getAsConstantArrayType(S->getType());
2429 assert(CAT && "string literal isn't an array");
2430 QualType CharType = CAT->getElementType();
2431 assert(CharType->isIntegerType() && "unexpected character type");
2433 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2434 CharType->isUnsignedIntegerType());
2435 if (Index < S->getLength())
2436 Value = S->getCodeUnit(Index);
2440 // Expand a string literal into an array of characters.
2441 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2443 const StringLiteral *S = cast<StringLiteral>(Lit);
2444 const ConstantArrayType *CAT =
2445 Info.Ctx.getAsConstantArrayType(S->getType());
2446 assert(CAT && "string literal isn't an array");
2447 QualType CharType = CAT->getElementType();
2448 assert(CharType->isIntegerType() && "unexpected character type");
2450 unsigned Elts = CAT->getSize().getZExtValue();
2451 Result = APValue(APValue::UninitArray(),
2452 std::min(S->getLength(), Elts), Elts);
2453 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2454 CharType->isUnsignedIntegerType());
2455 if (Result.hasArrayFiller())
2456 Result.getArrayFiller() = APValue(Value);
2457 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2458 Value = S->getCodeUnit(I);
2459 Result.getArrayInitializedElt(I) = APValue(Value);
2463 // Expand an array so that it has more than Index filled elements.
2464 static void expandArray(APValue &Array, unsigned Index) {
2465 unsigned Size = Array.getArraySize();
2466 assert(Index < Size);
2468 // Always at least double the number of elements for which we store a value.
2469 unsigned OldElts = Array.getArrayInitializedElts();
2470 unsigned NewElts = std::max(Index+1, OldElts * 2);
2471 NewElts = std::min(Size, std::max(NewElts, 8u));
2473 // Copy the data across.
2474 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2475 for (unsigned I = 0; I != OldElts; ++I)
2476 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2477 for (unsigned I = OldElts; I != NewElts; ++I)
2478 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2479 if (NewValue.hasArrayFiller())
2480 NewValue.getArrayFiller() = Array.getArrayFiller();
2481 Array.swap(NewValue);
2484 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2485 /// conversion. If it's of class type, we may assume that the copy operation
2486 /// is trivial. Note that this is never true for a union type with fields
2487 /// (because the copy always "reads" the active member) and always true for
2488 /// a non-class type.
2489 static bool isReadByLvalueToRvalueConversion(QualType T) {
2490 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2491 if (!RD || (RD->isUnion() && !RD->field_empty()))
2496 for (auto *Field : RD->fields())
2497 if (isReadByLvalueToRvalueConversion(Field->getType()))
2500 for (auto &BaseSpec : RD->bases())
2501 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2507 /// Diagnose an attempt to read from any unreadable field within the specified
2508 /// type, which might be a class type.
2509 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2511 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2515 if (!RD->hasMutableFields())
2518 for (auto *Field : RD->fields()) {
2519 // If we're actually going to read this field in some way, then it can't
2520 // be mutable. If we're in a union, then assigning to a mutable field
2521 // (even an empty one) can change the active member, so that's not OK.
2522 // FIXME: Add core issue number for the union case.
2523 if (Field->isMutable() &&
2524 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2525 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2526 Info.Note(Field->getLocation(), diag::note_declared_at);
2530 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2534 for (auto &BaseSpec : RD->bases())
2535 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2538 // All mutable fields were empty, and thus not actually read.
2542 /// Kinds of access we can perform on an object, for diagnostics.
2551 /// A handle to a complete object (an object that is not a subobject of
2552 /// another object).
2553 struct CompleteObject {
2554 /// The value of the complete object.
2556 /// The type of the complete object.
2559 CompleteObject() : Value(nullptr) {}
2560 CompleteObject(APValue *Value, QualType Type)
2561 : Value(Value), Type(Type) {
2562 assert(Value && "missing value for complete object");
2565 explicit operator bool() const { return Value; }
2567 } // end anonymous namespace
2569 /// Find the designated sub-object of an rvalue.
2570 template<typename SubobjectHandler>
2571 typename SubobjectHandler::result_type
2572 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2573 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2575 // A diagnostic will have already been produced.
2576 return handler.failed();
2577 if (Sub.isOnePastTheEnd()) {
2578 if (Info.getLangOpts().CPlusPlus11)
2579 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2580 << handler.AccessKind;
2583 return handler.failed();
2586 APValue *O = Obj.Value;
2587 QualType ObjType = Obj.Type;
2588 const FieldDecl *LastField = nullptr;
2590 // Walk the designator's path to find the subobject.
2591 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2592 if (O->isUninit()) {
2593 if (!Info.checkingPotentialConstantExpression())
2594 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2595 return handler.failed();
2599 // If we are reading an object of class type, there may still be more
2600 // things we need to check: if there are any mutable subobjects, we
2601 // cannot perform this read. (This only happens when performing a trivial
2602 // copy or assignment.)
2603 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2604 diagnoseUnreadableFields(Info, E, ObjType))
2605 return handler.failed();
2607 if (!handler.found(*O, ObjType))
2610 // If we modified a bit-field, truncate it to the right width.
2611 if (handler.AccessKind != AK_Read &&
2612 LastField && LastField->isBitField() &&
2613 !truncateBitfieldValue(Info, E, *O, LastField))
2619 LastField = nullptr;
2620 if (ObjType->isArrayType()) {
2621 // Next subobject is an array element.
2622 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2623 assert(CAT && "vla in literal type?");
2624 uint64_t Index = Sub.Entries[I].ArrayIndex;
2625 if (CAT->getSize().ule(Index)) {
2626 // Note, it should not be possible to form a pointer with a valid
2627 // designator which points more than one past the end of the array.
2628 if (Info.getLangOpts().CPlusPlus11)
2629 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2630 << handler.AccessKind;
2633 return handler.failed();
2636 ObjType = CAT->getElementType();
2638 // An array object is represented as either an Array APValue or as an
2639 // LValue which refers to a string literal.
2640 if (O->isLValue()) {
2641 assert(I == N - 1 && "extracting subobject of character?");
2642 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2643 if (handler.AccessKind != AK_Read)
2644 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2647 return handler.foundString(*O, ObjType, Index);
2650 if (O->getArrayInitializedElts() > Index)
2651 O = &O->getArrayInitializedElt(Index);
2652 else if (handler.AccessKind != AK_Read) {
2653 expandArray(*O, Index);
2654 O = &O->getArrayInitializedElt(Index);
2656 O = &O->getArrayFiller();
2657 } else if (ObjType->isAnyComplexType()) {
2658 // Next subobject is a complex number.
2659 uint64_t Index = Sub.Entries[I].ArrayIndex;
2661 if (Info.getLangOpts().CPlusPlus11)
2662 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2663 << handler.AccessKind;
2666 return handler.failed();
2669 bool WasConstQualified = ObjType.isConstQualified();
2670 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2671 if (WasConstQualified)
2674 assert(I == N - 1 && "extracting subobject of scalar?");
2675 if (O->isComplexInt()) {
2676 return handler.found(Index ? O->getComplexIntImag()
2677 : O->getComplexIntReal(), ObjType);
2679 assert(O->isComplexFloat());
2680 return handler.found(Index ? O->getComplexFloatImag()
2681 : O->getComplexFloatReal(), ObjType);
2683 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2684 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2685 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2687 Info.Note(Field->getLocation(), diag::note_declared_at);
2688 return handler.failed();
2691 // Next subobject is a class, struct or union field.
2692 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2693 if (RD->isUnion()) {
2694 const FieldDecl *UnionField = O->getUnionField();
2696 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2697 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2698 << handler.AccessKind << Field << !UnionField << UnionField;
2699 return handler.failed();
2701 O = &O->getUnionValue();
2703 O = &O->getStructField(Field->getFieldIndex());
2705 bool WasConstQualified = ObjType.isConstQualified();
2706 ObjType = Field->getType();
2707 if (WasConstQualified && !Field->isMutable())
2710 if (ObjType.isVolatileQualified()) {
2711 if (Info.getLangOpts().CPlusPlus) {
2712 // FIXME: Include a description of the path to the volatile subobject.
2713 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2714 << handler.AccessKind << 2 << Field;
2715 Info.Note(Field->getLocation(), diag::note_declared_at);
2717 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2719 return handler.failed();
2724 // Next subobject is a base class.
2725 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2726 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2727 O = &O->getStructBase(getBaseIndex(Derived, Base));
2729 bool WasConstQualified = ObjType.isConstQualified();
2730 ObjType = Info.Ctx.getRecordType(Base);
2731 if (WasConstQualified)
2738 struct ExtractSubobjectHandler {
2742 static const AccessKinds AccessKind = AK_Read;
2744 typedef bool result_type;
2745 bool failed() { return false; }
2746 bool found(APValue &Subobj, QualType SubobjType) {
2750 bool found(APSInt &Value, QualType SubobjType) {
2751 Result = APValue(Value);
2754 bool found(APFloat &Value, QualType SubobjType) {
2755 Result = APValue(Value);
2758 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2759 Result = APValue(extractStringLiteralCharacter(
2760 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2764 } // end anonymous namespace
2766 const AccessKinds ExtractSubobjectHandler::AccessKind;
2768 /// Extract the designated sub-object of an rvalue.
2769 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2770 const CompleteObject &Obj,
2771 const SubobjectDesignator &Sub,
2773 ExtractSubobjectHandler Handler = { Info, Result };
2774 return findSubobject(Info, E, Obj, Sub, Handler);
2778 struct ModifySubobjectHandler {
2783 typedef bool result_type;
2784 static const AccessKinds AccessKind = AK_Assign;
2786 bool checkConst(QualType QT) {
2787 // Assigning to a const object has undefined behavior.
2788 if (QT.isConstQualified()) {
2789 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2795 bool failed() { return false; }
2796 bool found(APValue &Subobj, QualType SubobjType) {
2797 if (!checkConst(SubobjType))
2799 // We've been given ownership of NewVal, so just swap it in.
2800 Subobj.swap(NewVal);
2803 bool found(APSInt &Value, QualType SubobjType) {
2804 if (!checkConst(SubobjType))
2806 if (!NewVal.isInt()) {
2807 // Maybe trying to write a cast pointer value into a complex?
2811 Value = NewVal.getInt();
2814 bool found(APFloat &Value, QualType SubobjType) {
2815 if (!checkConst(SubobjType))
2817 Value = NewVal.getFloat();
2820 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2821 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2824 } // end anonymous namespace
2826 const AccessKinds ModifySubobjectHandler::AccessKind;
2828 /// Update the designated sub-object of an rvalue to the given value.
2829 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2830 const CompleteObject &Obj,
2831 const SubobjectDesignator &Sub,
2833 ModifySubobjectHandler Handler = { Info, NewVal, E };
2834 return findSubobject(Info, E, Obj, Sub, Handler);
2837 /// Find the position where two subobject designators diverge, or equivalently
2838 /// the length of the common initial subsequence.
2839 static unsigned FindDesignatorMismatch(QualType ObjType,
2840 const SubobjectDesignator &A,
2841 const SubobjectDesignator &B,
2842 bool &WasArrayIndex) {
2843 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2844 for (/**/; I != N; ++I) {
2845 if (!ObjType.isNull() &&
2846 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2847 // Next subobject is an array element.
2848 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2849 WasArrayIndex = true;
2852 if (ObjType->isAnyComplexType())
2853 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2855 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2857 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2858 WasArrayIndex = false;
2861 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2862 // Next subobject is a field.
2863 ObjType = FD->getType();
2865 // Next subobject is a base class.
2866 ObjType = QualType();
2869 WasArrayIndex = false;
2873 /// Determine whether the given subobject designators refer to elements of the
2874 /// same array object.
2875 static bool AreElementsOfSameArray(QualType ObjType,
2876 const SubobjectDesignator &A,
2877 const SubobjectDesignator &B) {
2878 if (A.Entries.size() != B.Entries.size())
2881 bool IsArray = A.MostDerivedIsArrayElement;
2882 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2883 // A is a subobject of the array element.
2886 // If A (and B) designates an array element, the last entry will be the array
2887 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2888 // of length 1' case, and the entire path must match.
2890 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2891 return CommonLength >= A.Entries.size() - IsArray;
2894 /// Find the complete object to which an LValue refers.
2895 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2896 AccessKinds AK, const LValue &LVal,
2897 QualType LValType) {
2899 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2900 return CompleteObject();
2903 CallStackFrame *Frame = nullptr;
2904 if (LVal.CallIndex) {
2905 Frame = Info.getCallFrame(LVal.CallIndex);
2907 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2908 << AK << LVal.Base.is<const ValueDecl*>();
2909 NoteLValueLocation(Info, LVal.Base);
2910 return CompleteObject();
2914 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2915 // is not a constant expression (even if the object is non-volatile). We also
2916 // apply this rule to C++98, in order to conform to the expected 'volatile'
2918 if (LValType.isVolatileQualified()) {
2919 if (Info.getLangOpts().CPlusPlus)
2920 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2924 return CompleteObject();
2927 // Compute value storage location and type of base object.
2928 APValue *BaseVal = nullptr;
2929 QualType BaseType = getType(LVal.Base);
2931 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2932 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2933 // In C++11, constexpr, non-volatile variables initialized with constant
2934 // expressions are constant expressions too. Inside constexpr functions,
2935 // parameters are constant expressions even if they're non-const.
2936 // In C++1y, objects local to a constant expression (those with a Frame) are
2937 // both readable and writable inside constant expressions.
2938 // In C, such things can also be folded, although they are not ICEs.
2939 const VarDecl *VD = dyn_cast<VarDecl>(D);
2941 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2944 if (!VD || VD->isInvalidDecl()) {
2946 return CompleteObject();
2949 // Accesses of volatile-qualified objects are not allowed.
2950 if (BaseType.isVolatileQualified()) {
2951 if (Info.getLangOpts().CPlusPlus) {
2952 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2954 Info.Note(VD->getLocation(), diag::note_declared_at);
2958 return CompleteObject();
2961 // Unless we're looking at a local variable or argument in a constexpr call,
2962 // the variable we're reading must be const.
2964 if (Info.getLangOpts().CPlusPlus14 &&
2965 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2966 // OK, we can read and modify an object if we're in the process of
2967 // evaluating its initializer, because its lifetime began in this
2969 } else if (AK != AK_Read) {
2970 // All the remaining cases only permit reading.
2971 Info.FFDiag(E, diag::note_constexpr_modify_global);
2972 return CompleteObject();
2973 } else if (VD->isConstexpr()) {
2974 // OK, we can read this variable.
2975 } else if (BaseType->isIntegralOrEnumerationType()) {
2976 // In OpenCL if a variable is in constant address space it is a const value.
2977 if (!(BaseType.isConstQualified() ||
2978 (Info.getLangOpts().OpenCL &&
2979 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2980 if (Info.getLangOpts().CPlusPlus) {
2981 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2982 Info.Note(VD->getLocation(), diag::note_declared_at);
2986 return CompleteObject();
2988 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2989 // We support folding of const floating-point types, in order to make
2990 // static const data members of such types (supported as an extension)
2992 if (Info.getLangOpts().CPlusPlus11) {
2993 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2994 Info.Note(VD->getLocation(), diag::note_declared_at);
2998 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2999 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3000 // Keep evaluating to see what we can do.
3002 // FIXME: Allow folding of values of any literal type in all languages.
3003 if (Info.checkingPotentialConstantExpression() &&
3004 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3005 // The definition of this variable could be constexpr. We can't
3006 // access it right now, but may be able to in future.
3007 } else if (Info.getLangOpts().CPlusPlus11) {
3008 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3009 Info.Note(VD->getLocation(), diag::note_declared_at);
3013 return CompleteObject();
3017 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3018 return CompleteObject();
3020 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3023 if (const MaterializeTemporaryExpr *MTE =
3024 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3025 assert(MTE->getStorageDuration() == SD_Static &&
3026 "should have a frame for a non-global materialized temporary");
3028 // Per C++1y [expr.const]p2:
3029 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3030 // - a [...] glvalue of integral or enumeration type that refers to
3031 // a non-volatile const object [...]
3033 // - a [...] glvalue of literal type that refers to a non-volatile
3034 // object whose lifetime began within the evaluation of e.
3036 // C++11 misses the 'began within the evaluation of e' check and
3037 // instead allows all temporaries, including things like:
3040 // constexpr int k = r;
3041 // Therefore we use the C++1y rules in C++11 too.
3042 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3043 const ValueDecl *ED = MTE->getExtendingDecl();
3044 if (!(BaseType.isConstQualified() &&
3045 BaseType->isIntegralOrEnumerationType()) &&
3046 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3047 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3048 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3049 return CompleteObject();
3052 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3053 assert(BaseVal && "got reference to unevaluated temporary");
3056 return CompleteObject();
3059 BaseVal = Frame->getTemporary(Base);
3060 assert(BaseVal && "missing value for temporary");
3063 // Volatile temporary objects cannot be accessed in constant expressions.
3064 if (BaseType.isVolatileQualified()) {
3065 if (Info.getLangOpts().CPlusPlus) {
3066 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3068 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3072 return CompleteObject();
3076 // During the construction of an object, it is not yet 'const'.
3077 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3078 // and this doesn't do quite the right thing for const subobjects of the
3079 // object under construction.
3080 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3081 BaseType = Info.Ctx.getCanonicalType(BaseType);
3082 BaseType.removeLocalConst();
3085 // In C++1y, we can't safely access any mutable state when we might be
3086 // evaluating after an unmodeled side effect.
3088 // FIXME: Not all local state is mutable. Allow local constant subobjects
3089 // to be read here (but take care with 'mutable' fields).
3090 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3091 Info.EvalStatus.HasSideEffects) ||
3092 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3093 return CompleteObject();
3095 return CompleteObject(BaseVal, BaseType);
3098 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3099 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3100 /// glvalue referred to by an entity of reference type.
3102 /// \param Info - Information about the ongoing evaluation.
3103 /// \param Conv - The expression for which we are performing the conversion.
3104 /// Used for diagnostics.
3105 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3106 /// case of a non-class type).
3107 /// \param LVal - The glvalue on which we are attempting to perform this action.
3108 /// \param RVal - The produced value will be placed here.
3109 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3111 const LValue &LVal, APValue &RVal) {
3112 if (LVal.Designator.Invalid)
3115 // Check for special cases where there is no existing APValue to look at.
3116 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3117 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3118 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3119 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3120 // initializer until now for such expressions. Such an expression can't be
3121 // an ICE in C, so this only matters for fold.
3122 if (Type.isVolatileQualified()) {
3127 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3129 CompleteObject LitObj(&Lit, Base->getType());
3130 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3131 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3132 // We represent a string literal array as an lvalue pointing at the
3133 // corresponding expression, rather than building an array of chars.
3134 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3135 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3136 CompleteObject StrObj(&Str, Base->getType());
3137 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3141 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3142 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3145 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3146 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3147 QualType LValType, APValue &Val) {
3148 if (LVal.Designator.Invalid)
3151 if (!Info.getLangOpts().CPlusPlus14) {
3156 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3157 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3160 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3161 return T->isSignedIntegerType() &&
3162 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3166 struct CompoundAssignSubobjectHandler {
3169 QualType PromotedLHSType;
3170 BinaryOperatorKind Opcode;
3173 static const AccessKinds AccessKind = AK_Assign;
3175 typedef bool result_type;
3177 bool checkConst(QualType QT) {
3178 // Assigning to a const object has undefined behavior.
3179 if (QT.isConstQualified()) {
3180 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3186 bool failed() { return false; }
3187 bool found(APValue &Subobj, QualType SubobjType) {
3188 switch (Subobj.getKind()) {
3190 return found(Subobj.getInt(), SubobjType);
3191 case APValue::Float:
3192 return found(Subobj.getFloat(), SubobjType);
3193 case APValue::ComplexInt:
3194 case APValue::ComplexFloat:
3195 // FIXME: Implement complex compound assignment.
3198 case APValue::LValue:
3199 return foundPointer(Subobj, SubobjType);
3201 // FIXME: can this happen?
3206 bool found(APSInt &Value, QualType SubobjType) {
3207 if (!checkConst(SubobjType))
3210 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3211 // We don't support compound assignment on integer-cast-to-pointer
3217 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3219 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3221 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3224 bool found(APFloat &Value, QualType SubobjType) {
3225 return checkConst(SubobjType) &&
3226 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3228 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3229 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3231 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3232 if (!checkConst(SubobjType))
3235 QualType PointeeType;
3236 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3237 PointeeType = PT->getPointeeType();
3239 if (PointeeType.isNull() || !RHS.isInt() ||
3240 (Opcode != BO_Add && Opcode != BO_Sub)) {
3245 APSInt Offset = RHS.getInt();
3246 if (Opcode == BO_Sub)
3247 negateAsSigned(Offset);
3250 LVal.setFrom(Info.Ctx, Subobj);
3251 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3253 LVal.moveInto(Subobj);
3256 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3257 llvm_unreachable("shouldn't encounter string elements here");
3260 } // end anonymous namespace
3262 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3264 /// Perform a compound assignment of LVal <op>= RVal.
3265 static bool handleCompoundAssignment(
3266 EvalInfo &Info, const Expr *E,
3267 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3268 BinaryOperatorKind Opcode, const APValue &RVal) {
3269 if (LVal.Designator.Invalid)
3272 if (!Info.getLangOpts().CPlusPlus14) {
3277 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3278 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3280 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3284 struct IncDecSubobjectHandler {
3287 AccessKinds AccessKind;
3290 typedef bool result_type;
3292 bool checkConst(QualType QT) {
3293 // Assigning to a const object has undefined behavior.
3294 if (QT.isConstQualified()) {
3295 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3301 bool failed() { return false; }
3302 bool found(APValue &Subobj, QualType SubobjType) {
3303 // Stash the old value. Also clear Old, so we don't clobber it later
3304 // if we're post-incrementing a complex.
3310 switch (Subobj.getKind()) {
3312 return found(Subobj.getInt(), SubobjType);
3313 case APValue::Float:
3314 return found(Subobj.getFloat(), SubobjType);
3315 case APValue::ComplexInt:
3316 return found(Subobj.getComplexIntReal(),
3317 SubobjType->castAs<ComplexType>()->getElementType()
3318 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3319 case APValue::ComplexFloat:
3320 return found(Subobj.getComplexFloatReal(),
3321 SubobjType->castAs<ComplexType>()->getElementType()
3322 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3323 case APValue::LValue:
3324 return foundPointer(Subobj, SubobjType);
3326 // FIXME: can this happen?
3331 bool found(APSInt &Value, QualType SubobjType) {
3332 if (!checkConst(SubobjType))
3335 if (!SubobjType->isIntegerType()) {
3336 // We don't support increment / decrement on integer-cast-to-pointer
3342 if (Old) *Old = APValue(Value);
3344 // bool arithmetic promotes to int, and the conversion back to bool
3345 // doesn't reduce mod 2^n, so special-case it.
3346 if (SubobjType->isBooleanType()) {
3347 if (AccessKind == AK_Increment)
3354 bool WasNegative = Value.isNegative();
3355 if (AccessKind == AK_Increment) {
3358 if (!WasNegative && Value.isNegative() &&
3359 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3360 APSInt ActualValue(Value, /*IsUnsigned*/true);
3361 return HandleOverflow(Info, E, ActualValue, SubobjType);
3366 if (WasNegative && !Value.isNegative() &&
3367 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3368 unsigned BitWidth = Value.getBitWidth();
3369 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3370 ActualValue.setBit(BitWidth);
3371 return HandleOverflow(Info, E, ActualValue, SubobjType);
3376 bool found(APFloat &Value, QualType SubobjType) {
3377 if (!checkConst(SubobjType))
3380 if (Old) *Old = APValue(Value);
3382 APFloat One(Value.getSemantics(), 1);
3383 if (AccessKind == AK_Increment)
3384 Value.add(One, APFloat::rmNearestTiesToEven);
3386 Value.subtract(One, APFloat::rmNearestTiesToEven);
3389 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3390 if (!checkConst(SubobjType))
3393 QualType PointeeType;
3394 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3395 PointeeType = PT->getPointeeType();
3402 LVal.setFrom(Info.Ctx, Subobj);
3403 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3404 AccessKind == AK_Increment ? 1 : -1))
3406 LVal.moveInto(Subobj);
3409 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3410 llvm_unreachable("shouldn't encounter string elements here");
3413 } // end anonymous namespace
3415 /// Perform an increment or decrement on LVal.
3416 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3417 QualType LValType, bool IsIncrement, APValue *Old) {
3418 if (LVal.Designator.Invalid)
3421 if (!Info.getLangOpts().CPlusPlus14) {
3426 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3427 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3428 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3429 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3432 /// Build an lvalue for the object argument of a member function call.
3433 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3435 if (Object->getType()->isPointerType())
3436 return EvaluatePointer(Object, This, Info);
3438 if (Object->isGLValue())
3439 return EvaluateLValue(Object, This, Info);
3441 if (Object->getType()->isLiteralType(Info.Ctx))
3442 return EvaluateTemporary(Object, This, Info);
3444 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3448 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3449 /// lvalue referring to the result.
3451 /// \param Info - Information about the ongoing evaluation.
3452 /// \param LV - An lvalue referring to the base of the member pointer.
3453 /// \param RHS - The member pointer expression.
3454 /// \param IncludeMember - Specifies whether the member itself is included in
3455 /// the resulting LValue subobject designator. This is not possible when
3456 /// creating a bound member function.
3457 /// \return The field or method declaration to which the member pointer refers,
3458 /// or 0 if evaluation fails.
3459 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3463 bool IncludeMember = true) {
3465 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3468 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3469 // member value, the behavior is undefined.
3470 if (!MemPtr.getDecl()) {
3471 // FIXME: Specific diagnostic.
3476 if (MemPtr.isDerivedMember()) {
3477 // This is a member of some derived class. Truncate LV appropriately.
3478 // The end of the derived-to-base path for the base object must match the
3479 // derived-to-base path for the member pointer.
3480 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3481 LV.Designator.Entries.size()) {
3485 unsigned PathLengthToMember =
3486 LV.Designator.Entries.size() - MemPtr.Path.size();
3487 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3488 const CXXRecordDecl *LVDecl = getAsBaseClass(
3489 LV.Designator.Entries[PathLengthToMember + I]);
3490 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3491 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3497 // Truncate the lvalue to the appropriate derived class.
3498 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3499 PathLengthToMember))
3501 } else if (!MemPtr.Path.empty()) {
3502 // Extend the LValue path with the member pointer's path.
3503 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3504 MemPtr.Path.size() + IncludeMember);
3506 // Walk down to the appropriate base class.
3507 if (const PointerType *PT = LVType->getAs<PointerType>())
3508 LVType = PT->getPointeeType();
3509 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3510 assert(RD && "member pointer access on non-class-type expression");
3511 // The first class in the path is that of the lvalue.
3512 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3513 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3514 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3518 // Finally cast to the class containing the member.
3519 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3520 MemPtr.getContainingRecord()))
3524 // Add the member. Note that we cannot build bound member functions here.
3525 if (IncludeMember) {
3526 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3527 if (!HandleLValueMember(Info, RHS, LV, FD))
3529 } else if (const IndirectFieldDecl *IFD =
3530 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3531 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3534 llvm_unreachable("can't construct reference to bound member function");
3538 return MemPtr.getDecl();
3541 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3542 const BinaryOperator *BO,
3544 bool IncludeMember = true) {
3545 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3547 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3548 if (Info.noteFailure()) {
3550 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3555 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3556 BO->getRHS(), IncludeMember);
3559 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3560 /// the provided lvalue, which currently refers to the base object.
3561 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3563 SubobjectDesignator &D = Result.Designator;
3564 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3567 QualType TargetQT = E->getType();
3568 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3569 TargetQT = PT->getPointeeType();
3571 // Check this cast lands within the final derived-to-base subobject path.
3572 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3573 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3574 << D.MostDerivedType << TargetQT;
3578 // Check the type of the final cast. We don't need to check the path,
3579 // since a cast can only be formed if the path is unique.
3580 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3581 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3582 const CXXRecordDecl *FinalType;
3583 if (NewEntriesSize == D.MostDerivedPathLength)
3584 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3586 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3587 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3588 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3589 << D.MostDerivedType << TargetQT;
3593 // Truncate the lvalue to the appropriate derived class.
3594 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3598 enum EvalStmtResult {
3599 /// Evaluation failed.
3601 /// Hit a 'return' statement.
3603 /// Evaluation succeeded.
3605 /// Hit a 'continue' statement.
3607 /// Hit a 'break' statement.
3609 /// Still scanning for 'case' or 'default' statement.
3614 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3615 // We don't need to evaluate the initializer for a static local.
3616 if (!VD->hasLocalStorage())
3620 Result.set(VD, Info.CurrentCall->Index);
3621 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3623 const Expr *InitE = VD->getInit();
3625 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3626 << false << VD->getType();
3631 if (InitE->isValueDependent())
3634 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3635 // Wipe out any partially-computed value, to allow tracking that this
3636 // evaluation failed.
3644 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3647 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3648 OK &= EvaluateVarDecl(Info, VD);
3650 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3651 for (auto *BD : DD->bindings())
3652 if (auto *VD = BD->getHoldingVar())
3653 OK &= EvaluateDecl(Info, VD);
3659 /// Evaluate a condition (either a variable declaration or an expression).
3660 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3661 const Expr *Cond, bool &Result) {
3662 FullExpressionRAII Scope(Info);
3663 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3665 return EvaluateAsBooleanCondition(Cond, Result, Info);
3669 /// \brief A location where the result (returned value) of evaluating a
3670 /// statement should be stored.
3672 /// The APValue that should be filled in with the returned value.
3674 /// The location containing the result, if any (used to support RVO).
3679 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3681 const SwitchCase *SC = nullptr);
3683 /// Evaluate the body of a loop, and translate the result as appropriate.
3684 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3686 const SwitchCase *Case = nullptr) {
3687 BlockScopeRAII Scope(Info);
3688 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3690 return ESR_Succeeded;
3693 return ESR_Continue;
3696 case ESR_CaseNotFound:
3699 llvm_unreachable("Invalid EvalStmtResult!");
3702 /// Evaluate a switch statement.
3703 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3704 const SwitchStmt *SS) {
3705 BlockScopeRAII Scope(Info);
3707 // Evaluate the switch condition.
3710 FullExpressionRAII Scope(Info);
3711 if (const Stmt *Init = SS->getInit()) {
3712 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3713 if (ESR != ESR_Succeeded)
3716 if (SS->getConditionVariable() &&
3717 !EvaluateDecl(Info, SS->getConditionVariable()))
3719 if (!EvaluateInteger(SS->getCond(), Value, Info))
3723 // Find the switch case corresponding to the value of the condition.
3724 // FIXME: Cache this lookup.
3725 const SwitchCase *Found = nullptr;
3726 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3727 SC = SC->getNextSwitchCase()) {
3728 if (isa<DefaultStmt>(SC)) {
3733 const CaseStmt *CS = cast<CaseStmt>(SC);
3734 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3735 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3737 if (LHS <= Value && Value <= RHS) {
3744 return ESR_Succeeded;
3746 // Search the switch body for the switch case and evaluate it from there.
3747 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3749 return ESR_Succeeded;
3755 case ESR_CaseNotFound:
3756 // This can only happen if the switch case is nested within a statement
3757 // expression. We have no intention of supporting that.
3758 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3761 llvm_unreachable("Invalid EvalStmtResult!");
3764 // Evaluate a statement.
3765 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3766 const Stmt *S, const SwitchCase *Case) {
3767 if (!Info.nextStep(S))
3770 // If we're hunting down a 'case' or 'default' label, recurse through
3771 // substatements until we hit the label.
3773 // FIXME: We don't start the lifetime of objects whose initialization we
3774 // jump over. However, such objects must be of class type with a trivial
3775 // default constructor that initialize all subobjects, so must be empty,
3776 // so this almost never matters.
3777 switch (S->getStmtClass()) {
3778 case Stmt::CompoundStmtClass:
3779 // FIXME: Precompute which substatement of a compound statement we
3780 // would jump to, and go straight there rather than performing a
3781 // linear scan each time.
3782 case Stmt::LabelStmtClass:
3783 case Stmt::AttributedStmtClass:
3784 case Stmt::DoStmtClass:
3787 case Stmt::CaseStmtClass:
3788 case Stmt::DefaultStmtClass:
3793 case Stmt::IfStmtClass: {
3794 // FIXME: Precompute which side of an 'if' we would jump to, and go
3795 // straight there rather than scanning both sides.
3796 const IfStmt *IS = cast<IfStmt>(S);
3798 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3799 // preceded by our switch label.
3800 BlockScopeRAII Scope(Info);
3802 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3803 if (ESR != ESR_CaseNotFound || !IS->getElse())
3805 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3808 case Stmt::WhileStmtClass: {
3809 EvalStmtResult ESR =
3810 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3811 if (ESR != ESR_Continue)
3816 case Stmt::ForStmtClass: {
3817 const ForStmt *FS = cast<ForStmt>(S);
3818 EvalStmtResult ESR =
3819 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3820 if (ESR != ESR_Continue)
3823 FullExpressionRAII IncScope(Info);
3824 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3830 case Stmt::DeclStmtClass:
3831 // FIXME: If the variable has initialization that can't be jumped over,
3832 // bail out of any immediately-surrounding compound-statement too.
3834 return ESR_CaseNotFound;
3838 switch (S->getStmtClass()) {
3840 if (const Expr *E = dyn_cast<Expr>(S)) {
3841 // Don't bother evaluating beyond an expression-statement which couldn't
3843 FullExpressionRAII Scope(Info);
3844 if (!EvaluateIgnoredValue(Info, E))
3846 return ESR_Succeeded;
3849 Info.FFDiag(S->getLocStart());
3852 case Stmt::NullStmtClass:
3853 return ESR_Succeeded;
3855 case Stmt::DeclStmtClass: {
3856 const DeclStmt *DS = cast<DeclStmt>(S);
3857 for (const auto *DclIt : DS->decls()) {
3858 // Each declaration initialization is its own full-expression.
3859 // FIXME: This isn't quite right; if we're performing aggregate
3860 // initialization, each braced subexpression is its own full-expression.
3861 FullExpressionRAII Scope(Info);
3862 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3865 return ESR_Succeeded;
3868 case Stmt::ReturnStmtClass: {
3869 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3870 FullExpressionRAII Scope(Info);
3873 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3874 : Evaluate(Result.Value, Info, RetExpr)))
3876 return ESR_Returned;
3879 case Stmt::CompoundStmtClass: {
3880 BlockScopeRAII Scope(Info);
3882 const CompoundStmt *CS = cast<CompoundStmt>(S);
3883 for (const auto *BI : CS->body()) {
3884 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3885 if (ESR == ESR_Succeeded)
3887 else if (ESR != ESR_CaseNotFound)
3890 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3893 case Stmt::IfStmtClass: {
3894 const IfStmt *IS = cast<IfStmt>(S);
3896 // Evaluate the condition, as either a var decl or as an expression.
3897 BlockScopeRAII Scope(Info);
3898 if (const Stmt *Init = IS->getInit()) {
3899 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3900 if (ESR != ESR_Succeeded)
3904 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3907 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3908 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3909 if (ESR != ESR_Succeeded)
3912 return ESR_Succeeded;
3915 case Stmt::WhileStmtClass: {
3916 const WhileStmt *WS = cast<WhileStmt>(S);
3918 BlockScopeRAII Scope(Info);
3920 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3926 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3927 if (ESR != ESR_Continue)
3930 return ESR_Succeeded;
3933 case Stmt::DoStmtClass: {
3934 const DoStmt *DS = cast<DoStmt>(S);
3937 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3938 if (ESR != ESR_Continue)
3942 FullExpressionRAII CondScope(Info);
3943 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3946 return ESR_Succeeded;
3949 case Stmt::ForStmtClass: {
3950 const ForStmt *FS = cast<ForStmt>(S);
3951 BlockScopeRAII Scope(Info);
3952 if (FS->getInit()) {
3953 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3954 if (ESR != ESR_Succeeded)
3958 BlockScopeRAII Scope(Info);
3959 bool Continue = true;
3960 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3961 FS->getCond(), Continue))
3966 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3967 if (ESR != ESR_Continue)
3971 FullExpressionRAII IncScope(Info);
3972 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3976 return ESR_Succeeded;
3979 case Stmt::CXXForRangeStmtClass: {
3980 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3981 BlockScopeRAII Scope(Info);
3983 // Initialize the __range variable.
3984 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3985 if (ESR != ESR_Succeeded)
3988 // Create the __begin and __end iterators.
3989 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3990 if (ESR != ESR_Succeeded)
3992 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3993 if (ESR != ESR_Succeeded)
3997 // Condition: __begin != __end.
3999 bool Continue = true;
4000 FullExpressionRAII CondExpr(Info);
4001 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4007 // User's variable declaration, initialized by *__begin.
4008 BlockScopeRAII InnerScope(Info);
4009 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4010 if (ESR != ESR_Succeeded)
4014 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4015 if (ESR != ESR_Continue)
4018 // Increment: ++__begin
4019 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4023 return ESR_Succeeded;
4026 case Stmt::SwitchStmtClass:
4027 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4029 case Stmt::ContinueStmtClass:
4030 return ESR_Continue;
4032 case Stmt::BreakStmtClass:
4035 case Stmt::LabelStmtClass:
4036 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4038 case Stmt::AttributedStmtClass:
4039 // As a general principle, C++11 attributes can be ignored without
4040 // any semantic impact.
4041 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4044 case Stmt::CaseStmtClass:
4045 case Stmt::DefaultStmtClass:
4046 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4050 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4051 /// default constructor. If so, we'll fold it whether or not it's marked as
4052 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4053 /// so we need special handling.
4054 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4055 const CXXConstructorDecl *CD,
4056 bool IsValueInitialization) {
4057 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4060 // Value-initialization does not call a trivial default constructor, so such a
4061 // call is a core constant expression whether or not the constructor is
4063 if (!CD->isConstexpr() && !IsValueInitialization) {
4064 if (Info.getLangOpts().CPlusPlus11) {
4065 // FIXME: If DiagDecl is an implicitly-declared special member function,
4066 // we should be much more explicit about why it's not constexpr.
4067 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4068 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4069 Info.Note(CD->getLocation(), diag::note_declared_at);
4071 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4077 /// CheckConstexprFunction - Check that a function can be called in a constant
4079 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4080 const FunctionDecl *Declaration,
4081 const FunctionDecl *Definition,
4083 // Potential constant expressions can contain calls to declared, but not yet
4084 // defined, constexpr functions.
4085 if (Info.checkingPotentialConstantExpression() && !Definition &&
4086 Declaration->isConstexpr())
4089 // Bail out with no diagnostic if the function declaration itself is invalid.
4090 // We will have produced a relevant diagnostic while parsing it.
4091 if (Declaration->isInvalidDecl())
4094 // Can we evaluate this function call?
4095 if (Definition && Definition->isConstexpr() &&
4096 !Definition->isInvalidDecl() && Body)
4099 if (Info.getLangOpts().CPlusPlus11) {
4100 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4102 // If this function is not constexpr because it is an inherited
4103 // non-constexpr constructor, diagnose that directly.
4104 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4105 if (CD && CD->isInheritingConstructor()) {
4106 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4107 if (!Inherited->isConstexpr())
4108 DiagDecl = CD = Inherited;
4111 // FIXME: If DiagDecl is an implicitly-declared special member function
4112 // or an inheriting constructor, we should be much more explicit about why
4113 // it's not constexpr.
4114 if (CD && CD->isInheritingConstructor())
4115 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4116 << CD->getInheritedConstructor().getConstructor()->getParent();
4118 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4119 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4120 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4122 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4127 /// Determine if a class has any fields that might need to be copied by a
4128 /// trivial copy or move operation.
4129 static bool hasFields(const CXXRecordDecl *RD) {
4130 if (!RD || RD->isEmpty())
4132 for (auto *FD : RD->fields()) {
4133 if (FD->isUnnamedBitfield())
4137 for (auto &Base : RD->bases())
4138 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4144 typedef SmallVector<APValue, 8> ArgVector;
4147 /// EvaluateArgs - Evaluate the arguments to a function call.
4148 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4150 bool Success = true;
4151 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4153 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4154 // If we're checking for a potential constant expression, evaluate all
4155 // initializers even if some of them fail.
4156 if (!Info.noteFailure())
4164 /// Evaluate a function call.
4165 static bool HandleFunctionCall(SourceLocation CallLoc,
4166 const FunctionDecl *Callee, const LValue *This,
4167 ArrayRef<const Expr*> Args, const Stmt *Body,
4168 EvalInfo &Info, APValue &Result,
4169 const LValue *ResultSlot) {
4170 ArgVector ArgValues(Args.size());
4171 if (!EvaluateArgs(Args, ArgValues, Info))
4174 if (!Info.CheckCallLimit(CallLoc))
4177 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4179 // For a trivial copy or move assignment, perform an APValue copy. This is
4180 // essential for unions, where the operations performed by the assignment
4181 // operator cannot be represented as statements.
4183 // Skip this for non-union classes with no fields; in that case, the defaulted
4184 // copy/move does not actually read the object.
4185 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4186 if (MD && MD->isDefaulted() &&
4187 (MD->getParent()->isUnion() ||
4188 (MD->isTrivial() && hasFields(MD->getParent())))) {
4190 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4192 RHS.setFrom(Info.Ctx, ArgValues[0]);
4194 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4197 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4200 This->moveInto(Result);
4202 } else if (MD && isLambdaCallOperator(MD)) {
4203 // We're in a lambda; determine the lambda capture field maps.
4204 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4205 Frame.LambdaThisCaptureField);
4208 StmtResult Ret = {Result, ResultSlot};
4209 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4210 if (ESR == ESR_Succeeded) {
4211 if (Callee->getReturnType()->isVoidType())
4213 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4215 return ESR == ESR_Returned;
4218 /// Evaluate a constructor call.
4219 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4221 const CXXConstructorDecl *Definition,
4222 EvalInfo &Info, APValue &Result) {
4223 SourceLocation CallLoc = E->getExprLoc();
4224 if (!Info.CheckCallLimit(CallLoc))
4227 const CXXRecordDecl *RD = Definition->getParent();
4228 if (RD->getNumVBases()) {
4229 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4233 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4235 // FIXME: Creating an APValue just to hold a nonexistent return value is
4238 StmtResult Ret = {RetVal, nullptr};
4240 // If it's a delegating constructor, delegate.
4241 if (Definition->isDelegatingConstructor()) {
4242 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4244 FullExpressionRAII InitScope(Info);
4245 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4248 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4251 // For a trivial copy or move constructor, perform an APValue copy. This is
4252 // essential for unions (or classes with anonymous union members), where the
4253 // operations performed by the constructor cannot be represented by
4254 // ctor-initializers.
4256 // Skip this for empty non-union classes; we should not perform an
4257 // lvalue-to-rvalue conversion on them because their copy constructor does not
4258 // actually read them.
4259 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4260 (Definition->getParent()->isUnion() ||
4261 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4263 RHS.setFrom(Info.Ctx, ArgValues[0]);
4264 return handleLValueToRValueConversion(
4265 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4269 // Reserve space for the struct members.
4270 if (!RD->isUnion() && Result.isUninit())
4271 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4272 std::distance(RD->field_begin(), RD->field_end()));
4274 if (RD->isInvalidDecl()) return false;
4275 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4277 // A scope for temporaries lifetime-extended by reference members.
4278 BlockScopeRAII LifetimeExtendedScope(Info);
4280 bool Success = true;
4281 unsigned BasesSeen = 0;
4283 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4285 for (const auto *I : Definition->inits()) {
4286 LValue Subobject = This;
4287 APValue *Value = &Result;
4289 // Determine the subobject to initialize.
4290 FieldDecl *FD = nullptr;
4291 if (I->isBaseInitializer()) {
4292 QualType BaseType(I->getBaseClass(), 0);
4294 // Non-virtual base classes are initialized in the order in the class
4295 // definition. We have already checked for virtual base classes.
4296 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4297 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4298 "base class initializers not in expected order");
4301 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4302 BaseType->getAsCXXRecordDecl(), &Layout))
4304 Value = &Result.getStructBase(BasesSeen++);
4305 } else if ((FD = I->getMember())) {
4306 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4308 if (RD->isUnion()) {
4309 Result = APValue(FD);
4310 Value = &Result.getUnionValue();
4312 Value = &Result.getStructField(FD->getFieldIndex());
4314 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4315 // Walk the indirect field decl's chain to find the object to initialize,
4316 // and make sure we've initialized every step along it.
4317 for (auto *C : IFD->chain()) {
4318 FD = cast<FieldDecl>(C);
4319 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4320 // Switch the union field if it differs. This happens if we had
4321 // preceding zero-initialization, and we're now initializing a union
4322 // subobject other than the first.
4323 // FIXME: In this case, the values of the other subobjects are
4324 // specified, since zero-initialization sets all padding bits to zero.
4325 if (Value->isUninit() ||
4326 (Value->isUnion() && Value->getUnionField() != FD)) {
4328 *Value = APValue(FD);
4330 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4331 std::distance(CD->field_begin(), CD->field_end()));
4333 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4336 Value = &Value->getUnionValue();
4338 Value = &Value->getStructField(FD->getFieldIndex());
4341 llvm_unreachable("unknown base initializer kind");
4344 FullExpressionRAII InitScope(Info);
4345 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4346 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4348 // If we're checking for a potential constant expression, evaluate all
4349 // initializers even if some of them fail.
4350 if (!Info.noteFailure())
4357 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4360 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4361 ArrayRef<const Expr*> Args,
4362 const CXXConstructorDecl *Definition,
4363 EvalInfo &Info, APValue &Result) {
4364 ArgVector ArgValues(Args.size());
4365 if (!EvaluateArgs(Args, ArgValues, Info))
4368 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4372 //===----------------------------------------------------------------------===//
4373 // Generic Evaluation
4374 //===----------------------------------------------------------------------===//
4377 template <class Derived>
4378 class ExprEvaluatorBase
4379 : public ConstStmtVisitor<Derived, bool> {
4381 Derived &getDerived() { return static_cast<Derived&>(*this); }
4382 bool DerivedSuccess(const APValue &V, const Expr *E) {
4383 return getDerived().Success(V, E);
4385 bool DerivedZeroInitialization(const Expr *E) {
4386 return getDerived().ZeroInitialization(E);
4389 // Check whether a conditional operator with a non-constant condition is a
4390 // potential constant expression. If neither arm is a potential constant
4391 // expression, then the conditional operator is not either.
4392 template<typename ConditionalOperator>
4393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4394 assert(Info.checkingPotentialConstantExpression());
4396 // Speculatively evaluate both arms.
4397 SmallVector<PartialDiagnosticAt, 8> Diag;
4399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4400 StmtVisitorTy::Visit(E->getFalseExpr());
4406 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4408 StmtVisitorTy::Visit(E->getTrueExpr());
4413 Error(E, diag::note_constexpr_conditional_never_const);
4417 template<typename ConditionalOperator>
4418 bool HandleConditionalOperator(const ConditionalOperator *E) {
4420 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4421 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4422 CheckPotentialConstantConditional(E);
4426 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4427 return StmtVisitorTy::Visit(EvalExpr);
4432 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4433 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4435 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4436 return Info.CCEDiag(E, D);
4439 bool ZeroInitialization(const Expr *E) { return Error(E); }
4442 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4444 EvalInfo &getEvalInfo() { return Info; }
4446 /// Report an evaluation error. This should only be called when an error is
4447 /// first discovered. When propagating an error, just return false.
4448 bool Error(const Expr *E, diag::kind D) {
4452 bool Error(const Expr *E) {
4453 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4456 bool VisitStmt(const Stmt *) {
4457 llvm_unreachable("Expression evaluator should not be called on stmts");
4459 bool VisitExpr(const Expr *E) {
4463 bool VisitParenExpr(const ParenExpr *E)
4464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4465 bool VisitUnaryExtension(const UnaryOperator *E)
4466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4467 bool VisitUnaryPlus(const UnaryOperator *E)
4468 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4469 bool VisitChooseExpr(const ChooseExpr *E)
4470 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4471 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4472 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4473 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4474 { return StmtVisitorTy::Visit(E->getReplacement()); }
4475 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4476 { return StmtVisitorTy::Visit(E->getExpr()); }
4477 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4478 // The initializer may not have been parsed yet, or might be erroneous.
4481 return StmtVisitorTy::Visit(E->getExpr());
4483 // We cannot create any objects for which cleanups are required, so there is
4484 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4485 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4486 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4488 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4489 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4490 return static_cast<Derived*>(this)->VisitCastExpr(E);
4492 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4493 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4494 return static_cast<Derived*>(this)->VisitCastExpr(E);
4497 bool VisitBinaryOperator(const BinaryOperator *E) {
4498 switch (E->getOpcode()) {
4503 VisitIgnoredValue(E->getLHS());
4504 return StmtVisitorTy::Visit(E->getRHS());
4509 if (!HandleMemberPointerAccess(Info, E, Obj))
4512 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4514 return DerivedSuccess(Result, E);
4519 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4520 // Evaluate and cache the common expression. We treat it as a temporary,
4521 // even though it's not quite the same thing.
4522 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4523 Info, E->getCommon()))
4526 return HandleConditionalOperator(E);
4529 bool VisitConditionalOperator(const ConditionalOperator *E) {
4530 bool IsBcpCall = false;
4531 // If the condition (ignoring parens) is a __builtin_constant_p call,
4532 // the result is a constant expression if it can be folded without
4533 // side-effects. This is an important GNU extension. See GCC PR38377
4535 if (const CallExpr *CallCE =
4536 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4537 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4540 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4541 // constant expression; we can't check whether it's potentially foldable.
4542 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4545 FoldConstant Fold(Info, IsBcpCall);
4546 if (!HandleConditionalOperator(E)) {
4547 Fold.keepDiagnostics();
4554 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4555 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4556 return DerivedSuccess(*Value, E);
4558 const Expr *Source = E->getSourceExpr();
4561 if (Source == E) { // sanity checking.
4562 assert(0 && "OpaqueValueExpr recursively refers to itself");
4565 return StmtVisitorTy::Visit(Source);
4568 bool VisitCallExpr(const CallExpr *E) {
4570 if (!handleCallExpr(E, Result, nullptr))
4572 return DerivedSuccess(Result, E);
4575 bool handleCallExpr(const CallExpr *E, APValue &Result,
4576 const LValue *ResultSlot) {
4577 const Expr *Callee = E->getCallee()->IgnoreParens();
4578 QualType CalleeType = Callee->getType();
4580 const FunctionDecl *FD = nullptr;
4581 LValue *This = nullptr, ThisVal;
4582 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4583 bool HasQualifier = false;
4585 // Extract function decl and 'this' pointer from the callee.
4586 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4587 const ValueDecl *Member = nullptr;
4588 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4589 // Explicit bound member calls, such as x.f() or p->g();
4590 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4592 Member = ME->getMemberDecl();
4594 HasQualifier = ME->hasQualifier();
4595 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4596 // Indirect bound member calls ('.*' or '->*').
4597 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4598 if (!Member) return false;
4601 return Error(Callee);
4603 FD = dyn_cast<FunctionDecl>(Member);
4605 return Error(Callee);
4606 } else if (CalleeType->isFunctionPointerType()) {
4608 if (!EvaluatePointer(Callee, Call, Info))
4611 if (!Call.getLValueOffset().isZero())
4612 return Error(Callee);
4613 FD = dyn_cast_or_null<FunctionDecl>(
4614 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4616 return Error(Callee);
4617 // Don't call function pointers which have been cast to some other type.
4618 // Per DR (no number yet), the caller and callee can differ in noexcept.
4619 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4620 CalleeType->getPointeeType(), FD->getType())) {
4624 // Overloaded operator calls to member functions are represented as normal
4625 // calls with '*this' as the first argument.
4626 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4627 if (MD && !MD->isStatic()) {
4628 // FIXME: When selecting an implicit conversion for an overloaded
4629 // operator delete, we sometimes try to evaluate calls to conversion
4630 // operators without a 'this' parameter!
4634 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4637 Args = Args.slice(1);
4638 } else if (MD && MD->isLambdaStaticInvoker()) {
4639 // Map the static invoker for the lambda back to the call operator.
4640 // Conveniently, we don't have to slice out the 'this' argument (as is
4641 // being done for the non-static case), since a static member function
4642 // doesn't have an implicit argument passed in.
4643 const CXXRecordDecl *ClosureClass = MD->getParent();
4645 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4646 "Number of captures must be zero for conversion to function-ptr");
4648 const CXXMethodDecl *LambdaCallOp =
4649 ClosureClass->getLambdaCallOperator();
4651 // Set 'FD', the function that will be called below, to the call
4652 // operator. If the closure object represents a generic lambda, find
4653 // the corresponding specialization of the call operator.
4655 if (ClosureClass->isGenericLambda()) {
4656 assert(MD->isFunctionTemplateSpecialization() &&
4657 "A generic lambda's static-invoker function must be a "
4658 "template specialization");
4659 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4660 FunctionTemplateDecl *CallOpTemplate =
4661 LambdaCallOp->getDescribedFunctionTemplate();
4662 void *InsertPos = nullptr;
4663 FunctionDecl *CorrespondingCallOpSpecialization =
4664 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4665 assert(CorrespondingCallOpSpecialization &&
4666 "We must always have a function call operator specialization "
4667 "that corresponds to our static invoker specialization");
4668 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4677 if (This && !This->checkSubobject(Info, E, CSK_This))
4680 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4681 // calls to such functions in constant expressions.
4682 if (This && !HasQualifier &&
4683 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4684 return Error(E, diag::note_constexpr_virtual_call);
4686 const FunctionDecl *Definition = nullptr;
4687 Stmt *Body = FD->getBody(Definition);
4689 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4690 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4691 Result, ResultSlot))
4697 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4698 return StmtVisitorTy::Visit(E->getInitializer());
4700 bool VisitInitListExpr(const InitListExpr *E) {
4701 if (E->getNumInits() == 0)
4702 return DerivedZeroInitialization(E);
4703 if (E->getNumInits() == 1)
4704 return StmtVisitorTy::Visit(E->getInit(0));
4707 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4708 return DerivedZeroInitialization(E);
4710 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4711 return DerivedZeroInitialization(E);
4713 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4714 return DerivedZeroInitialization(E);
4717 /// A member expression where the object is a prvalue is itself a prvalue.
4718 bool VisitMemberExpr(const MemberExpr *E) {
4719 assert(!E->isArrow() && "missing call to bound member function?");
4722 if (!Evaluate(Val, Info, E->getBase()))
4725 QualType BaseTy = E->getBase()->getType();
4727 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4728 if (!FD) return Error(E);
4729 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4730 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4731 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4733 CompleteObject Obj(&Val, BaseTy);
4734 SubobjectDesignator Designator(BaseTy);
4735 Designator.addDeclUnchecked(FD);
4738 return extractSubobject(Info, E, Obj, Designator, Result) &&
4739 DerivedSuccess(Result, E);
4742 bool VisitCastExpr(const CastExpr *E) {
4743 switch (E->getCastKind()) {
4747 case CK_AtomicToNonAtomic: {
4749 // This does not need to be done in place even for class/array types:
4750 // atomic-to-non-atomic conversion implies copying the object
4752 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4754 return DerivedSuccess(AtomicVal, E);
4758 case CK_UserDefinedConversion:
4759 return StmtVisitorTy::Visit(E->getSubExpr());
4761 case CK_LValueToRValue: {
4763 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4766 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4767 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4770 return DerivedSuccess(RVal, E);
4777 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4778 return VisitUnaryPostIncDec(UO);
4780 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4781 return VisitUnaryPostIncDec(UO);
4783 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4784 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4788 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4791 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4792 UO->isIncrementOp(), &RVal))
4794 return DerivedSuccess(RVal, UO);
4797 bool VisitStmtExpr(const StmtExpr *E) {
4798 // We will have checked the full-expressions inside the statement expression
4799 // when they were completed, and don't need to check them again now.
4800 if (Info.checkingForOverflow())
4803 BlockScopeRAII Scope(Info);
4804 const CompoundStmt *CS = E->getSubStmt();
4805 if (CS->body_empty())
4808 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4809 BE = CS->body_end();
4812 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4814 Info.FFDiag((*BI)->getLocStart(),
4815 diag::note_constexpr_stmt_expr_unsupported);
4818 return this->Visit(FinalExpr);
4821 APValue ReturnValue;
4822 StmtResult Result = { ReturnValue, nullptr };
4823 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4824 if (ESR != ESR_Succeeded) {
4825 // FIXME: If the statement-expression terminated due to 'return',
4826 // 'break', or 'continue', it would be nice to propagate that to
4827 // the outer statement evaluation rather than bailing out.
4828 if (ESR != ESR_Failed)
4829 Info.FFDiag((*BI)->getLocStart(),
4830 diag::note_constexpr_stmt_expr_unsupported);
4835 llvm_unreachable("Return from function from the loop above.");
4838 /// Visit a value which is evaluated, but whose value is ignored.
4839 void VisitIgnoredValue(const Expr *E) {
4840 EvaluateIgnoredValue(Info, E);
4843 /// Potentially visit a MemberExpr's base expression.
4844 void VisitIgnoredBaseExpression(const Expr *E) {
4845 // While MSVC doesn't evaluate the base expression, it does diagnose the
4846 // presence of side-effecting behavior.
4847 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4849 VisitIgnoredValue(E);
4855 //===----------------------------------------------------------------------===//
4856 // Common base class for lvalue and temporary evaluation.
4857 //===----------------------------------------------------------------------===//
4859 template<class Derived>
4860 class LValueExprEvaluatorBase
4861 : public ExprEvaluatorBase<Derived> {
4865 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4866 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4868 bool Success(APValue::LValueBase B) {
4873 bool evaluatePointer(const Expr *E, LValue &Result) {
4874 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4878 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4879 : ExprEvaluatorBaseTy(Info), Result(Result),
4880 InvalidBaseOK(InvalidBaseOK) {}
4882 bool Success(const APValue &V, const Expr *E) {
4883 Result.setFrom(this->Info.Ctx, V);
4887 bool VisitMemberExpr(const MemberExpr *E) {
4888 // Handle non-static data members.
4892 EvalOK = evaluatePointer(E->getBase(), Result);
4893 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4894 } else if (E->getBase()->isRValue()) {
4895 assert(E->getBase()->getType()->isRecordType());
4896 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4897 BaseTy = E->getBase()->getType();
4899 EvalOK = this->Visit(E->getBase());
4900 BaseTy = E->getBase()->getType();
4905 Result.setInvalid(E);
4909 const ValueDecl *MD = E->getMemberDecl();
4910 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4911 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4912 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4914 if (!HandleLValueMember(this->Info, E, Result, FD))
4916 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4917 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4920 return this->Error(E);
4922 if (MD->getType()->isReferenceType()) {
4924 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4927 return Success(RefValue, E);
4932 bool VisitBinaryOperator(const BinaryOperator *E) {
4933 switch (E->getOpcode()) {
4935 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4939 return HandleMemberPointerAccess(this->Info, E, Result);
4943 bool VisitCastExpr(const CastExpr *E) {
4944 switch (E->getCastKind()) {
4946 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4948 case CK_DerivedToBase:
4949 case CK_UncheckedDerivedToBase:
4950 if (!this->Visit(E->getSubExpr()))
4953 // Now figure out the necessary offset to add to the base LV to get from
4954 // the derived class to the base class.
4955 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4962 //===----------------------------------------------------------------------===//
4963 // LValue Evaluation
4965 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4966 // function designators (in C), decl references to void objects (in C), and
4967 // temporaries (if building with -Wno-address-of-temporary).
4969 // LValue evaluation produces values comprising a base expression of one of the
4975 // * CompoundLiteralExpr in C (and in global scope in C++)
4979 // * ObjCStringLiteralExpr
4983 // * CallExpr for a MakeStringConstant builtin
4984 // - Locals and temporaries
4985 // * MaterializeTemporaryExpr
4986 // * Any Expr, with a CallIndex indicating the function in which the temporary
4987 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4988 // from the AST (FIXME).
4989 // * A MaterializeTemporaryExpr that has static storage duration, with no
4990 // CallIndex, for a lifetime-extended temporary.
4991 // plus an offset in bytes.
4992 //===----------------------------------------------------------------------===//
4994 class LValueExprEvaluator
4995 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4997 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
4998 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5000 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5001 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5003 bool VisitDeclRefExpr(const DeclRefExpr *E);
5004 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5005 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5006 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5007 bool VisitMemberExpr(const MemberExpr *E);
5008 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5009 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5010 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5011 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5012 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5013 bool VisitUnaryDeref(const UnaryOperator *E);
5014 bool VisitUnaryReal(const UnaryOperator *E);
5015 bool VisitUnaryImag(const UnaryOperator *E);
5016 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5017 return VisitUnaryPreIncDec(UO);
5019 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5020 return VisitUnaryPreIncDec(UO);
5022 bool VisitBinAssign(const BinaryOperator *BO);
5023 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5025 bool VisitCastExpr(const CastExpr *E) {
5026 switch (E->getCastKind()) {
5028 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5030 case CK_LValueBitCast:
5031 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5032 if (!Visit(E->getSubExpr()))
5034 Result.Designator.setInvalid();
5037 case CK_BaseToDerived:
5038 if (!Visit(E->getSubExpr()))
5040 return HandleBaseToDerivedCast(Info, E, Result);
5044 } // end anonymous namespace
5046 /// Evaluate an expression as an lvalue. This can be legitimately called on
5047 /// expressions which are not glvalues, in three cases:
5048 /// * function designators in C, and
5049 /// * "extern void" objects
5050 /// * @selector() expressions in Objective-C
5051 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5052 bool InvalidBaseOK) {
5053 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5054 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5055 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5058 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5059 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5061 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5062 return VisitVarDecl(E, VD);
5063 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5064 return Visit(BD->getBinding());
5069 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5071 // If we are within a lambda's call operator, check whether the 'VD' referred
5072 // to within 'E' actually represents a lambda-capture that maps to a
5073 // data-member/field within the closure object, and if so, evaluate to the
5074 // field or what the field refers to.
5075 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5076 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5077 if (Info.checkingPotentialConstantExpression())
5079 // Start with 'Result' referring to the complete closure object...
5080 Result = *Info.CurrentCall->This;
5081 // ... then update it to refer to the field of the closure object
5082 // that represents the capture.
5083 if (!HandleLValueMember(Info, E, Result, FD))
5085 // And if the field is of reference type, update 'Result' to refer to what
5086 // the field refers to.
5087 if (FD->getType()->isReferenceType()) {
5089 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5092 Result.setFrom(Info.Ctx, RVal);
5097 CallStackFrame *Frame = nullptr;
5098 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5099 // Only if a local variable was declared in the function currently being
5100 // evaluated, do we expect to be able to find its value in the current
5101 // frame. (Otherwise it was likely declared in an enclosing context and
5102 // could either have a valid evaluatable value (for e.g. a constexpr
5103 // variable) or be ill-formed (and trigger an appropriate evaluation
5105 if (Info.CurrentCall->Callee &&
5106 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5107 Frame = Info.CurrentCall;
5111 if (!VD->getType()->isReferenceType()) {
5113 Result.set(VD, Frame->Index);
5120 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5122 if (V->isUninit()) {
5123 if (!Info.checkingPotentialConstantExpression())
5124 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5127 return Success(*V, E);
5130 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5131 const MaterializeTemporaryExpr *E) {
5132 // Walk through the expression to find the materialized temporary itself.
5133 SmallVector<const Expr *, 2> CommaLHSs;
5134 SmallVector<SubobjectAdjustment, 2> Adjustments;
5135 const Expr *Inner = E->GetTemporaryExpr()->
5136 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5138 // If we passed any comma operators, evaluate their LHSs.
5139 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5140 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5143 // A materialized temporary with static storage duration can appear within the
5144 // result of a constant expression evaluation, so we need to preserve its
5145 // value for use outside this evaluation.
5147 if (E->getStorageDuration() == SD_Static) {
5148 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5152 Value = &Info.CurrentCall->
5153 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5154 Result.set(E, Info.CurrentCall->Index);
5157 QualType Type = Inner->getType();
5159 // Materialize the temporary itself.
5160 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5161 (E->getStorageDuration() == SD_Static &&
5162 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5167 // Adjust our lvalue to refer to the desired subobject.
5168 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5170 switch (Adjustments[I].Kind) {
5171 case SubobjectAdjustment::DerivedToBaseAdjustment:
5172 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5175 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5178 case SubobjectAdjustment::FieldAdjustment:
5179 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5181 Type = Adjustments[I].Field->getType();
5184 case SubobjectAdjustment::MemberPointerAdjustment:
5185 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5186 Adjustments[I].Ptr.RHS))
5188 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5197 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5198 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5199 "lvalue compound literal in c++?");
5200 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5201 // only see this when folding in C, so there's no standard to follow here.
5205 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5206 if (!E->isPotentiallyEvaluated())
5209 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5210 << E->getExprOperand()->getType()
5211 << E->getExprOperand()->getSourceRange();
5215 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5219 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5220 // Handle static data members.
5221 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5222 VisitIgnoredBaseExpression(E->getBase());
5223 return VisitVarDecl(E, VD);
5226 // Handle static member functions.
5227 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5228 if (MD->isStatic()) {
5229 VisitIgnoredBaseExpression(E->getBase());
5234 // Handle non-static data members.
5235 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5238 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5239 // FIXME: Deal with vectors as array subscript bases.
5240 if (E->getBase()->getType()->isVectorType())
5243 if (!evaluatePointer(E->getBase(), Result))
5247 if (!EvaluateInteger(E->getIdx(), Index, Info))
5250 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5253 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5254 return evaluatePointer(E->getSubExpr(), Result);
5257 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5258 if (!Visit(E->getSubExpr()))
5260 // __real is a no-op on scalar lvalues.
5261 if (E->getSubExpr()->getType()->isAnyComplexType())
5262 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5266 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5267 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5268 "lvalue __imag__ on scalar?");
5269 if (!Visit(E->getSubExpr()))
5271 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5275 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5276 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5279 if (!this->Visit(UO->getSubExpr()))
5282 return handleIncDec(
5283 this->Info, UO, Result, UO->getSubExpr()->getType(),
5284 UO->isIncrementOp(), nullptr);
5287 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5288 const CompoundAssignOperator *CAO) {
5289 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5294 // The overall lvalue result is the result of evaluating the LHS.
5295 if (!this->Visit(CAO->getLHS())) {
5296 if (Info.noteFailure())
5297 Evaluate(RHS, this->Info, CAO->getRHS());
5301 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5304 return handleCompoundAssignment(
5306 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5307 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5310 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5311 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5316 if (!this->Visit(E->getLHS())) {
5317 if (Info.noteFailure())
5318 Evaluate(NewVal, this->Info, E->getRHS());
5322 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5325 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5329 //===----------------------------------------------------------------------===//
5330 // Pointer Evaluation
5331 //===----------------------------------------------------------------------===//
5333 /// \brief Attempts to compute the number of bytes available at the pointer
5334 /// returned by a function with the alloc_size attribute. Returns true if we
5335 /// were successful. Places an unsigned number into `Result`.
5337 /// This expects the given CallExpr to be a call to a function with an
5338 /// alloc_size attribute.
5339 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5340 const CallExpr *Call,
5341 llvm::APInt &Result) {
5342 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5344 // alloc_size args are 1-indexed, 0 means not present.
5345 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5346 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5347 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5348 if (Call->getNumArgs() <= SizeArgNo)
5351 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5352 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5354 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5356 Into = Into.zextOrSelf(BitsInSizeT);
5361 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5364 if (!AllocSize->getNumElemsParam()) {
5365 Result = std::move(SizeOfElem);
5369 APSInt NumberOfElems;
5370 // Argument numbers start at 1
5371 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5372 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5376 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5380 Result = std::move(BytesAvailable);
5384 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5386 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5388 llvm::APInt &Result) {
5389 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5390 "Can't get the size of a non alloc_size function");
5391 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5392 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5393 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5396 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5397 /// a function with the alloc_size attribute. If it was possible to do so, this
5398 /// function will return true, make Result's Base point to said function call,
5399 /// and mark Result's Base as invalid.
5400 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5405 // Because we do no form of static analysis, we only support const variables.
5407 // Additionally, we can't support parameters, nor can we support static
5408 // variables (in the latter case, use-before-assign isn't UB; in the former,
5409 // we have no clue what they'll be assigned to).
5411 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5412 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5415 const Expr *Init = VD->getAnyInitializer();
5419 const Expr *E = Init->IgnoreParens();
5420 if (!tryUnwrapAllocSizeCall(E))
5423 // Store E instead of E unwrapped so that the type of the LValue's base is
5424 // what the user wanted.
5425 Result.setInvalid(E);
5427 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5428 Result.addUnsizedArray(Info, Pointee);
5433 class PointerExprEvaluator
5434 : public ExprEvaluatorBase<PointerExprEvaluator> {
5438 bool Success(const Expr *E) {
5443 bool evaluateLValue(const Expr *E, LValue &Result) {
5444 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5447 bool evaluatePointer(const Expr *E, LValue &Result) {
5448 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5451 bool visitNonBuiltinCallExpr(const CallExpr *E);
5454 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5455 : ExprEvaluatorBaseTy(info), Result(Result),
5456 InvalidBaseOK(InvalidBaseOK) {}
5458 bool Success(const APValue &V, const Expr *E) {
5459 Result.setFrom(Info.Ctx, V);
5462 bool ZeroInitialization(const Expr *E) {
5463 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5464 Result.set((Expr*)nullptr, 0, false, true, Offset);
5468 bool VisitBinaryOperator(const BinaryOperator *E);
5469 bool VisitCastExpr(const CastExpr* E);
5470 bool VisitUnaryAddrOf(const UnaryOperator *E);
5471 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5472 { return Success(E); }
5473 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5474 { return Success(E); }
5475 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5476 { return Success(E); }
5477 bool VisitCallExpr(const CallExpr *E);
5478 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5479 bool VisitBlockExpr(const BlockExpr *E) {
5480 if (!E->getBlockDecl()->hasCaptures())
5484 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5485 // Can't look at 'this' when checking a potential constant expression.
5486 if (Info.checkingPotentialConstantExpression())
5488 if (!Info.CurrentCall->This) {
5489 if (Info.getLangOpts().CPlusPlus11)
5490 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5495 Result = *Info.CurrentCall->This;
5496 // If we are inside a lambda's call operator, the 'this' expression refers
5497 // to the enclosing '*this' object (either by value or reference) which is
5498 // either copied into the closure object's field that represents the '*this'
5499 // or refers to '*this'.
5500 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5501 // Update 'Result' to refer to the data member/field of the closure object
5502 // that represents the '*this' capture.
5503 if (!HandleLValueMember(Info, E, Result,
5504 Info.CurrentCall->LambdaThisCaptureField))
5506 // If we captured '*this' by reference, replace the field with its referent.
5507 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5508 ->isPointerType()) {
5510 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5514 Result.setFrom(Info.Ctx, RVal);
5520 // FIXME: Missing: @protocol, @selector
5522 } // end anonymous namespace
5524 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5525 bool InvalidBaseOK) {
5526 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5527 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5530 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5531 if (E->getOpcode() != BO_Add &&
5532 E->getOpcode() != BO_Sub)
5533 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5535 const Expr *PExp = E->getLHS();
5536 const Expr *IExp = E->getRHS();
5537 if (IExp->getType()->isPointerType())
5538 std::swap(PExp, IExp);
5540 bool EvalPtrOK = evaluatePointer(PExp, Result);
5541 if (!EvalPtrOK && !Info.noteFailure())
5544 llvm::APSInt Offset;
5545 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5548 if (E->getOpcode() == BO_Sub)
5549 negateAsSigned(Offset);
5551 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5552 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5555 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5556 return evaluateLValue(E->getSubExpr(), Result);
5559 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5560 const Expr* SubExpr = E->getSubExpr();
5562 switch (E->getCastKind()) {
5567 case CK_CPointerToObjCPointerCast:
5568 case CK_BlockPointerToObjCPointerCast:
5569 case CK_AnyPointerToBlockPointerCast:
5570 case CK_AddressSpaceConversion:
5571 if (!Visit(SubExpr))
5573 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5574 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5575 // also static_casts, but we disallow them as a resolution to DR1312.
5576 if (!E->getType()->isVoidPointerType()) {
5577 Result.Designator.setInvalid();
5578 if (SubExpr->getType()->isVoidPointerType())
5579 CCEDiag(E, diag::note_constexpr_invalid_cast)
5580 << 3 << SubExpr->getType();
5582 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5584 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5585 ZeroInitialization(E);
5588 case CK_DerivedToBase:
5589 case CK_UncheckedDerivedToBase:
5590 if (!evaluatePointer(E->getSubExpr(), Result))
5592 if (!Result.Base && Result.Offset.isZero())
5595 // Now figure out the necessary offset to add to the base LV to get from
5596 // the derived class to the base class.
5597 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5598 castAs<PointerType>()->getPointeeType(),
5601 case CK_BaseToDerived:
5602 if (!Visit(E->getSubExpr()))
5604 if (!Result.Base && Result.Offset.isZero())
5606 return HandleBaseToDerivedCast(Info, E, Result);
5608 case CK_NullToPointer:
5609 VisitIgnoredValue(E->getSubExpr());
5610 return ZeroInitialization(E);
5612 case CK_IntegralToPointer: {
5613 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5616 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5619 if (Value.isInt()) {
5620 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5621 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5622 Result.Base = (Expr*)nullptr;
5623 Result.InvalidBase = false;
5624 Result.Offset = CharUnits::fromQuantity(N);
5625 Result.CallIndex = 0;
5626 Result.Designator.setInvalid();
5627 Result.IsNullPtr = false;
5630 // Cast is of an lvalue, no need to change value.
5631 Result.setFrom(Info.Ctx, Value);
5635 case CK_ArrayToPointerDecay:
5636 if (SubExpr->isGLValue()) {
5637 if (!evaluateLValue(SubExpr, Result))
5640 Result.set(SubExpr, Info.CurrentCall->Index);
5641 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5642 Info, Result, SubExpr))
5645 // The result is a pointer to the first element of the array.
5646 if (const ConstantArrayType *CAT
5647 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5648 Result.addArray(Info, E, CAT);
5650 Result.Designator.setInvalid();
5653 case CK_FunctionToPointerDecay:
5654 return evaluateLValue(SubExpr, Result);
5656 case CK_LValueToRValue: {
5658 if (!evaluateLValue(E->getSubExpr(), LVal))
5662 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5663 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5665 return InvalidBaseOK &&
5666 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5667 return Success(RVal, E);
5671 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5674 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5675 // C++ [expr.alignof]p3:
5676 // When alignof is applied to a reference type, the result is the
5677 // alignment of the referenced type.
5678 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5679 T = Ref->getPointeeType();
5681 // __alignof is defined to return the preferred alignment.
5682 if (T.getQualifiers().hasUnaligned())
5683 return CharUnits::One();
5684 return Info.Ctx.toCharUnitsFromBits(
5685 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5688 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5689 E = E->IgnoreParens();
5691 // The kinds of expressions that we have special-case logic here for
5692 // should be kept up to date with the special checks for those
5693 // expressions in Sema.
5695 // alignof decl is always accepted, even if it doesn't make sense: we default
5696 // to 1 in those cases.
5697 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5698 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5699 /*RefAsPointee*/true);
5701 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5702 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5703 /*RefAsPointee*/true);
5705 return GetAlignOfType(Info, E->getType());
5708 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5709 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5710 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5713 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5716 Result.setInvalid(E);
5717 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5718 Result.addUnsizedArray(Info, PointeeTy);
5722 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5723 if (IsStringLiteralCall(E))
5726 if (unsigned BuiltinOp = E->getBuiltinCallee())
5727 return VisitBuiltinCallExpr(E, BuiltinOp);
5729 return visitNonBuiltinCallExpr(E);
5732 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5733 unsigned BuiltinOp) {
5734 switch (BuiltinOp) {
5735 case Builtin::BI__builtin_addressof:
5736 return evaluateLValue(E->getArg(0), Result);
5737 case Builtin::BI__builtin_assume_aligned: {
5738 // We need to be very careful here because: if the pointer does not have the
5739 // asserted alignment, then the behavior is undefined, and undefined
5740 // behavior is non-constant.
5741 if (!evaluatePointer(E->getArg(0), Result))
5744 LValue OffsetResult(Result);
5746 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5748 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5750 if (E->getNumArgs() > 2) {
5752 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5755 int64_t AdditionalOffset = -Offset.getZExtValue();
5756 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5759 // If there is a base object, then it must have the correct alignment.
5760 if (OffsetResult.Base) {
5761 CharUnits BaseAlignment;
5762 if (const ValueDecl *VD =
5763 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5764 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5767 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5770 if (BaseAlignment < Align) {
5771 Result.Designator.setInvalid();
5772 // FIXME: Add support to Diagnostic for long / long long.
5773 CCEDiag(E->getArg(0),
5774 diag::note_constexpr_baa_insufficient_alignment) << 0
5775 << (unsigned)BaseAlignment.getQuantity()
5776 << (unsigned)Align.getQuantity();
5781 // The offset must also have the correct alignment.
5782 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5783 Result.Designator.setInvalid();
5786 ? CCEDiag(E->getArg(0),
5787 diag::note_constexpr_baa_insufficient_alignment) << 1
5788 : CCEDiag(E->getArg(0),
5789 diag::note_constexpr_baa_value_insufficient_alignment))
5790 << (int)OffsetResult.Offset.getQuantity()
5791 << (unsigned)Align.getQuantity();
5798 case Builtin::BIstrchr:
5799 case Builtin::BIwcschr:
5800 case Builtin::BImemchr:
5801 case Builtin::BIwmemchr:
5802 if (Info.getLangOpts().CPlusPlus11)
5803 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5804 << /*isConstexpr*/0 << /*isConstructor*/0
5805 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5807 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5809 case Builtin::BI__builtin_strchr:
5810 case Builtin::BI__builtin_wcschr:
5811 case Builtin::BI__builtin_memchr:
5812 case Builtin::BI__builtin_char_memchr:
5813 case Builtin::BI__builtin_wmemchr: {
5814 if (!Visit(E->getArg(0)))
5817 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5819 uint64_t MaxLength = uint64_t(-1);
5820 if (BuiltinOp != Builtin::BIstrchr &&
5821 BuiltinOp != Builtin::BIwcschr &&
5822 BuiltinOp != Builtin::BI__builtin_strchr &&
5823 BuiltinOp != Builtin::BI__builtin_wcschr) {
5825 if (!EvaluateInteger(E->getArg(2), N, Info))
5827 MaxLength = N.getExtValue();
5830 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5832 // Figure out what value we're actually looking for (after converting to
5833 // the corresponding unsigned type if necessary).
5834 uint64_t DesiredVal;
5835 bool StopAtNull = false;
5836 switch (BuiltinOp) {
5837 case Builtin::BIstrchr:
5838 case Builtin::BI__builtin_strchr:
5839 // strchr compares directly to the passed integer, and therefore
5840 // always fails if given an int that is not a char.
5841 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5842 E->getArg(1)->getType(),
5845 return ZeroInitialization(E);
5848 case Builtin::BImemchr:
5849 case Builtin::BI__builtin_memchr:
5850 case Builtin::BI__builtin_char_memchr:
5851 // memchr compares by converting both sides to unsigned char. That's also
5852 // correct for strchr if we get this far (to cope with plain char being
5853 // unsigned in the strchr case).
5854 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5857 case Builtin::BIwcschr:
5858 case Builtin::BI__builtin_wcschr:
5861 case Builtin::BIwmemchr:
5862 case Builtin::BI__builtin_wmemchr:
5863 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5864 DesiredVal = Desired.getZExtValue();
5868 for (; MaxLength; --MaxLength) {
5870 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5873 if (Char.getInt().getZExtValue() == DesiredVal)
5875 if (StopAtNull && !Char.getInt())
5877 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5880 // Not found: return nullptr.
5881 return ZeroInitialization(E);
5885 return visitNonBuiltinCallExpr(E);
5889 //===----------------------------------------------------------------------===//
5890 // Member Pointer Evaluation
5891 //===----------------------------------------------------------------------===//
5894 class MemberPointerExprEvaluator
5895 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5898 bool Success(const ValueDecl *D) {
5899 Result = MemberPtr(D);
5904 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5905 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5907 bool Success(const APValue &V, const Expr *E) {
5911 bool ZeroInitialization(const Expr *E) {
5912 return Success((const ValueDecl*)nullptr);
5915 bool VisitCastExpr(const CastExpr *E);
5916 bool VisitUnaryAddrOf(const UnaryOperator *E);
5918 } // end anonymous namespace
5920 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5922 assert(E->isRValue() && E->getType()->isMemberPointerType());
5923 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5926 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5927 switch (E->getCastKind()) {
5929 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5931 case CK_NullToMemberPointer:
5932 VisitIgnoredValue(E->getSubExpr());
5933 return ZeroInitialization(E);
5935 case CK_BaseToDerivedMemberPointer: {
5936 if (!Visit(E->getSubExpr()))
5938 if (E->path_empty())
5940 // Base-to-derived member pointer casts store the path in derived-to-base
5941 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5942 // the wrong end of the derived->base arc, so stagger the path by one class.
5943 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5944 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5945 PathI != PathE; ++PathI) {
5946 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5947 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5948 if (!Result.castToDerived(Derived))
5951 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5952 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5957 case CK_DerivedToBaseMemberPointer:
5958 if (!Visit(E->getSubExpr()))
5960 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5961 PathE = E->path_end(); PathI != PathE; ++PathI) {
5962 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5963 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5964 if (!Result.castToBase(Base))
5971 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5972 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5973 // member can be formed.
5974 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5977 //===----------------------------------------------------------------------===//
5978 // Record Evaluation
5979 //===----------------------------------------------------------------------===//
5982 class RecordExprEvaluator
5983 : public ExprEvaluatorBase<RecordExprEvaluator> {
5988 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5989 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5991 bool Success(const APValue &V, const Expr *E) {
5995 bool ZeroInitialization(const Expr *E) {
5996 return ZeroInitialization(E, E->getType());
5998 bool ZeroInitialization(const Expr *E, QualType T);
6000 bool VisitCallExpr(const CallExpr *E) {
6001 return handleCallExpr(E, Result, &This);
6003 bool VisitCastExpr(const CastExpr *E);
6004 bool VisitInitListExpr(const InitListExpr *E);
6005 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6006 return VisitCXXConstructExpr(E, E->getType());
6008 bool VisitLambdaExpr(const LambdaExpr *E);
6009 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6010 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6011 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6015 /// Perform zero-initialization on an object of non-union class type.
6016 /// C++11 [dcl.init]p5:
6017 /// To zero-initialize an object or reference of type T means:
6019 /// -- if T is a (possibly cv-qualified) non-union class type,
6020 /// each non-static data member and each base-class subobject is
6021 /// zero-initialized
6022 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6023 const RecordDecl *RD,
6024 const LValue &This, APValue &Result) {
6025 assert(!RD->isUnion() && "Expected non-union class type");
6026 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6027 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6028 std::distance(RD->field_begin(), RD->field_end()));
6030 if (RD->isInvalidDecl()) return false;
6031 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6035 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6036 End = CD->bases_end(); I != End; ++I, ++Index) {
6037 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6038 LValue Subobject = This;
6039 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6041 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6042 Result.getStructBase(Index)))
6047 for (const auto *I : RD->fields()) {
6048 // -- if T is a reference type, no initialization is performed.
6049 if (I->getType()->isReferenceType())
6052 LValue Subobject = This;
6053 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6056 ImplicitValueInitExpr VIE(I->getType());
6057 if (!EvaluateInPlace(
6058 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6065 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6066 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6067 if (RD->isInvalidDecl()) return false;
6068 if (RD->isUnion()) {
6069 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6070 // object's first non-static named data member is zero-initialized
6071 RecordDecl::field_iterator I = RD->field_begin();
6072 if (I == RD->field_end()) {
6073 Result = APValue((const FieldDecl*)nullptr);
6077 LValue Subobject = This;
6078 if (!HandleLValueMember(Info, E, Subobject, *I))
6080 Result = APValue(*I);
6081 ImplicitValueInitExpr VIE(I->getType());
6082 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6085 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6086 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6090 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6093 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6094 switch (E->getCastKind()) {
6096 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6098 case CK_ConstructorConversion:
6099 return Visit(E->getSubExpr());
6101 case CK_DerivedToBase:
6102 case CK_UncheckedDerivedToBase: {
6103 APValue DerivedObject;
6104 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6106 if (!DerivedObject.isStruct())
6107 return Error(E->getSubExpr());
6109 // Derived-to-base rvalue conversion: just slice off the derived part.
6110 APValue *Value = &DerivedObject;
6111 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6112 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6113 PathE = E->path_end(); PathI != PathE; ++PathI) {
6114 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6115 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6116 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6125 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6126 if (E->isTransparent())
6127 return Visit(E->getInit(0));
6129 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6130 if (RD->isInvalidDecl()) return false;
6131 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6133 if (RD->isUnion()) {
6134 const FieldDecl *Field = E->getInitializedFieldInUnion();
6135 Result = APValue(Field);
6139 // If the initializer list for a union does not contain any elements, the
6140 // first element of the union is value-initialized.
6141 // FIXME: The element should be initialized from an initializer list.
6142 // Is this difference ever observable for initializer lists which
6144 ImplicitValueInitExpr VIE(Field->getType());
6145 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6147 LValue Subobject = This;
6148 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6151 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6152 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6153 isa<CXXDefaultInitExpr>(InitExpr));
6155 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6158 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6159 if (Result.isUninit())
6160 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6161 std::distance(RD->field_begin(), RD->field_end()));
6162 unsigned ElementNo = 0;
6163 bool Success = true;
6165 // Initialize base classes.
6167 for (const auto &Base : CXXRD->bases()) {
6168 assert(ElementNo < E->getNumInits() && "missing init for base class");
6169 const Expr *Init = E->getInit(ElementNo);
6171 LValue Subobject = This;
6172 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6175 APValue &FieldVal = Result.getStructBase(ElementNo);
6176 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6177 if (!Info.noteFailure())
6185 // Initialize members.
6186 for (const auto *Field : RD->fields()) {
6187 // Anonymous bit-fields are not considered members of the class for
6188 // purposes of aggregate initialization.
6189 if (Field->isUnnamedBitfield())
6192 LValue Subobject = This;
6194 bool HaveInit = ElementNo < E->getNumInits();
6196 // FIXME: Diagnostics here should point to the end of the initializer
6197 // list, not the start.
6198 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6199 Subobject, Field, &Layout))
6202 // Perform an implicit value-initialization for members beyond the end of
6203 // the initializer list.
6204 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6205 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6207 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6208 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6209 isa<CXXDefaultInitExpr>(Init));
6211 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6212 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6213 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6214 FieldVal, Field))) {
6215 if (!Info.noteFailure())
6224 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6226 // Note that E's type is not necessarily the type of our class here; we might
6227 // be initializing an array element instead.
6228 const CXXConstructorDecl *FD = E->getConstructor();
6229 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6231 bool ZeroInit = E->requiresZeroInitialization();
6232 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6233 // If we've already performed zero-initialization, we're already done.
6234 if (!Result.isUninit())
6237 // We can get here in two different ways:
6238 // 1) We're performing value-initialization, and should zero-initialize
6240 // 2) We're performing default-initialization of an object with a trivial
6241 // constexpr default constructor, in which case we should start the
6242 // lifetimes of all the base subobjects (there can be no data member
6243 // subobjects in this case) per [basic.life]p1.
6244 // Either way, ZeroInitialization is appropriate.
6245 return ZeroInitialization(E, T);
6248 const FunctionDecl *Definition = nullptr;
6249 auto Body = FD->getBody(Definition);
6251 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6254 // Avoid materializing a temporary for an elidable copy/move constructor.
6255 if (E->isElidable() && !ZeroInit)
6256 if (const MaterializeTemporaryExpr *ME
6257 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6258 return Visit(ME->GetTemporaryExpr());
6260 if (ZeroInit && !ZeroInitialization(E, T))
6263 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6264 return HandleConstructorCall(E, This, Args,
6265 cast<CXXConstructorDecl>(Definition), Info,
6269 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6270 const CXXInheritedCtorInitExpr *E) {
6271 if (!Info.CurrentCall) {
6272 assert(Info.checkingPotentialConstantExpression());
6276 const CXXConstructorDecl *FD = E->getConstructor();
6277 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6280 const FunctionDecl *Definition = nullptr;
6281 auto Body = FD->getBody(Definition);
6283 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6286 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6287 cast<CXXConstructorDecl>(Definition), Info,
6291 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6292 const CXXStdInitializerListExpr *E) {
6293 const ConstantArrayType *ArrayType =
6294 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6297 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6300 // Get a pointer to the first element of the array.
6301 Array.addArray(Info, E, ArrayType);
6303 // FIXME: Perform the checks on the field types in SemaInit.
6304 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6305 RecordDecl::field_iterator Field = Record->field_begin();
6306 if (Field == Record->field_end())
6310 if (!Field->getType()->isPointerType() ||
6311 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6312 ArrayType->getElementType()))
6315 // FIXME: What if the initializer_list type has base classes, etc?
6316 Result = APValue(APValue::UninitStruct(), 0, 2);
6317 Array.moveInto(Result.getStructField(0));
6319 if (++Field == Record->field_end())
6322 if (Field->getType()->isPointerType() &&
6323 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6324 ArrayType->getElementType())) {
6326 if (!HandleLValueArrayAdjustment(Info, E, Array,
6327 ArrayType->getElementType(),
6328 ArrayType->getSize().getZExtValue()))
6330 Array.moveInto(Result.getStructField(1));
6331 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6333 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6337 if (++Field != Record->field_end())
6343 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6344 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6345 if (ClosureClass->isInvalidDecl()) return false;
6347 if (Info.checkingPotentialConstantExpression()) return true;
6349 const size_t NumFields =
6350 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6352 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6353 E->capture_init_end()) &&
6354 "The number of lambda capture initializers should equal the number of "
6355 "fields within the closure type");
6357 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6358 // Iterate through all the lambda's closure object's fields and initialize
6360 auto *CaptureInitIt = E->capture_init_begin();
6361 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6362 bool Success = true;
6363 for (const auto *Field : ClosureClass->fields()) {
6364 assert(CaptureInitIt != E->capture_init_end());
6365 // Get the initializer for this field
6366 Expr *const CurFieldInit = *CaptureInitIt++;
6368 // If there is no initializer, either this is a VLA or an error has
6373 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6374 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6375 if (!Info.keepEvaluatingAfterFailure())
6384 static bool EvaluateRecord(const Expr *E, const LValue &This,
6385 APValue &Result, EvalInfo &Info) {
6386 assert(E->isRValue() && E->getType()->isRecordType() &&
6387 "can't evaluate expression as a record rvalue");
6388 return RecordExprEvaluator(Info, This, Result).Visit(E);
6391 //===----------------------------------------------------------------------===//
6392 // Temporary Evaluation
6394 // Temporaries are represented in the AST as rvalues, but generally behave like
6395 // lvalues. The full-object of which the temporary is a subobject is implicitly
6396 // materialized so that a reference can bind to it.
6397 //===----------------------------------------------------------------------===//
6399 class TemporaryExprEvaluator
6400 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6402 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6403 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6405 /// Visit an expression which constructs the value of this temporary.
6406 bool VisitConstructExpr(const Expr *E) {
6407 Result.set(E, Info.CurrentCall->Index);
6408 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6412 bool VisitCastExpr(const CastExpr *E) {
6413 switch (E->getCastKind()) {
6415 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6417 case CK_ConstructorConversion:
6418 return VisitConstructExpr(E->getSubExpr());
6421 bool VisitInitListExpr(const InitListExpr *E) {
6422 return VisitConstructExpr(E);
6424 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6425 return VisitConstructExpr(E);
6427 bool VisitCallExpr(const CallExpr *E) {
6428 return VisitConstructExpr(E);
6430 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6431 return VisitConstructExpr(E);
6433 bool VisitLambdaExpr(const LambdaExpr *E) {
6434 return VisitConstructExpr(E);
6437 } // end anonymous namespace
6439 /// Evaluate an expression of record type as a temporary.
6440 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6441 assert(E->isRValue() && E->getType()->isRecordType());
6442 return TemporaryExprEvaluator(Info, Result).Visit(E);
6445 //===----------------------------------------------------------------------===//
6446 // Vector Evaluation
6447 //===----------------------------------------------------------------------===//
6450 class VectorExprEvaluator
6451 : public ExprEvaluatorBase<VectorExprEvaluator> {
6455 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6456 : ExprEvaluatorBaseTy(info), Result(Result) {}
6458 bool Success(ArrayRef<APValue> V, const Expr *E) {
6459 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6460 // FIXME: remove this APValue copy.
6461 Result = APValue(V.data(), V.size());
6464 bool Success(const APValue &V, const Expr *E) {
6465 assert(V.isVector());
6469 bool ZeroInitialization(const Expr *E);
6471 bool VisitUnaryReal(const UnaryOperator *E)
6472 { return Visit(E->getSubExpr()); }
6473 bool VisitCastExpr(const CastExpr* E);
6474 bool VisitInitListExpr(const InitListExpr *E);
6475 bool VisitUnaryImag(const UnaryOperator *E);
6476 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6477 // binary comparisons, binary and/or/xor,
6478 // shufflevector, ExtVectorElementExpr
6480 } // end anonymous namespace
6482 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6483 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6484 return VectorExprEvaluator(Info, Result).Visit(E);
6487 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6488 const VectorType *VTy = E->getType()->castAs<VectorType>();
6489 unsigned NElts = VTy->getNumElements();
6491 const Expr *SE = E->getSubExpr();
6492 QualType SETy = SE->getType();
6494 switch (E->getCastKind()) {
6495 case CK_VectorSplat: {
6496 APValue Val = APValue();
6497 if (SETy->isIntegerType()) {
6499 if (!EvaluateInteger(SE, IntResult, Info))
6501 Val = APValue(std::move(IntResult));
6502 } else if (SETy->isRealFloatingType()) {
6503 APFloat FloatResult(0.0);
6504 if (!EvaluateFloat(SE, FloatResult, Info))
6506 Val = APValue(std::move(FloatResult));
6511 // Splat and create vector APValue.
6512 SmallVector<APValue, 4> Elts(NElts, Val);
6513 return Success(Elts, E);
6516 // Evaluate the operand into an APInt we can extract from.
6517 llvm::APInt SValInt;
6518 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6520 // Extract the elements
6521 QualType EltTy = VTy->getElementType();
6522 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6523 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6524 SmallVector<APValue, 4> Elts;
6525 if (EltTy->isRealFloatingType()) {
6526 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6527 unsigned FloatEltSize = EltSize;
6528 if (&Sem == &APFloat::x87DoubleExtended())
6530 for (unsigned i = 0; i < NElts; i++) {
6533 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6535 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6536 Elts.push_back(APValue(APFloat(Sem, Elt)));
6538 } else if (EltTy->isIntegerType()) {
6539 for (unsigned i = 0; i < NElts; i++) {
6542 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6544 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6545 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6550 return Success(Elts, E);
6553 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6558 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6559 const VectorType *VT = E->getType()->castAs<VectorType>();
6560 unsigned NumInits = E->getNumInits();
6561 unsigned NumElements = VT->getNumElements();
6563 QualType EltTy = VT->getElementType();
6564 SmallVector<APValue, 4> Elements;
6566 // The number of initializers can be less than the number of
6567 // vector elements. For OpenCL, this can be due to nested vector
6568 // initialization. For GCC compatibility, missing trailing elements
6569 // should be initialized with zeroes.
6570 unsigned CountInits = 0, CountElts = 0;
6571 while (CountElts < NumElements) {
6572 // Handle nested vector initialization.
6573 if (CountInits < NumInits
6574 && E->getInit(CountInits)->getType()->isVectorType()) {
6576 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6578 unsigned vlen = v.getVectorLength();
6579 for (unsigned j = 0; j < vlen; j++)
6580 Elements.push_back(v.getVectorElt(j));
6582 } else if (EltTy->isIntegerType()) {
6583 llvm::APSInt sInt(32);
6584 if (CountInits < NumInits) {
6585 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6587 } else // trailing integer zero.
6588 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6589 Elements.push_back(APValue(sInt));
6592 llvm::APFloat f(0.0);
6593 if (CountInits < NumInits) {
6594 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6596 } else // trailing float zero.
6597 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6598 Elements.push_back(APValue(f));
6603 return Success(Elements, E);
6607 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6608 const VectorType *VT = E->getType()->getAs<VectorType>();
6609 QualType EltTy = VT->getElementType();
6610 APValue ZeroElement;
6611 if (EltTy->isIntegerType())
6612 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6615 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6617 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6618 return Success(Elements, E);
6621 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6622 VisitIgnoredValue(E->getSubExpr());
6623 return ZeroInitialization(E);
6626 //===----------------------------------------------------------------------===//
6628 //===----------------------------------------------------------------------===//
6631 class ArrayExprEvaluator
6632 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6637 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6638 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6640 bool Success(const APValue &V, const Expr *E) {
6641 assert((V.isArray() || V.isLValue()) &&
6642 "expected array or string literal");
6647 bool ZeroInitialization(const Expr *E) {
6648 const ConstantArrayType *CAT =
6649 Info.Ctx.getAsConstantArrayType(E->getType());
6653 Result = APValue(APValue::UninitArray(), 0,
6654 CAT->getSize().getZExtValue());
6655 if (!Result.hasArrayFiller()) return true;
6657 // Zero-initialize all elements.
6658 LValue Subobject = This;
6659 Subobject.addArray(Info, E, CAT);
6660 ImplicitValueInitExpr VIE(CAT->getElementType());
6661 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6664 bool VisitCallExpr(const CallExpr *E) {
6665 return handleCallExpr(E, Result, &This);
6667 bool VisitInitListExpr(const InitListExpr *E);
6668 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6669 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6670 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6671 const LValue &Subobject,
6672 APValue *Value, QualType Type);
6674 } // end anonymous namespace
6676 static bool EvaluateArray(const Expr *E, const LValue &This,
6677 APValue &Result, EvalInfo &Info) {
6678 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6679 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6682 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6683 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6687 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6688 // an appropriately-typed string literal enclosed in braces.
6689 if (E->isStringLiteralInit()) {
6691 if (!EvaluateLValue(E->getInit(0), LV, Info))
6695 return Success(Val, E);
6698 bool Success = true;
6700 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6701 "zero-initialized array shouldn't have any initialized elts");
6703 if (Result.isArray() && Result.hasArrayFiller())
6704 Filler = Result.getArrayFiller();
6706 unsigned NumEltsToInit = E->getNumInits();
6707 unsigned NumElts = CAT->getSize().getZExtValue();
6708 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6710 // If the initializer might depend on the array index, run it for each
6711 // array element. For now, just whitelist non-class value-initialization.
6712 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6713 NumEltsToInit = NumElts;
6715 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6717 // If the array was previously zero-initialized, preserve the
6718 // zero-initialized values.
6719 if (!Filler.isUninit()) {
6720 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6721 Result.getArrayInitializedElt(I) = Filler;
6722 if (Result.hasArrayFiller())
6723 Result.getArrayFiller() = Filler;
6726 LValue Subobject = This;
6727 Subobject.addArray(Info, E, CAT);
6728 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6730 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6731 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6732 Info, Subobject, Init) ||
6733 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6734 CAT->getElementType(), 1)) {
6735 if (!Info.noteFailure())
6741 if (!Result.hasArrayFiller())
6744 // If we get here, we have a trivial filler, which we can just evaluate
6745 // once and splat over the rest of the array elements.
6746 assert(FillerExpr && "no array filler for incomplete init list");
6747 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6748 FillerExpr) && Success;
6751 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6752 if (E->getCommonExpr() &&
6753 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6754 Info, E->getCommonExpr()->getSourceExpr()))
6757 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6759 uint64_t Elements = CAT->getSize().getZExtValue();
6760 Result = APValue(APValue::UninitArray(), Elements, Elements);
6762 LValue Subobject = This;
6763 Subobject.addArray(Info, E, CAT);
6765 bool Success = true;
6766 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6767 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6768 Info, Subobject, E->getSubExpr()) ||
6769 !HandleLValueArrayAdjustment(Info, E, Subobject,
6770 CAT->getElementType(), 1)) {
6771 if (!Info.noteFailure())
6780 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6781 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6784 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6785 const LValue &Subobject,
6788 bool HadZeroInit = !Value->isUninit();
6790 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6791 unsigned N = CAT->getSize().getZExtValue();
6793 // Preserve the array filler if we had prior zero-initialization.
6795 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6798 *Value = APValue(APValue::UninitArray(), N, N);
6801 for (unsigned I = 0; I != N; ++I)
6802 Value->getArrayInitializedElt(I) = Filler;
6804 // Initialize the elements.
6805 LValue ArrayElt = Subobject;
6806 ArrayElt.addArray(Info, E, CAT);
6807 for (unsigned I = 0; I != N; ++I)
6808 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6809 CAT->getElementType()) ||
6810 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6811 CAT->getElementType(), 1))
6817 if (!Type->isRecordType())
6820 return RecordExprEvaluator(Info, Subobject, *Value)
6821 .VisitCXXConstructExpr(E, Type);
6824 //===----------------------------------------------------------------------===//
6825 // Integer Evaluation
6827 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6828 // types and back in constant folding. Integer values are thus represented
6829 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6830 //===----------------------------------------------------------------------===//
6833 class IntExprEvaluator
6834 : public ExprEvaluatorBase<IntExprEvaluator> {
6837 IntExprEvaluator(EvalInfo &info, APValue &result)
6838 : ExprEvaluatorBaseTy(info), Result(result) {}
6840 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6841 assert(E->getType()->isIntegralOrEnumerationType() &&
6842 "Invalid evaluation result.");
6843 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6844 "Invalid evaluation result.");
6845 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6846 "Invalid evaluation result.");
6847 Result = APValue(SI);
6850 bool Success(const llvm::APSInt &SI, const Expr *E) {
6851 return Success(SI, E, Result);
6854 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6855 assert(E->getType()->isIntegralOrEnumerationType() &&
6856 "Invalid evaluation result.");
6857 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6858 "Invalid evaluation result.");
6859 Result = APValue(APSInt(I));
6860 Result.getInt().setIsUnsigned(
6861 E->getType()->isUnsignedIntegerOrEnumerationType());
6864 bool Success(const llvm::APInt &I, const Expr *E) {
6865 return Success(I, E, Result);
6868 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6869 assert(E->getType()->isIntegralOrEnumerationType() &&
6870 "Invalid evaluation result.");
6871 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6874 bool Success(uint64_t Value, const Expr *E) {
6875 return Success(Value, E, Result);
6878 bool Success(CharUnits Size, const Expr *E) {
6879 return Success(Size.getQuantity(), E);
6882 bool Success(const APValue &V, const Expr *E) {
6883 if (V.isLValue() || V.isAddrLabelDiff()) {
6887 return Success(V.getInt(), E);
6890 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6892 //===--------------------------------------------------------------------===//
6894 //===--------------------------------------------------------------------===//
6896 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6897 return Success(E->getValue(), E);
6899 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6900 return Success(E->getValue(), E);
6903 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6904 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6905 if (CheckReferencedDecl(E, E->getDecl()))
6908 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6910 bool VisitMemberExpr(const MemberExpr *E) {
6911 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6912 VisitIgnoredBaseExpression(E->getBase());
6916 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6919 bool VisitCallExpr(const CallExpr *E);
6920 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6921 bool VisitBinaryOperator(const BinaryOperator *E);
6922 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6923 bool VisitUnaryOperator(const UnaryOperator *E);
6925 bool VisitCastExpr(const CastExpr* E);
6926 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6928 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6929 return Success(E->getValue(), E);
6932 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6933 return Success(E->getValue(), E);
6936 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6937 if (Info.ArrayInitIndex == uint64_t(-1)) {
6938 // We were asked to evaluate this subexpression independent of the
6939 // enclosing ArrayInitLoopExpr. We can't do that.
6943 return Success(Info.ArrayInitIndex, E);
6946 // Note, GNU defines __null as an integer, not a pointer.
6947 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6948 return ZeroInitialization(E);
6951 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6952 return Success(E->getValue(), E);
6955 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6956 return Success(E->getValue(), E);
6959 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6960 return Success(E->getValue(), E);
6963 bool VisitUnaryReal(const UnaryOperator *E);
6964 bool VisitUnaryImag(const UnaryOperator *E);
6966 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6967 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6969 // FIXME: Missing: array subscript of vector, member of vector
6971 } // end anonymous namespace
6973 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6974 /// produce either the integer value or a pointer.
6976 /// GCC has a heinous extension which folds casts between pointer types and
6977 /// pointer-sized integral types. We support this by allowing the evaluation of
6978 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6979 /// Some simple arithmetic on such values is supported (they are treated much
6981 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6983 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6984 return IntExprEvaluator(Info, Result).Visit(E);
6987 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6989 if (!EvaluateIntegerOrLValue(E, Val, Info))
6992 // FIXME: It would be better to produce the diagnostic for casting
6993 // a pointer to an integer.
6994 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6997 Result = Val.getInt();
7001 /// Check whether the given declaration can be directly converted to an integral
7002 /// rvalue. If not, no diagnostic is produced; there are other things we can
7004 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7005 // Enums are integer constant exprs.
7006 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7007 // Check for signedness/width mismatches between E type and ECD value.
7008 bool SameSign = (ECD->getInitVal().isSigned()
7009 == E->getType()->isSignedIntegerOrEnumerationType());
7010 bool SameWidth = (ECD->getInitVal().getBitWidth()
7011 == Info.Ctx.getIntWidth(E->getType()));
7012 if (SameSign && SameWidth)
7013 return Success(ECD->getInitVal(), E);
7015 // Get rid of mismatch (otherwise Success assertions will fail)
7016 // by computing a new value matching the type of E.
7017 llvm::APSInt Val = ECD->getInitVal();
7019 Val.setIsSigned(!ECD->getInitVal().isSigned());
7021 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7022 return Success(Val, E);
7028 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7030 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7031 const LangOptions &LangOpts) {
7032 // The following enum mimics the values returned by GCC.
7033 // FIXME: Does GCC differ between lvalue and rvalue references here?
7034 enum gcc_type_class {
7036 void_type_class, integer_type_class, char_type_class,
7037 enumeral_type_class, boolean_type_class,
7038 pointer_type_class, reference_type_class, offset_type_class,
7039 real_type_class, complex_type_class,
7040 function_type_class, method_type_class,
7041 record_type_class, union_type_class,
7042 array_type_class, string_type_class,
7046 // If no argument was supplied, default to "no_type_class". This isn't
7047 // ideal, however it is what gcc does.
7048 if (E->getNumArgs() == 0)
7049 return no_type_class;
7051 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7052 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7054 switch (CanTy->getTypeClass()) {
7055 #define TYPE(ID, BASE)
7056 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7057 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7058 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7059 #include "clang/AST/TypeNodes.def"
7060 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7063 switch (BT->getKind()) {
7064 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7065 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7066 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7067 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7068 #include "clang/AST/BuiltinTypes.def"
7069 case BuiltinType::Void:
7070 return void_type_class;
7072 case BuiltinType::Bool:
7073 return boolean_type_class;
7075 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7076 case BuiltinType::UChar:
7077 case BuiltinType::UShort:
7078 case BuiltinType::UInt:
7079 case BuiltinType::ULong:
7080 case BuiltinType::ULongLong:
7081 case BuiltinType::UInt128:
7082 return integer_type_class;
7084 case BuiltinType::NullPtr:
7085 return pointer_type_class;
7087 case BuiltinType::WChar_U:
7088 case BuiltinType::Char16:
7089 case BuiltinType::Char32:
7090 case BuiltinType::ObjCId:
7091 case BuiltinType::ObjCClass:
7092 case BuiltinType::ObjCSel:
7093 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7094 case BuiltinType::Id:
7095 #include "clang/Basic/OpenCLImageTypes.def"
7096 case BuiltinType::OCLSampler:
7097 case BuiltinType::OCLEvent:
7098 case BuiltinType::OCLClkEvent:
7099 case BuiltinType::OCLQueue:
7100 case BuiltinType::OCLReserveID:
7101 case BuiltinType::Dependent:
7102 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7106 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7110 return pointer_type_class;
7113 case Type::MemberPointer:
7114 if (CanTy->isMemberDataPointerType())
7115 return offset_type_class;
7117 // We expect member pointers to be either data or function pointers,
7119 assert(CanTy->isMemberFunctionPointerType());
7120 return method_type_class;
7124 return complex_type_class;
7126 case Type::FunctionNoProto:
7127 case Type::FunctionProto:
7128 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7131 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7132 switch (RT->getDecl()->getTagKind()) {
7133 case TagTypeKind::TTK_Struct:
7134 case TagTypeKind::TTK_Class:
7135 case TagTypeKind::TTK_Interface:
7136 return record_type_class;
7138 case TagTypeKind::TTK_Enum:
7139 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7141 case TagTypeKind::TTK_Union:
7142 return union_type_class;
7145 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7147 case Type::ConstantArray:
7148 case Type::VariableArray:
7149 case Type::IncompleteArray:
7150 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7152 case Type::BlockPointer:
7153 case Type::LValueReference:
7154 case Type::RValueReference:
7156 case Type::ExtVector:
7158 case Type::DeducedTemplateSpecialization:
7159 case Type::ObjCObject:
7160 case Type::ObjCInterface:
7161 case Type::ObjCObjectPointer:
7164 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7167 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7170 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7171 /// __builtin_constant_p when applied to the given lvalue.
7173 /// An lvalue is only "constant" if it is a pointer or reference to the first
7174 /// character of a string literal.
7175 template<typename LValue>
7176 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7177 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7178 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7181 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7182 /// GCC as we can manage.
7183 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7184 QualType ArgType = Arg->getType();
7186 // __builtin_constant_p always has one operand. The rules which gcc follows
7187 // are not precisely documented, but are as follows:
7189 // - If the operand is of integral, floating, complex or enumeration type,
7190 // and can be folded to a known value of that type, it returns 1.
7191 // - If the operand and can be folded to a pointer to the first character
7192 // of a string literal (or such a pointer cast to an integral type), it
7195 // Otherwise, it returns 0.
7197 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7198 // its support for this does not currently work.
7199 if (ArgType->isIntegralOrEnumerationType()) {
7200 Expr::EvalResult Result;
7201 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7204 APValue &V = Result.Val;
7205 if (V.getKind() == APValue::Int)
7207 if (V.getKind() == APValue::LValue)
7208 return EvaluateBuiltinConstantPForLValue(V);
7209 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7210 return Arg->isEvaluatable(Ctx);
7211 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7213 Expr::EvalStatus Status;
7214 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7215 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7216 : EvaluatePointer(Arg, LV, Info)) &&
7217 !Status.HasSideEffects)
7218 return EvaluateBuiltinConstantPForLValue(LV);
7221 // Anything else isn't considered to be sufficiently constant.
7225 /// Retrieves the "underlying object type" of the given expression,
7226 /// as used by __builtin_object_size.
7227 static QualType getObjectType(APValue::LValueBase B) {
7228 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7229 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7230 return VD->getType();
7231 } else if (const Expr *E = B.get<const Expr*>()) {
7232 if (isa<CompoundLiteralExpr>(E))
7233 return E->getType();
7239 /// A more selective version of E->IgnoreParenCasts for
7240 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7241 /// to change the type of E.
7242 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7244 /// Always returns an RValue with a pointer representation.
7245 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7246 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7248 auto *NoParens = E->IgnoreParens();
7249 auto *Cast = dyn_cast<CastExpr>(NoParens);
7250 if (Cast == nullptr)
7253 // We only conservatively allow a few kinds of casts, because this code is
7254 // inherently a simple solution that seeks to support the common case.
7255 auto CastKind = Cast->getCastKind();
7256 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7257 CastKind != CK_AddressSpaceConversion)
7260 auto *SubExpr = Cast->getSubExpr();
7261 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7263 return ignorePointerCastsAndParens(SubExpr);
7266 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7267 /// record layout. e.g.
7268 /// struct { struct { int a, b; } fst, snd; } obj;
7274 /// obj.snd.b // yes
7276 /// Please note: this function is specialized for how __builtin_object_size
7277 /// views "objects".
7279 /// If this encounters an invalid RecordDecl, it will always return true.
7280 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7281 assert(!LVal.Designator.Invalid);
7283 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7284 const RecordDecl *Parent = FD->getParent();
7285 Invalid = Parent->isInvalidDecl();
7286 if (Invalid || Parent->isUnion())
7288 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7289 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7292 auto &Base = LVal.getLValueBase();
7293 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7294 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7296 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7298 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7299 for (auto *FD : IFD->chain()) {
7301 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7308 QualType BaseType = getType(Base);
7309 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7310 assert(isBaseAnAllocSizeCall(Base) &&
7311 "Unsized array in non-alloc_size call?");
7312 // If this is an alloc_size base, we should ignore the initial array index
7314 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7317 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7318 const auto &Entry = LVal.Designator.Entries[I];
7319 if (BaseType->isArrayType()) {
7320 // Because __builtin_object_size treats arrays as objects, we can ignore
7321 // the index iff this is the last array in the Designator.
7324 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7325 uint64_t Index = Entry.ArrayIndex;
7326 if (Index + 1 != CAT->getSize())
7328 BaseType = CAT->getElementType();
7329 } else if (BaseType->isAnyComplexType()) {
7330 const auto *CT = BaseType->castAs<ComplexType>();
7331 uint64_t Index = Entry.ArrayIndex;
7334 BaseType = CT->getElementType();
7335 } else if (auto *FD = getAsField(Entry)) {
7337 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7339 BaseType = FD->getType();
7341 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7348 /// Tests to see if the LValue has a user-specified designator (that isn't
7349 /// necessarily valid). Note that this always returns 'true' if the LValue has
7350 /// an unsized array as its first designator entry, because there's currently no
7351 /// way to tell if the user typed *foo or foo[0].
7352 static bool refersToCompleteObject(const LValue &LVal) {
7353 if (LVal.Designator.Invalid)
7356 if (!LVal.Designator.Entries.empty())
7357 return LVal.Designator.isMostDerivedAnUnsizedArray();
7359 if (!LVal.InvalidBase)
7362 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7364 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7365 return !E || !isa<MemberExpr>(E);
7368 /// Attempts to detect a user writing into a piece of memory that's impossible
7369 /// to figure out the size of by just using types.
7370 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7371 const SubobjectDesignator &Designator = LVal.Designator;
7373 // - Users can only write off of the end when we have an invalid base. Invalid
7374 // bases imply we don't know where the memory came from.
7375 // - We used to be a bit more aggressive here; we'd only be conservative if
7376 // the array at the end was flexible, or if it had 0 or 1 elements. This
7377 // broke some common standard library extensions (PR30346), but was
7378 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7379 // with some sort of whitelist. OTOH, it seems that GCC is always
7380 // conservative with the last element in structs (if it's an array), so our
7381 // current behavior is more compatible than a whitelisting approach would
7383 return LVal.InvalidBase &&
7384 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7385 Designator.MostDerivedIsArrayElement &&
7386 isDesignatorAtObjectEnd(Ctx, LVal);
7389 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7390 /// Fails if the conversion would cause loss of precision.
7391 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7392 CharUnits &Result) {
7393 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7394 if (Int.ugt(CharUnitsMax))
7396 Result = CharUnits::fromQuantity(Int.getZExtValue());
7400 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7401 /// determine how many bytes exist from the beginning of the object to either
7402 /// the end of the current subobject, or the end of the object itself, depending
7403 /// on what the LValue looks like + the value of Type.
7405 /// If this returns false, the value of Result is undefined.
7406 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7407 unsigned Type, const LValue &LVal,
7408 CharUnits &EndOffset) {
7409 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7411 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7412 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7414 return HandleSizeof(Info, ExprLoc, Ty, Result);
7417 // We want to evaluate the size of the entire object. This is a valid fallback
7418 // for when Type=1 and the designator is invalid, because we're asked for an
7420 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7421 // Type=3 wants a lower bound, so we can't fall back to this.
7422 if (Type == 3 && !DetermineForCompleteObject)
7425 llvm::APInt APEndOffset;
7426 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7427 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7428 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7430 if (LVal.InvalidBase)
7433 QualType BaseTy = getObjectType(LVal.getLValueBase());
7434 return CheckedHandleSizeof(BaseTy, EndOffset);
7437 // We want to evaluate the size of a subobject.
7438 const SubobjectDesignator &Designator = LVal.Designator;
7440 // The following is a moderately common idiom in C:
7442 // struct Foo { int a; char c[1]; };
7443 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7444 // strcpy(&F->c[0], Bar);
7446 // In order to not break too much legacy code, we need to support it.
7447 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7448 // If we can resolve this to an alloc_size call, we can hand that back,
7449 // because we know for certain how many bytes there are to write to.
7450 llvm::APInt APEndOffset;
7451 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7452 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7453 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7455 // If we cannot determine the size of the initial allocation, then we can't
7456 // given an accurate upper-bound. However, we are still able to give
7457 // conservative lower-bounds for Type=3.
7462 CharUnits BytesPerElem;
7463 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7466 // According to the GCC documentation, we want the size of the subobject
7467 // denoted by the pointer. But that's not quite right -- what we actually
7468 // want is the size of the immediately-enclosing array, if there is one.
7469 int64_t ElemsRemaining;
7470 if (Designator.MostDerivedIsArrayElement &&
7471 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7472 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7473 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7474 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7476 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7479 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7483 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7484 /// returns true and stores the result in @p Size.
7486 /// If @p WasError is non-null, this will report whether the failure to evaluate
7487 /// is to be treated as an Error in IntExprEvaluator.
7488 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7489 EvalInfo &Info, uint64_t &Size) {
7490 // Determine the denoted object.
7493 // The operand of __builtin_object_size is never evaluated for side-effects.
7494 // If there are any, but we can determine the pointed-to object anyway, then
7495 // ignore the side-effects.
7496 SpeculativeEvaluationRAII SpeculativeEval(Info);
7497 FoldOffsetRAII Fold(Info);
7499 if (E->isGLValue()) {
7500 // It's possible for us to be given GLValues if we're called via
7501 // Expr::tryEvaluateObjectSize.
7503 if (!EvaluateAsRValue(Info, E, RVal))
7505 LVal.setFrom(Info.Ctx, RVal);
7506 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7507 /*InvalidBaseOK=*/true))
7511 // If we point to before the start of the object, there are no accessible
7513 if (LVal.getLValueOffset().isNegative()) {
7518 CharUnits EndOffset;
7519 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7522 // If we've fallen outside of the end offset, just pretend there's nothing to
7523 // write to/read from.
7524 if (EndOffset <= LVal.getLValueOffset())
7527 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7531 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7532 if (unsigned BuiltinOp = E->getBuiltinCallee())
7533 return VisitBuiltinCallExpr(E, BuiltinOp);
7535 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7538 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7539 unsigned BuiltinOp) {
7540 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7542 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7544 case Builtin::BI__builtin_object_size: {
7545 // The type was checked when we built the expression.
7547 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7548 assert(Type <= 3 && "unexpected type");
7551 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7552 return Success(Size, E);
7554 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7555 return Success((Type & 2) ? 0 : -1, E);
7557 // Expression had no side effects, but we couldn't statically determine the
7558 // size of the referenced object.
7559 switch (Info.EvalMode) {
7560 case EvalInfo::EM_ConstantExpression:
7561 case EvalInfo::EM_PotentialConstantExpression:
7562 case EvalInfo::EM_ConstantFold:
7563 case EvalInfo::EM_EvaluateForOverflow:
7564 case EvalInfo::EM_IgnoreSideEffects:
7565 case EvalInfo::EM_OffsetFold:
7566 // Leave it to IR generation.
7568 case EvalInfo::EM_ConstantExpressionUnevaluated:
7569 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7570 // Reduce it to a constant now.
7571 return Success((Type & 2) ? 0 : -1, E);
7574 llvm_unreachable("unexpected EvalMode");
7577 case Builtin::BI__builtin_bswap16:
7578 case Builtin::BI__builtin_bswap32:
7579 case Builtin::BI__builtin_bswap64: {
7581 if (!EvaluateInteger(E->getArg(0), Val, Info))
7584 return Success(Val.byteSwap(), E);
7587 case Builtin::BI__builtin_classify_type:
7588 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7590 // FIXME: BI__builtin_clrsb
7591 // FIXME: BI__builtin_clrsbl
7592 // FIXME: BI__builtin_clrsbll
7594 case Builtin::BI__builtin_clz:
7595 case Builtin::BI__builtin_clzl:
7596 case Builtin::BI__builtin_clzll:
7597 case Builtin::BI__builtin_clzs: {
7599 if (!EvaluateInteger(E->getArg(0), Val, Info))
7604 return Success(Val.countLeadingZeros(), E);
7607 case Builtin::BI__builtin_constant_p:
7608 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7610 case Builtin::BI__builtin_ctz:
7611 case Builtin::BI__builtin_ctzl:
7612 case Builtin::BI__builtin_ctzll:
7613 case Builtin::BI__builtin_ctzs: {
7615 if (!EvaluateInteger(E->getArg(0), Val, Info))
7620 return Success(Val.countTrailingZeros(), E);
7623 case Builtin::BI__builtin_eh_return_data_regno: {
7624 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7625 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7626 return Success(Operand, E);
7629 case Builtin::BI__builtin_expect:
7630 return Visit(E->getArg(0));
7632 case Builtin::BI__builtin_ffs:
7633 case Builtin::BI__builtin_ffsl:
7634 case Builtin::BI__builtin_ffsll: {
7636 if (!EvaluateInteger(E->getArg(0), Val, Info))
7639 unsigned N = Val.countTrailingZeros();
7640 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7643 case Builtin::BI__builtin_fpclassify: {
7645 if (!EvaluateFloat(E->getArg(5), Val, Info))
7648 switch (Val.getCategory()) {
7649 case APFloat::fcNaN: Arg = 0; break;
7650 case APFloat::fcInfinity: Arg = 1; break;
7651 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7652 case APFloat::fcZero: Arg = 4; break;
7654 return Visit(E->getArg(Arg));
7657 case Builtin::BI__builtin_isinf_sign: {
7659 return EvaluateFloat(E->getArg(0), Val, Info) &&
7660 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7663 case Builtin::BI__builtin_isinf: {
7665 return EvaluateFloat(E->getArg(0), Val, Info) &&
7666 Success(Val.isInfinity() ? 1 : 0, E);
7669 case Builtin::BI__builtin_isfinite: {
7671 return EvaluateFloat(E->getArg(0), Val, Info) &&
7672 Success(Val.isFinite() ? 1 : 0, E);
7675 case Builtin::BI__builtin_isnan: {
7677 return EvaluateFloat(E->getArg(0), Val, Info) &&
7678 Success(Val.isNaN() ? 1 : 0, E);
7681 case Builtin::BI__builtin_isnormal: {
7683 return EvaluateFloat(E->getArg(0), Val, Info) &&
7684 Success(Val.isNormal() ? 1 : 0, E);
7687 case Builtin::BI__builtin_parity:
7688 case Builtin::BI__builtin_parityl:
7689 case Builtin::BI__builtin_parityll: {
7691 if (!EvaluateInteger(E->getArg(0), Val, Info))
7694 return Success(Val.countPopulation() % 2, E);
7697 case Builtin::BI__builtin_popcount:
7698 case Builtin::BI__builtin_popcountl:
7699 case Builtin::BI__builtin_popcountll: {
7701 if (!EvaluateInteger(E->getArg(0), Val, Info))
7704 return Success(Val.countPopulation(), E);
7707 case Builtin::BIstrlen:
7708 case Builtin::BIwcslen:
7709 // A call to strlen is not a constant expression.
7710 if (Info.getLangOpts().CPlusPlus11)
7711 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7712 << /*isConstexpr*/0 << /*isConstructor*/0
7713 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7715 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7717 case Builtin::BI__builtin_strlen:
7718 case Builtin::BI__builtin_wcslen: {
7719 // As an extension, we support __builtin_strlen() as a constant expression,
7720 // and support folding strlen() to a constant.
7722 if (!EvaluatePointer(E->getArg(0), String, Info))
7725 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7727 // Fast path: if it's a string literal, search the string value.
7728 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7729 String.getLValueBase().dyn_cast<const Expr *>())) {
7730 // The string literal may have embedded null characters. Find the first
7731 // one and truncate there.
7732 StringRef Str = S->getBytes();
7733 int64_t Off = String.Offset.getQuantity();
7734 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7735 S->getCharByteWidth() == 1 &&
7736 // FIXME: Add fast-path for wchar_t too.
7737 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7738 Str = Str.substr(Off);
7740 StringRef::size_type Pos = Str.find(0);
7741 if (Pos != StringRef::npos)
7742 Str = Str.substr(0, Pos);
7744 return Success(Str.size(), E);
7747 // Fall through to slow path to issue appropriate diagnostic.
7750 // Slow path: scan the bytes of the string looking for the terminating 0.
7751 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7753 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7757 return Success(Strlen, E);
7758 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7763 case Builtin::BIstrcmp:
7764 case Builtin::BIwcscmp:
7765 case Builtin::BIstrncmp:
7766 case Builtin::BIwcsncmp:
7767 case Builtin::BImemcmp:
7768 case Builtin::BIwmemcmp:
7769 // A call to strlen is not a constant expression.
7770 if (Info.getLangOpts().CPlusPlus11)
7771 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7772 << /*isConstexpr*/0 << /*isConstructor*/0
7773 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7775 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7777 case Builtin::BI__builtin_strcmp:
7778 case Builtin::BI__builtin_wcscmp:
7779 case Builtin::BI__builtin_strncmp:
7780 case Builtin::BI__builtin_wcsncmp:
7781 case Builtin::BI__builtin_memcmp:
7782 case Builtin::BI__builtin_wmemcmp: {
7783 LValue String1, String2;
7784 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7785 !EvaluatePointer(E->getArg(1), String2, Info))
7788 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7790 uint64_t MaxLength = uint64_t(-1);
7791 if (BuiltinOp != Builtin::BIstrcmp &&
7792 BuiltinOp != Builtin::BIwcscmp &&
7793 BuiltinOp != Builtin::BI__builtin_strcmp &&
7794 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7796 if (!EvaluateInteger(E->getArg(2), N, Info))
7798 MaxLength = N.getExtValue();
7800 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7801 BuiltinOp != Builtin::BIwmemcmp &&
7802 BuiltinOp != Builtin::BI__builtin_memcmp &&
7803 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7804 for (; MaxLength; --MaxLength) {
7805 APValue Char1, Char2;
7806 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7807 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7808 !Char1.isInt() || !Char2.isInt())
7810 if (Char1.getInt() != Char2.getInt())
7811 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7812 if (StopAtNull && !Char1.getInt())
7813 return Success(0, E);
7814 assert(!(StopAtNull && !Char2.getInt()));
7815 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7816 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7819 // We hit the strncmp / memcmp limit.
7820 return Success(0, E);
7823 case Builtin::BI__atomic_always_lock_free:
7824 case Builtin::BI__atomic_is_lock_free:
7825 case Builtin::BI__c11_atomic_is_lock_free: {
7827 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7830 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7831 // of two less than the maximum inline atomic width, we know it is
7832 // lock-free. If the size isn't a power of two, or greater than the
7833 // maximum alignment where we promote atomics, we know it is not lock-free
7834 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7835 // the answer can only be determined at runtime; for example, 16-byte
7836 // atomics have lock-free implementations on some, but not all,
7837 // x86-64 processors.
7839 // Check power-of-two.
7840 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7841 if (Size.isPowerOfTwo()) {
7842 // Check against inlining width.
7843 unsigned InlineWidthBits =
7844 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7845 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7846 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7847 Size == CharUnits::One() ||
7848 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7849 Expr::NPC_NeverValueDependent))
7850 // OK, we will inline appropriately-aligned operations of this size,
7851 // and _Atomic(T) is appropriately-aligned.
7852 return Success(1, E);
7854 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7855 castAs<PointerType>()->getPointeeType();
7856 if (!PointeeType->isIncompleteType() &&
7857 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7858 // OK, we will inline operations on this object.
7859 return Success(1, E);
7864 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7865 Success(0, E) : Error(E);
7870 static bool HasSameBase(const LValue &A, const LValue &B) {
7871 if (!A.getLValueBase())
7872 return !B.getLValueBase();
7873 if (!B.getLValueBase())
7876 if (A.getLValueBase().getOpaqueValue() !=
7877 B.getLValueBase().getOpaqueValue()) {
7878 const Decl *ADecl = GetLValueBaseDecl(A);
7881 const Decl *BDecl = GetLValueBaseDecl(B);
7882 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7886 return IsGlobalLValue(A.getLValueBase()) ||
7887 A.getLValueCallIndex() == B.getLValueCallIndex();
7890 /// \brief Determine whether this is a pointer past the end of the complete
7891 /// object referred to by the lvalue.
7892 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7894 // A null pointer can be viewed as being "past the end" but we don't
7895 // choose to look at it that way here.
7896 if (!LV.getLValueBase())
7899 // If the designator is valid and refers to a subobject, we're not pointing
7901 if (!LV.getLValueDesignator().Invalid &&
7902 !LV.getLValueDesignator().isOnePastTheEnd())
7905 // A pointer to an incomplete type might be past-the-end if the type's size is
7906 // zero. We cannot tell because the type is incomplete.
7907 QualType Ty = getType(LV.getLValueBase());
7908 if (Ty->isIncompleteType())
7911 // We're a past-the-end pointer if we point to the byte after the object,
7912 // no matter what our type or path is.
7913 auto Size = Ctx.getTypeSizeInChars(Ty);
7914 return LV.getLValueOffset() == Size;
7919 /// \brief Data recursive integer evaluator of certain binary operators.
7921 /// We use a data recursive algorithm for binary operators so that we are able
7922 /// to handle extreme cases of chained binary operators without causing stack
7924 class DataRecursiveIntBinOpEvaluator {
7929 EvalResult() : Failed(false) { }
7931 void swap(EvalResult &RHS) {
7933 Failed = RHS.Failed;
7940 EvalResult LHSResult; // meaningful only for binary operator expression.
7941 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7944 Job(Job &&) = default;
7946 void startSpeculativeEval(EvalInfo &Info) {
7947 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7951 SpeculativeEvaluationRAII SpecEvalRAII;
7954 SmallVector<Job, 16> Queue;
7956 IntExprEvaluator &IntEval;
7958 APValue &FinalResult;
7961 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7962 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7964 /// \brief True if \param E is a binary operator that we are going to handle
7965 /// data recursively.
7966 /// We handle binary operators that are comma, logical, or that have operands
7967 /// with integral or enumeration type.
7968 static bool shouldEnqueue(const BinaryOperator *E) {
7969 return E->getOpcode() == BO_Comma ||
7972 E->getType()->isIntegralOrEnumerationType() &&
7973 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7974 E->getRHS()->getType()->isIntegralOrEnumerationType());
7977 bool Traverse(const BinaryOperator *E) {
7979 EvalResult PrevResult;
7980 while (!Queue.empty())
7981 process(PrevResult);
7983 if (PrevResult.Failed) return false;
7985 FinalResult.swap(PrevResult.Val);
7990 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7991 return IntEval.Success(Value, E, Result);
7993 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7994 return IntEval.Success(Value, E, Result);
7996 bool Error(const Expr *E) {
7997 return IntEval.Error(E);
7999 bool Error(const Expr *E, diag::kind D) {
8000 return IntEval.Error(E, D);
8003 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8004 return Info.CCEDiag(E, D);
8007 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8008 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8009 bool &SuppressRHSDiags);
8011 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8012 const BinaryOperator *E, APValue &Result);
8014 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8015 Result.Failed = !Evaluate(Result.Val, Info, E);
8017 Result.Val = APValue();
8020 void process(EvalResult &Result);
8022 void enqueue(const Expr *E) {
8023 E = E->IgnoreParens();
8024 Queue.resize(Queue.size()+1);
8026 Queue.back().Kind = Job::AnyExprKind;
8032 bool DataRecursiveIntBinOpEvaluator::
8033 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8034 bool &SuppressRHSDiags) {
8035 if (E->getOpcode() == BO_Comma) {
8036 // Ignore LHS but note if we could not evaluate it.
8037 if (LHSResult.Failed)
8038 return Info.noteSideEffect();
8042 if (E->isLogicalOp()) {
8044 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8045 // We were able to evaluate the LHS, see if we can get away with not
8046 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8047 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8048 Success(LHSAsBool, E, LHSResult.Val);
8049 return false; // Ignore RHS
8052 LHSResult.Failed = true;
8054 // Since we weren't able to evaluate the left hand side, it
8055 // might have had side effects.
8056 if (!Info.noteSideEffect())
8059 // We can't evaluate the LHS; however, sometimes the result
8060 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8061 // Don't ignore RHS and suppress diagnostics from this arm.
8062 SuppressRHSDiags = true;
8068 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8069 E->getRHS()->getType()->isIntegralOrEnumerationType());
8071 if (LHSResult.Failed && !Info.noteFailure())
8072 return false; // Ignore RHS;
8077 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8079 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8080 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8082 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8083 CharUnits &Offset = LVal.getLValueOffset();
8084 uint64_t Offset64 = Offset.getQuantity();
8085 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8086 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8087 : Offset64 + Index64);
8090 bool DataRecursiveIntBinOpEvaluator::
8091 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8092 const BinaryOperator *E, APValue &Result) {
8093 if (E->getOpcode() == BO_Comma) {
8094 if (RHSResult.Failed)
8096 Result = RHSResult.Val;
8100 if (E->isLogicalOp()) {
8101 bool lhsResult, rhsResult;
8102 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8103 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8107 if (E->getOpcode() == BO_LOr)
8108 return Success(lhsResult || rhsResult, E, Result);
8110 return Success(lhsResult && rhsResult, E, Result);
8114 // We can't evaluate the LHS; however, sometimes the result
8115 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8116 if (rhsResult == (E->getOpcode() == BO_LOr))
8117 return Success(rhsResult, E, Result);
8124 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8125 E->getRHS()->getType()->isIntegralOrEnumerationType());
8127 if (LHSResult.Failed || RHSResult.Failed)
8130 const APValue &LHSVal = LHSResult.Val;
8131 const APValue &RHSVal = RHSResult.Val;
8133 // Handle cases like (unsigned long)&a + 4.
8134 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8136 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8140 // Handle cases like 4 + (unsigned long)&a
8141 if (E->getOpcode() == BO_Add &&
8142 RHSVal.isLValue() && LHSVal.isInt()) {
8144 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8148 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8149 // Handle (intptr_t)&&A - (intptr_t)&&B.
8150 if (!LHSVal.getLValueOffset().isZero() ||
8151 !RHSVal.getLValueOffset().isZero())
8153 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8154 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8155 if (!LHSExpr || !RHSExpr)
8157 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8158 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8159 if (!LHSAddrExpr || !RHSAddrExpr)
8161 // Make sure both labels come from the same function.
8162 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8163 RHSAddrExpr->getLabel()->getDeclContext())
8165 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8169 // All the remaining cases expect both operands to be an integer
8170 if (!LHSVal.isInt() || !RHSVal.isInt())
8173 // Set up the width and signedness manually, in case it can't be deduced
8174 // from the operation we're performing.
8175 // FIXME: Don't do this in the cases where we can deduce it.
8176 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8177 E->getType()->isUnsignedIntegerOrEnumerationType());
8178 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8179 RHSVal.getInt(), Value))
8181 return Success(Value, E, Result);
8184 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8185 Job &job = Queue.back();
8188 case Job::AnyExprKind: {
8189 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8190 if (shouldEnqueue(Bop)) {
8191 job.Kind = Job::BinOpKind;
8192 enqueue(Bop->getLHS());
8197 EvaluateExpr(job.E, Result);
8202 case Job::BinOpKind: {
8203 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8204 bool SuppressRHSDiags = false;
8205 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8209 if (SuppressRHSDiags)
8210 job.startSpeculativeEval(Info);
8211 job.LHSResult.swap(Result);
8212 job.Kind = Job::BinOpVisitedLHSKind;
8213 enqueue(Bop->getRHS());
8217 case Job::BinOpVisitedLHSKind: {
8218 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8221 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8227 llvm_unreachable("Invalid Job::Kind!");
8231 /// Used when we determine that we should fail, but can keep evaluating prior to
8232 /// noting that we had a failure.
8233 class DelayedNoteFailureRAII {
8238 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8239 : Info(Info), NoteFailure(NoteFailure) {}
8240 ~DelayedNoteFailureRAII() {
8242 bool ContinueAfterFailure = Info.noteFailure();
8243 (void)ContinueAfterFailure;
8244 assert(ContinueAfterFailure &&
8245 "Shouldn't have kept evaluating on failure.");
8251 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8252 // We don't call noteFailure immediately because the assignment happens after
8253 // we evaluate LHS and RHS.
8254 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8257 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8258 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8259 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8261 QualType LHSTy = E->getLHS()->getType();
8262 QualType RHSTy = E->getRHS()->getType();
8264 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8265 ComplexValue LHS, RHS;
8267 if (E->isAssignmentOp()) {
8269 EvaluateLValue(E->getLHS(), LV, Info);
8271 } else if (LHSTy->isRealFloatingType()) {
8272 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8274 LHS.makeComplexFloat();
8275 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8278 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8280 if (!LHSOK && !Info.noteFailure())
8283 if (E->getRHS()->getType()->isRealFloatingType()) {
8284 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8286 RHS.makeComplexFloat();
8287 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8288 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8291 if (LHS.isComplexFloat()) {
8292 APFloat::cmpResult CR_r =
8293 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8294 APFloat::cmpResult CR_i =
8295 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8297 if (E->getOpcode() == BO_EQ)
8298 return Success((CR_r == APFloat::cmpEqual &&
8299 CR_i == APFloat::cmpEqual), E);
8301 assert(E->getOpcode() == BO_NE &&
8302 "Invalid complex comparison.");
8303 return Success(((CR_r == APFloat::cmpGreaterThan ||
8304 CR_r == APFloat::cmpLessThan ||
8305 CR_r == APFloat::cmpUnordered) ||
8306 (CR_i == APFloat::cmpGreaterThan ||
8307 CR_i == APFloat::cmpLessThan ||
8308 CR_i == APFloat::cmpUnordered)), E);
8311 if (E->getOpcode() == BO_EQ)
8312 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8313 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8315 assert(E->getOpcode() == BO_NE &&
8316 "Invalid compex comparison.");
8317 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8318 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8323 if (LHSTy->isRealFloatingType() &&
8324 RHSTy->isRealFloatingType()) {
8325 APFloat RHS(0.0), LHS(0.0);
8327 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8328 if (!LHSOK && !Info.noteFailure())
8331 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8334 APFloat::cmpResult CR = LHS.compare(RHS);
8336 switch (E->getOpcode()) {
8338 llvm_unreachable("Invalid binary operator!");
8340 return Success(CR == APFloat::cmpLessThan, E);
8342 return Success(CR == APFloat::cmpGreaterThan, E);
8344 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8346 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8349 return Success(CR == APFloat::cmpEqual, E);
8351 return Success(CR == APFloat::cmpGreaterThan
8352 || CR == APFloat::cmpLessThan
8353 || CR == APFloat::cmpUnordered, E);
8357 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8358 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8359 LValue LHSValue, RHSValue;
8361 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8362 if (!LHSOK && !Info.noteFailure())
8365 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8368 // Reject differing bases from the normal codepath; we special-case
8369 // comparisons to null.
8370 if (!HasSameBase(LHSValue, RHSValue)) {
8371 if (E->getOpcode() == BO_Sub) {
8372 // Handle &&A - &&B.
8373 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8375 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8376 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8377 if (!LHSExpr || !RHSExpr)
8379 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8380 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8381 if (!LHSAddrExpr || !RHSAddrExpr)
8383 // Make sure both labels come from the same function.
8384 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8385 RHSAddrExpr->getLabel()->getDeclContext())
8387 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8389 // Inequalities and subtractions between unrelated pointers have
8390 // unspecified or undefined behavior.
8391 if (!E->isEqualityOp())
8393 // A constant address may compare equal to the address of a symbol.
8394 // The one exception is that address of an object cannot compare equal
8395 // to a null pointer constant.
8396 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8397 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8399 // It's implementation-defined whether distinct literals will have
8400 // distinct addresses. In clang, the result of such a comparison is
8401 // unspecified, so it is not a constant expression. However, we do know
8402 // that the address of a literal will be non-null.
8403 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8404 LHSValue.Base && RHSValue.Base)
8406 // We can't tell whether weak symbols will end up pointing to the same
8408 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8410 // We can't compare the address of the start of one object with the
8411 // past-the-end address of another object, per C++ DR1652.
8412 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8413 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8414 (RHSValue.Base && RHSValue.Offset.isZero() &&
8415 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8417 // We can't tell whether an object is at the same address as another
8418 // zero sized object.
8419 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8420 (LHSValue.Base && isZeroSized(RHSValue)))
8422 // Pointers with different bases cannot represent the same object.
8423 // (Note that clang defaults to -fmerge-all-constants, which can
8424 // lead to inconsistent results for comparisons involving the address
8425 // of a constant; this generally doesn't matter in practice.)
8426 return Success(E->getOpcode() == BO_NE, E);
8429 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8430 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8432 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8433 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8435 if (E->getOpcode() == BO_Sub) {
8436 // C++11 [expr.add]p6:
8437 // Unless both pointers point to elements of the same array object, or
8438 // one past the last element of the array object, the behavior is
8440 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8441 !AreElementsOfSameArray(getType(LHSValue.Base),
8442 LHSDesignator, RHSDesignator))
8443 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8445 QualType Type = E->getLHS()->getType();
8446 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8448 CharUnits ElementSize;
8449 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8452 // As an extension, a type may have zero size (empty struct or union in
8453 // C, array of zero length). Pointer subtraction in such cases has
8454 // undefined behavior, so is not constant.
8455 if (ElementSize.isZero()) {
8456 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8461 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8462 // and produce incorrect results when it overflows. Such behavior
8463 // appears to be non-conforming, but is common, so perhaps we should
8464 // assume the standard intended for such cases to be undefined behavior
8465 // and check for them.
8467 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8468 // overflow in the final conversion to ptrdiff_t.
8470 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8472 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8474 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8475 APSInt TrueResult = (LHS - RHS) / ElemSize;
8476 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8478 if (Result.extend(65) != TrueResult &&
8479 !HandleOverflow(Info, E, TrueResult, E->getType()))
8481 return Success(Result, E);
8484 // C++11 [expr.rel]p3:
8485 // Pointers to void (after pointer conversions) can be compared, with a
8486 // result defined as follows: If both pointers represent the same
8487 // address or are both the null pointer value, the result is true if the
8488 // operator is <= or >= and false otherwise; otherwise the result is
8490 // We interpret this as applying to pointers to *cv* void.
8491 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8492 E->isRelationalOp())
8493 CCEDiag(E, diag::note_constexpr_void_comparison);
8495 // C++11 [expr.rel]p2:
8496 // - If two pointers point to non-static data members of the same object,
8497 // or to subobjects or array elements fo such members, recursively, the
8498 // pointer to the later declared member compares greater provided the
8499 // two members have the same access control and provided their class is
8502 // - Otherwise pointer comparisons are unspecified.
8503 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8504 E->isRelationalOp()) {
8507 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8508 RHSDesignator, WasArrayIndex);
8509 // At the point where the designators diverge, the comparison has a
8510 // specified value if:
8511 // - we are comparing array indices
8512 // - we are comparing fields of a union, or fields with the same access
8513 // Otherwise, the result is unspecified and thus the comparison is not a
8514 // constant expression.
8515 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8516 Mismatch < RHSDesignator.Entries.size()) {
8517 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8518 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8520 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8522 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8523 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8524 << RF->getParent() << RF;
8526 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8527 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8528 << LF->getParent() << LF;
8529 else if (!LF->getParent()->isUnion() &&
8530 LF->getAccess() != RF->getAccess())
8531 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8532 << LF << LF->getAccess() << RF << RF->getAccess()
8537 // The comparison here must be unsigned, and performed with the same
8538 // width as the pointer.
8539 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8540 uint64_t CompareLHS = LHSOffset.getQuantity();
8541 uint64_t CompareRHS = RHSOffset.getQuantity();
8542 assert(PtrSize <= 64 && "Unexpected pointer width");
8543 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8547 // If there is a base and this is a relational operator, we can only
8548 // compare pointers within the object in question; otherwise, the result
8549 // depends on where the object is located in memory.
8550 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8551 QualType BaseTy = getType(LHSValue.Base);
8552 if (BaseTy->isIncompleteType())
8554 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8555 uint64_t OffsetLimit = Size.getQuantity();
8556 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8560 switch (E->getOpcode()) {
8561 default: llvm_unreachable("missing comparison operator");
8562 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8563 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8564 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8565 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8566 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8567 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8572 if (LHSTy->isMemberPointerType()) {
8573 assert(E->isEqualityOp() && "unexpected member pointer operation");
8574 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8576 MemberPtr LHSValue, RHSValue;
8578 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8579 if (!LHSOK && !Info.noteFailure())
8582 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8585 // C++11 [expr.eq]p2:
8586 // If both operands are null, they compare equal. Otherwise if only one is
8587 // null, they compare unequal.
8588 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8589 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8590 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8593 // Otherwise if either is a pointer to a virtual member function, the
8594 // result is unspecified.
8595 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8596 if (MD->isVirtual())
8597 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8598 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8599 if (MD->isVirtual())
8600 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8602 // Otherwise they compare equal if and only if they would refer to the
8603 // same member of the same most derived object or the same subobject if
8604 // they were dereferenced with a hypothetical object of the associated
8606 bool Equal = LHSValue == RHSValue;
8607 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8610 if (LHSTy->isNullPtrType()) {
8611 assert(E->isComparisonOp() && "unexpected nullptr operation");
8612 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8613 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8614 // are compared, the result is true of the operator is <=, >= or ==, and
8616 BinaryOperator::Opcode Opcode = E->getOpcode();
8617 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8620 assert((!LHSTy->isIntegralOrEnumerationType() ||
8621 !RHSTy->isIntegralOrEnumerationType()) &&
8622 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8623 // We can't continue from here for non-integral types.
8624 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8627 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8628 /// a result as the expression's type.
8629 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8630 const UnaryExprOrTypeTraitExpr *E) {
8631 switch(E->getKind()) {
8632 case UETT_AlignOf: {
8633 if (E->isArgumentType())
8634 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8636 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8639 case UETT_VecStep: {
8640 QualType Ty = E->getTypeOfArgument();
8642 if (Ty->isVectorType()) {
8643 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8645 // The vec_step built-in functions that take a 3-component
8646 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8650 return Success(n, E);
8652 return Success(1, E);
8656 QualType SrcTy = E->getTypeOfArgument();
8657 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8658 // the result is the size of the referenced type."
8659 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8660 SrcTy = Ref->getPointeeType();
8663 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8665 return Success(Sizeof, E);
8667 case UETT_OpenMPRequiredSimdAlign:
8668 assert(E->isArgumentType());
8670 Info.Ctx.toCharUnitsFromBits(
8671 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8676 llvm_unreachable("unknown expr/type trait");
8679 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8681 unsigned n = OOE->getNumComponents();
8684 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8685 for (unsigned i = 0; i != n; ++i) {
8686 OffsetOfNode ON = OOE->getComponent(i);
8687 switch (ON.getKind()) {
8688 case OffsetOfNode::Array: {
8689 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8691 if (!EvaluateInteger(Idx, IdxResult, Info))
8693 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8696 CurrentType = AT->getElementType();
8697 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8698 Result += IdxResult.getSExtValue() * ElementSize;
8702 case OffsetOfNode::Field: {
8703 FieldDecl *MemberDecl = ON.getField();
8704 const RecordType *RT = CurrentType->getAs<RecordType>();
8707 RecordDecl *RD = RT->getDecl();
8708 if (RD->isInvalidDecl()) return false;
8709 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8710 unsigned i = MemberDecl->getFieldIndex();
8711 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8712 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8713 CurrentType = MemberDecl->getType().getNonReferenceType();
8717 case OffsetOfNode::Identifier:
8718 llvm_unreachable("dependent __builtin_offsetof");
8720 case OffsetOfNode::Base: {
8721 CXXBaseSpecifier *BaseSpec = ON.getBase();
8722 if (BaseSpec->isVirtual())
8725 // Find the layout of the class whose base we are looking into.
8726 const RecordType *RT = CurrentType->getAs<RecordType>();
8729 RecordDecl *RD = RT->getDecl();
8730 if (RD->isInvalidDecl()) return false;
8731 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8733 // Find the base class itself.
8734 CurrentType = BaseSpec->getType();
8735 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8739 // Add the offset to the base.
8740 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8745 return Success(Result, OOE);
8748 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8749 switch (E->getOpcode()) {
8751 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8755 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8756 // If so, we could clear the diagnostic ID.
8757 return Visit(E->getSubExpr());
8759 // The result is just the value.
8760 return Visit(E->getSubExpr());
8762 if (!Visit(E->getSubExpr()))
8764 if (!Result.isInt()) return Error(E);
8765 const APSInt &Value = Result.getInt();
8766 if (Value.isSigned() && Value.isMinSignedValue() &&
8767 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8770 return Success(-Value, E);
8773 if (!Visit(E->getSubExpr()))
8775 if (!Result.isInt()) return Error(E);
8776 return Success(~Result.getInt(), E);
8780 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8782 return Success(!bres, E);
8787 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8788 /// result type is integer.
8789 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8790 const Expr *SubExpr = E->getSubExpr();
8791 QualType DestType = E->getType();
8792 QualType SrcType = SubExpr->getType();
8794 switch (E->getCastKind()) {
8795 case CK_BaseToDerived:
8796 case CK_DerivedToBase:
8797 case CK_UncheckedDerivedToBase:
8800 case CK_ArrayToPointerDecay:
8801 case CK_FunctionToPointerDecay:
8802 case CK_NullToPointer:
8803 case CK_NullToMemberPointer:
8804 case CK_BaseToDerivedMemberPointer:
8805 case CK_DerivedToBaseMemberPointer:
8806 case CK_ReinterpretMemberPointer:
8807 case CK_ConstructorConversion:
8808 case CK_IntegralToPointer:
8810 case CK_VectorSplat:
8811 case CK_IntegralToFloating:
8812 case CK_FloatingCast:
8813 case CK_CPointerToObjCPointerCast:
8814 case CK_BlockPointerToObjCPointerCast:
8815 case CK_AnyPointerToBlockPointerCast:
8816 case CK_ObjCObjectLValueCast:
8817 case CK_FloatingRealToComplex:
8818 case CK_FloatingComplexToReal:
8819 case CK_FloatingComplexCast:
8820 case CK_FloatingComplexToIntegralComplex:
8821 case CK_IntegralRealToComplex:
8822 case CK_IntegralComplexCast:
8823 case CK_IntegralComplexToFloatingComplex:
8824 case CK_BuiltinFnToFnPtr:
8825 case CK_ZeroToOCLEvent:
8826 case CK_ZeroToOCLQueue:
8827 case CK_NonAtomicToAtomic:
8828 case CK_AddressSpaceConversion:
8829 case CK_IntToOCLSampler:
8830 llvm_unreachable("invalid cast kind for integral value");
8834 case CK_LValueBitCast:
8835 case CK_ARCProduceObject:
8836 case CK_ARCConsumeObject:
8837 case CK_ARCReclaimReturnedObject:
8838 case CK_ARCExtendBlockObject:
8839 case CK_CopyAndAutoreleaseBlockObject:
8842 case CK_UserDefinedConversion:
8843 case CK_LValueToRValue:
8844 case CK_AtomicToNonAtomic:
8846 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8848 case CK_MemberPointerToBoolean:
8849 case CK_PointerToBoolean:
8850 case CK_IntegralToBoolean:
8851 case CK_FloatingToBoolean:
8852 case CK_BooleanToSignedIntegral:
8853 case CK_FloatingComplexToBoolean:
8854 case CK_IntegralComplexToBoolean: {
8856 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8858 uint64_t IntResult = BoolResult;
8859 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8860 IntResult = (uint64_t)-1;
8861 return Success(IntResult, E);
8864 case CK_IntegralCast: {
8865 if (!Visit(SubExpr))
8868 if (!Result.isInt()) {
8869 // Allow casts of address-of-label differences if they are no-ops
8870 // or narrowing. (The narrowing case isn't actually guaranteed to
8871 // be constant-evaluatable except in some narrow cases which are hard
8872 // to detect here. We let it through on the assumption the user knows
8873 // what they are doing.)
8874 if (Result.isAddrLabelDiff())
8875 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8876 // Only allow casts of lvalues if they are lossless.
8877 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8880 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8881 Result.getInt()), E);
8884 case CK_PointerToIntegral: {
8885 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8888 if (!EvaluatePointer(SubExpr, LV, Info))
8891 if (LV.getLValueBase()) {
8892 // Only allow based lvalue casts if they are lossless.
8893 // FIXME: Allow a larger integer size than the pointer size, and allow
8894 // narrowing back down to pointer width in subsequent integral casts.
8895 // FIXME: Check integer type's active bits, not its type size.
8896 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8899 LV.Designator.setInvalid();
8900 LV.moveInto(Result);
8905 if (LV.isNullPointer())
8906 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8908 V = LV.getLValueOffset().getQuantity();
8910 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8911 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8914 case CK_IntegralComplexToReal: {
8916 if (!EvaluateComplex(SubExpr, C, Info))
8918 return Success(C.getComplexIntReal(), E);
8921 case CK_FloatingToIntegral: {
8923 if (!EvaluateFloat(SubExpr, F, Info))
8927 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8929 return Success(Value, E);
8933 llvm_unreachable("unknown cast resulting in integral value");
8936 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8937 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8939 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8941 if (!LV.isComplexInt())
8943 return Success(LV.getComplexIntReal(), E);
8946 return Visit(E->getSubExpr());
8949 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8950 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8952 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8954 if (!LV.isComplexInt())
8956 return Success(LV.getComplexIntImag(), E);
8959 VisitIgnoredValue(E->getSubExpr());
8960 return Success(0, E);
8963 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8964 return Success(E->getPackLength(), E);
8967 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8968 return Success(E->getValue(), E);
8971 //===----------------------------------------------------------------------===//
8973 //===----------------------------------------------------------------------===//
8976 class FloatExprEvaluator
8977 : public ExprEvaluatorBase<FloatExprEvaluator> {
8980 FloatExprEvaluator(EvalInfo &info, APFloat &result)
8981 : ExprEvaluatorBaseTy(info), Result(result) {}
8983 bool Success(const APValue &V, const Expr *e) {
8984 Result = V.getFloat();
8988 bool ZeroInitialization(const Expr *E) {
8989 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8993 bool VisitCallExpr(const CallExpr *E);
8995 bool VisitUnaryOperator(const UnaryOperator *E);
8996 bool VisitBinaryOperator(const BinaryOperator *E);
8997 bool VisitFloatingLiteral(const FloatingLiteral *E);
8998 bool VisitCastExpr(const CastExpr *E);
9000 bool VisitUnaryReal(const UnaryOperator *E);
9001 bool VisitUnaryImag(const UnaryOperator *E);
9003 // FIXME: Missing: array subscript of vector, member of vector
9005 } // end anonymous namespace
9007 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9008 assert(E->isRValue() && E->getType()->isRealFloatingType());
9009 return FloatExprEvaluator(Info, Result).Visit(E);
9012 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9016 llvm::APFloat &Result) {
9017 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9018 if (!S) return false;
9020 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9024 // Treat empty strings as if they were zero.
9025 if (S->getString().empty())
9026 fill = llvm::APInt(32, 0);
9027 else if (S->getString().getAsInteger(0, fill))
9030 if (Context.getTargetInfo().isNan2008()) {
9032 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9034 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9036 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9037 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9038 // a different encoding to what became a standard in 2008, and for pre-
9039 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9040 // sNaN. This is now known as "legacy NaN" encoding.
9042 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9044 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9050 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9051 switch (E->getBuiltinCallee()) {
9053 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9055 case Builtin::BI__builtin_huge_val:
9056 case Builtin::BI__builtin_huge_valf:
9057 case Builtin::BI__builtin_huge_vall:
9058 case Builtin::BI__builtin_inf:
9059 case Builtin::BI__builtin_inff:
9060 case Builtin::BI__builtin_infl: {
9061 const llvm::fltSemantics &Sem =
9062 Info.Ctx.getFloatTypeSemantics(E->getType());
9063 Result = llvm::APFloat::getInf(Sem);
9067 case Builtin::BI__builtin_nans:
9068 case Builtin::BI__builtin_nansf:
9069 case Builtin::BI__builtin_nansl:
9070 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9075 case Builtin::BI__builtin_nan:
9076 case Builtin::BI__builtin_nanf:
9077 case Builtin::BI__builtin_nanl:
9078 // If this is __builtin_nan() turn this into a nan, otherwise we
9079 // can't constant fold it.
9080 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9085 case Builtin::BI__builtin_fabs:
9086 case Builtin::BI__builtin_fabsf:
9087 case Builtin::BI__builtin_fabsl:
9088 if (!EvaluateFloat(E->getArg(0), Result, Info))
9091 if (Result.isNegative())
9092 Result.changeSign();
9095 // FIXME: Builtin::BI__builtin_powi
9096 // FIXME: Builtin::BI__builtin_powif
9097 // FIXME: Builtin::BI__builtin_powil
9099 case Builtin::BI__builtin_copysign:
9100 case Builtin::BI__builtin_copysignf:
9101 case Builtin::BI__builtin_copysignl: {
9103 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9104 !EvaluateFloat(E->getArg(1), RHS, Info))
9106 Result.copySign(RHS);
9112 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9113 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9115 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9117 Result = CV.FloatReal;
9121 return Visit(E->getSubExpr());
9124 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9125 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9127 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9129 Result = CV.FloatImag;
9133 VisitIgnoredValue(E->getSubExpr());
9134 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9135 Result = llvm::APFloat::getZero(Sem);
9139 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9140 switch (E->getOpcode()) {
9141 default: return Error(E);
9143 return EvaluateFloat(E->getSubExpr(), Result, Info);
9145 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9147 Result.changeSign();
9152 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9153 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9154 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9157 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9158 if (!LHSOK && !Info.noteFailure())
9160 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9161 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9164 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9165 Result = E->getValue();
9169 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9170 const Expr* SubExpr = E->getSubExpr();
9172 switch (E->getCastKind()) {
9174 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9176 case CK_IntegralToFloating: {
9178 return EvaluateInteger(SubExpr, IntResult, Info) &&
9179 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9180 E->getType(), Result);
9183 case CK_FloatingCast: {
9184 if (!Visit(SubExpr))
9186 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9190 case CK_FloatingComplexToReal: {
9192 if (!EvaluateComplex(SubExpr, V, Info))
9194 Result = V.getComplexFloatReal();
9200 //===----------------------------------------------------------------------===//
9201 // Complex Evaluation (for float and integer)
9202 //===----------------------------------------------------------------------===//
9205 class ComplexExprEvaluator
9206 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9207 ComplexValue &Result;
9210 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9211 : ExprEvaluatorBaseTy(info), Result(Result) {}
9213 bool Success(const APValue &V, const Expr *e) {
9218 bool ZeroInitialization(const Expr *E);
9220 //===--------------------------------------------------------------------===//
9222 //===--------------------------------------------------------------------===//
9224 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9225 bool VisitCastExpr(const CastExpr *E);
9226 bool VisitBinaryOperator(const BinaryOperator *E);
9227 bool VisitUnaryOperator(const UnaryOperator *E);
9228 bool VisitInitListExpr(const InitListExpr *E);
9230 } // end anonymous namespace
9232 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9234 assert(E->isRValue() && E->getType()->isAnyComplexType());
9235 return ComplexExprEvaluator(Info, Result).Visit(E);
9238 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9239 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9240 if (ElemTy->isRealFloatingType()) {
9241 Result.makeComplexFloat();
9242 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9243 Result.FloatReal = Zero;
9244 Result.FloatImag = Zero;
9246 Result.makeComplexInt();
9247 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9248 Result.IntReal = Zero;
9249 Result.IntImag = Zero;
9254 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9255 const Expr* SubExpr = E->getSubExpr();
9257 if (SubExpr->getType()->isRealFloatingType()) {
9258 Result.makeComplexFloat();
9259 APFloat &Imag = Result.FloatImag;
9260 if (!EvaluateFloat(SubExpr, Imag, Info))
9263 Result.FloatReal = APFloat(Imag.getSemantics());
9266 assert(SubExpr->getType()->isIntegerType() &&
9267 "Unexpected imaginary literal.");
9269 Result.makeComplexInt();
9270 APSInt &Imag = Result.IntImag;
9271 if (!EvaluateInteger(SubExpr, Imag, Info))
9274 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9279 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9281 switch (E->getCastKind()) {
9283 case CK_BaseToDerived:
9284 case CK_DerivedToBase:
9285 case CK_UncheckedDerivedToBase:
9288 case CK_ArrayToPointerDecay:
9289 case CK_FunctionToPointerDecay:
9290 case CK_NullToPointer:
9291 case CK_NullToMemberPointer:
9292 case CK_BaseToDerivedMemberPointer:
9293 case CK_DerivedToBaseMemberPointer:
9294 case CK_MemberPointerToBoolean:
9295 case CK_ReinterpretMemberPointer:
9296 case CK_ConstructorConversion:
9297 case CK_IntegralToPointer:
9298 case CK_PointerToIntegral:
9299 case CK_PointerToBoolean:
9301 case CK_VectorSplat:
9302 case CK_IntegralCast:
9303 case CK_BooleanToSignedIntegral:
9304 case CK_IntegralToBoolean:
9305 case CK_IntegralToFloating:
9306 case CK_FloatingToIntegral:
9307 case CK_FloatingToBoolean:
9308 case CK_FloatingCast:
9309 case CK_CPointerToObjCPointerCast:
9310 case CK_BlockPointerToObjCPointerCast:
9311 case CK_AnyPointerToBlockPointerCast:
9312 case CK_ObjCObjectLValueCast:
9313 case CK_FloatingComplexToReal:
9314 case CK_FloatingComplexToBoolean:
9315 case CK_IntegralComplexToReal:
9316 case CK_IntegralComplexToBoolean:
9317 case CK_ARCProduceObject:
9318 case CK_ARCConsumeObject:
9319 case CK_ARCReclaimReturnedObject:
9320 case CK_ARCExtendBlockObject:
9321 case CK_CopyAndAutoreleaseBlockObject:
9322 case CK_BuiltinFnToFnPtr:
9323 case CK_ZeroToOCLEvent:
9324 case CK_ZeroToOCLQueue:
9325 case CK_NonAtomicToAtomic:
9326 case CK_AddressSpaceConversion:
9327 case CK_IntToOCLSampler:
9328 llvm_unreachable("invalid cast kind for complex value");
9330 case CK_LValueToRValue:
9331 case CK_AtomicToNonAtomic:
9333 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9336 case CK_LValueBitCast:
9337 case CK_UserDefinedConversion:
9340 case CK_FloatingRealToComplex: {
9341 APFloat &Real = Result.FloatReal;
9342 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9345 Result.makeComplexFloat();
9346 Result.FloatImag = APFloat(Real.getSemantics());
9350 case CK_FloatingComplexCast: {
9351 if (!Visit(E->getSubExpr()))
9354 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9356 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9358 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9359 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9362 case CK_FloatingComplexToIntegralComplex: {
9363 if (!Visit(E->getSubExpr()))
9366 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9368 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9369 Result.makeComplexInt();
9370 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9371 To, Result.IntReal) &&
9372 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9373 To, Result.IntImag);
9376 case CK_IntegralRealToComplex: {
9377 APSInt &Real = Result.IntReal;
9378 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9381 Result.makeComplexInt();
9382 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9386 case CK_IntegralComplexCast: {
9387 if (!Visit(E->getSubExpr()))
9390 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9392 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9394 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9395 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9399 case CK_IntegralComplexToFloatingComplex: {
9400 if (!Visit(E->getSubExpr()))
9403 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9405 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9406 Result.makeComplexFloat();
9407 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9408 To, Result.FloatReal) &&
9409 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9410 To, Result.FloatImag);
9414 llvm_unreachable("unknown cast resulting in complex value");
9417 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9418 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9419 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9421 // Track whether the LHS or RHS is real at the type system level. When this is
9422 // the case we can simplify our evaluation strategy.
9423 bool LHSReal = false, RHSReal = false;
9426 if (E->getLHS()->getType()->isRealFloatingType()) {
9428 APFloat &Real = Result.FloatReal;
9429 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9431 Result.makeComplexFloat();
9432 Result.FloatImag = APFloat(Real.getSemantics());
9435 LHSOK = Visit(E->getLHS());
9437 if (!LHSOK && !Info.noteFailure())
9441 if (E->getRHS()->getType()->isRealFloatingType()) {
9443 APFloat &Real = RHS.FloatReal;
9444 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9446 RHS.makeComplexFloat();
9447 RHS.FloatImag = APFloat(Real.getSemantics());
9448 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9451 assert(!(LHSReal && RHSReal) &&
9452 "Cannot have both operands of a complex operation be real.");
9453 switch (E->getOpcode()) {
9454 default: return Error(E);
9456 if (Result.isComplexFloat()) {
9457 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9458 APFloat::rmNearestTiesToEven);
9460 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9462 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9463 APFloat::rmNearestTiesToEven);
9465 Result.getComplexIntReal() += RHS.getComplexIntReal();
9466 Result.getComplexIntImag() += RHS.getComplexIntImag();
9470 if (Result.isComplexFloat()) {
9471 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9472 APFloat::rmNearestTiesToEven);
9474 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9475 Result.getComplexFloatImag().changeSign();
9476 } else if (!RHSReal) {
9477 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9478 APFloat::rmNearestTiesToEven);
9481 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9482 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9486 if (Result.isComplexFloat()) {
9487 // This is an implementation of complex multiplication according to the
9488 // constraints laid out in C11 Annex G. The implemantion uses the
9489 // following naming scheme:
9490 // (a + ib) * (c + id)
9491 ComplexValue LHS = Result;
9492 APFloat &A = LHS.getComplexFloatReal();
9493 APFloat &B = LHS.getComplexFloatImag();
9494 APFloat &C = RHS.getComplexFloatReal();
9495 APFloat &D = RHS.getComplexFloatImag();
9496 APFloat &ResR = Result.getComplexFloatReal();
9497 APFloat &ResI = Result.getComplexFloatImag();
9499 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9502 } else if (RHSReal) {
9506 // In the fully general case, we need to handle NaNs and infinities
9514 if (ResR.isNaN() && ResI.isNaN()) {
9515 bool Recalc = false;
9516 if (A.isInfinity() || B.isInfinity()) {
9517 A = APFloat::copySign(
9518 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9519 B = APFloat::copySign(
9520 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9522 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9524 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9527 if (C.isInfinity() || D.isInfinity()) {
9528 C = APFloat::copySign(
9529 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9530 D = APFloat::copySign(
9531 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9533 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9535 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9538 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9539 AD.isInfinity() || BC.isInfinity())) {
9541 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9543 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9545 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9547 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9551 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9552 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9557 ComplexValue LHS = Result;
9558 Result.getComplexIntReal() =
9559 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9560 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9561 Result.getComplexIntImag() =
9562 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9563 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9567 if (Result.isComplexFloat()) {
9568 // This is an implementation of complex division according to the
9569 // constraints laid out in C11 Annex G. The implemantion uses the
9570 // following naming scheme:
9571 // (a + ib) / (c + id)
9572 ComplexValue LHS = Result;
9573 APFloat &A = LHS.getComplexFloatReal();
9574 APFloat &B = LHS.getComplexFloatImag();
9575 APFloat &C = RHS.getComplexFloatReal();
9576 APFloat &D = RHS.getComplexFloatImag();
9577 APFloat &ResR = Result.getComplexFloatReal();
9578 APFloat &ResI = Result.getComplexFloatImag();
9584 // No real optimizations we can do here, stub out with zero.
9585 B = APFloat::getZero(A.getSemantics());
9588 APFloat MaxCD = maxnum(abs(C), abs(D));
9589 if (MaxCD.isFinite()) {
9590 DenomLogB = ilogb(MaxCD);
9591 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9592 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9594 APFloat Denom = C * C + D * D;
9595 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9596 APFloat::rmNearestTiesToEven);
9597 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9598 APFloat::rmNearestTiesToEven);
9599 if (ResR.isNaN() && ResI.isNaN()) {
9600 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9601 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9602 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9603 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9605 A = APFloat::copySign(
9606 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9607 B = APFloat::copySign(
9608 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9609 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9610 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9611 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9612 C = APFloat::copySign(
9613 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9614 D = APFloat::copySign(
9615 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9616 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9617 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9622 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9623 return Error(E, diag::note_expr_divide_by_zero);
9625 ComplexValue LHS = Result;
9626 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9627 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9628 Result.getComplexIntReal() =
9629 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9630 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9631 Result.getComplexIntImag() =
9632 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9633 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9641 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9642 // Get the operand value into 'Result'.
9643 if (!Visit(E->getSubExpr()))
9646 switch (E->getOpcode()) {
9652 // The result is always just the subexpr.
9655 if (Result.isComplexFloat()) {
9656 Result.getComplexFloatReal().changeSign();
9657 Result.getComplexFloatImag().changeSign();
9660 Result.getComplexIntReal() = -Result.getComplexIntReal();
9661 Result.getComplexIntImag() = -Result.getComplexIntImag();
9665 if (Result.isComplexFloat())
9666 Result.getComplexFloatImag().changeSign();
9668 Result.getComplexIntImag() = -Result.getComplexIntImag();
9673 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9674 if (E->getNumInits() == 2) {
9675 if (E->getType()->isComplexType()) {
9676 Result.makeComplexFloat();
9677 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9679 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9682 Result.makeComplexInt();
9683 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9685 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9690 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9693 //===----------------------------------------------------------------------===//
9694 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9695 // implicit conversion.
9696 //===----------------------------------------------------------------------===//
9699 class AtomicExprEvaluator :
9700 public ExprEvaluatorBase<AtomicExprEvaluator> {
9704 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9705 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9707 bool Success(const APValue &V, const Expr *E) {
9712 bool ZeroInitialization(const Expr *E) {
9713 ImplicitValueInitExpr VIE(
9714 E->getType()->castAs<AtomicType>()->getValueType());
9715 // For atomic-qualified class (and array) types in C++, initialize the
9716 // _Atomic-wrapped subobject directly, in-place.
9717 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9718 : Evaluate(Result, Info, &VIE);
9721 bool VisitCastExpr(const CastExpr *E) {
9722 switch (E->getCastKind()) {
9724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9725 case CK_NonAtomicToAtomic:
9726 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9727 : Evaluate(Result, Info, E->getSubExpr());
9731 } // end anonymous namespace
9733 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9735 assert(E->isRValue() && E->getType()->isAtomicType());
9736 return AtomicExprEvaluator(Info, This, Result).Visit(E);
9739 //===----------------------------------------------------------------------===//
9740 // Void expression evaluation, primarily for a cast to void on the LHS of a
9742 //===----------------------------------------------------------------------===//
9745 class VoidExprEvaluator
9746 : public ExprEvaluatorBase<VoidExprEvaluator> {
9748 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9750 bool Success(const APValue &V, const Expr *e) { return true; }
9752 bool VisitCastExpr(const CastExpr *E) {
9753 switch (E->getCastKind()) {
9755 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9757 VisitIgnoredValue(E->getSubExpr());
9762 bool VisitCallExpr(const CallExpr *E) {
9763 switch (E->getBuiltinCallee()) {
9765 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9766 case Builtin::BI__assume:
9767 case Builtin::BI__builtin_assume:
9768 // The argument is not evaluated!
9773 } // end anonymous namespace
9775 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9776 assert(E->isRValue() && E->getType()->isVoidType());
9777 return VoidExprEvaluator(Info).Visit(E);
9780 //===----------------------------------------------------------------------===//
9781 // Top level Expr::EvaluateAsRValue method.
9782 //===----------------------------------------------------------------------===//
9784 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9785 // In C, function designators are not lvalues, but we evaluate them as if they
9787 QualType T = E->getType();
9788 if (E->isGLValue() || T->isFunctionType()) {
9790 if (!EvaluateLValue(E, LV, Info))
9792 LV.moveInto(Result);
9793 } else if (T->isVectorType()) {
9794 if (!EvaluateVector(E, Result, Info))
9796 } else if (T->isIntegralOrEnumerationType()) {
9797 if (!IntExprEvaluator(Info, Result).Visit(E))
9799 } else if (T->hasPointerRepresentation()) {
9801 if (!EvaluatePointer(E, LV, Info))
9803 LV.moveInto(Result);
9804 } else if (T->isRealFloatingType()) {
9805 llvm::APFloat F(0.0);
9806 if (!EvaluateFloat(E, F, Info))
9808 Result = APValue(F);
9809 } else if (T->isAnyComplexType()) {
9811 if (!EvaluateComplex(E, C, Info))
9814 } else if (T->isMemberPointerType()) {
9816 if (!EvaluateMemberPointer(E, P, Info))
9820 } else if (T->isArrayType()) {
9822 LV.set(E, Info.CurrentCall->Index);
9823 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9824 if (!EvaluateArray(E, LV, Value, Info))
9827 } else if (T->isRecordType()) {
9829 LV.set(E, Info.CurrentCall->Index);
9830 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9831 if (!EvaluateRecord(E, LV, Value, Info))
9834 } else if (T->isVoidType()) {
9835 if (!Info.getLangOpts().CPlusPlus11)
9836 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9838 if (!EvaluateVoid(E, Info))
9840 } else if (T->isAtomicType()) {
9841 QualType Unqual = T.getAtomicUnqualifiedType();
9842 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9844 LV.set(E, Info.CurrentCall->Index);
9845 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9846 if (!EvaluateAtomic(E, &LV, Value, Info))
9849 if (!EvaluateAtomic(E, nullptr, Result, Info))
9852 } else if (Info.getLangOpts().CPlusPlus11) {
9853 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9856 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9863 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9864 /// cases, the in-place evaluation is essential, since later initializers for
9865 /// an object can indirectly refer to subobjects which were initialized earlier.
9866 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9867 const Expr *E, bool AllowNonLiteralTypes) {
9868 assert(!E->isValueDependent());
9870 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9873 if (E->isRValue()) {
9874 // Evaluate arrays and record types in-place, so that later initializers can
9875 // refer to earlier-initialized members of the object.
9876 QualType T = E->getType();
9877 if (T->isArrayType())
9878 return EvaluateArray(E, This, Result, Info);
9879 else if (T->isRecordType())
9880 return EvaluateRecord(E, This, Result, Info);
9881 else if (T->isAtomicType()) {
9882 QualType Unqual = T.getAtomicUnqualifiedType();
9883 if (Unqual->isArrayType() || Unqual->isRecordType())
9884 return EvaluateAtomic(E, &This, Result, Info);
9888 // For any other type, in-place evaluation is unimportant.
9889 return Evaluate(Result, Info, E);
9892 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9893 /// lvalue-to-rvalue cast if it is an lvalue.
9894 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9895 if (E->getType().isNull())
9898 if (!CheckLiteralType(Info, E))
9901 if (!::Evaluate(Result, Info, E))
9904 if (E->isGLValue()) {
9906 LV.setFrom(Info.Ctx, Result);
9907 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9911 // Check this core constant expression is a constant expression.
9912 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9915 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9916 const ASTContext &Ctx, bool &IsConst) {
9917 // Fast-path evaluations of integer literals, since we sometimes see files
9918 // containing vast quantities of these.
9919 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9920 Result.Val = APValue(APSInt(L->getValue(),
9921 L->getType()->isUnsignedIntegerType()));
9926 // This case should be rare, but we need to check it before we check on
9928 if (Exp->getType().isNull()) {
9933 // FIXME: Evaluating values of large array and record types can cause
9934 // performance problems. Only do so in C++11 for now.
9935 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9936 Exp->getType()->isRecordType()) &&
9937 !Ctx.getLangOpts().CPlusPlus11) {
9945 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9946 /// any crazy technique (that has nothing to do with language standards) that
9947 /// we want to. If this function returns true, it returns the folded constant
9948 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9949 /// will be applied to the result.
9950 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9952 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9955 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9956 return ::EvaluateAsRValue(Info, this, Result.Val);
9959 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9960 const ASTContext &Ctx) const {
9962 return EvaluateAsRValue(Scratch, Ctx) &&
9963 HandleConversionToBool(Scratch.Val, Result);
9966 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9967 Expr::SideEffectsKind SEK) {
9968 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9969 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9972 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9973 SideEffectsKind AllowSideEffects) const {
9974 if (!getType()->isIntegralOrEnumerationType())
9977 EvalResult ExprResult;
9978 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9979 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9982 Result = ExprResult.Val.getInt();
9986 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9987 SideEffectsKind AllowSideEffects) const {
9988 if (!getType()->isRealFloatingType())
9991 EvalResult ExprResult;
9992 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9993 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9996 Result = ExprResult.Val.getFloat();
10000 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10001 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10004 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10005 !CheckLValueConstantExpression(Info, getExprLoc(),
10006 Ctx.getLValueReferenceType(getType()), LV))
10009 LV.moveInto(Result.Val);
10013 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10015 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10016 // FIXME: Evaluating initializers for large array and record types can cause
10017 // performance problems. Only do so in C++11 for now.
10018 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10019 !Ctx.getLangOpts().CPlusPlus11)
10022 Expr::EvalStatus EStatus;
10023 EStatus.Diag = &Notes;
10025 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10026 ? EvalInfo::EM_ConstantExpression
10027 : EvalInfo::EM_ConstantFold);
10028 InitInfo.setEvaluatingDecl(VD, Value);
10033 // C++11 [basic.start.init]p2:
10034 // Variables with static storage duration or thread storage duration shall be
10035 // zero-initialized before any other initialization takes place.
10036 // This behavior is not present in C.
10037 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10038 !VD->getType()->isReferenceType()) {
10039 ImplicitValueInitExpr VIE(VD->getType());
10040 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10041 /*AllowNonLiteralTypes=*/true))
10045 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10046 /*AllowNonLiteralTypes=*/true) ||
10047 EStatus.HasSideEffects)
10050 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10054 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10055 /// constant folded, but discard the result.
10056 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10058 return EvaluateAsRValue(Result, Ctx) &&
10059 !hasUnacceptableSideEffect(Result, SEK);
10062 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10063 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10064 EvalResult EvalResult;
10065 EvalResult.Diag = Diag;
10066 bool Result = EvaluateAsRValue(EvalResult, Ctx);
10068 assert(Result && "Could not evaluate expression");
10069 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10071 return EvalResult.Val.getInt();
10074 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10076 EvalResult EvalResult;
10077 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10078 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10079 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10083 bool Expr::EvalResult::isGlobalLValue() const {
10084 assert(Val.isLValue());
10085 return IsGlobalLValue(Val.getLValueBase());
10089 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10090 /// an integer constant expression.
10092 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10095 // CheckICE - This function does the fundamental ICE checking: the returned
10096 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10097 // and a (possibly null) SourceLocation indicating the location of the problem.
10099 // Note that to reduce code duplication, this helper does no evaluation
10100 // itself; the caller checks whether the expression is evaluatable, and
10101 // in the rare cases where CheckICE actually cares about the evaluated
10102 // value, it calls into Evaluate.
10107 /// This expression is an ICE.
10109 /// This expression is not an ICE, but if it isn't evaluated, it's
10110 /// a legal subexpression for an ICE. This return value is used to handle
10111 /// the comma operator in C99 mode, and non-constant subexpressions.
10112 IK_ICEIfUnevaluated,
10113 /// This expression is not an ICE, and is not a legal subexpression for one.
10119 SourceLocation Loc;
10121 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10126 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10128 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10130 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10131 Expr::EvalResult EVResult;
10132 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10133 !EVResult.Val.isInt())
10134 return ICEDiag(IK_NotICE, E->getLocStart());
10139 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10140 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10141 if (!E->getType()->isIntegralOrEnumerationType())
10142 return ICEDiag(IK_NotICE, E->getLocStart());
10144 switch (E->getStmtClass()) {
10145 #define ABSTRACT_STMT(Node)
10146 #define STMT(Node, Base) case Expr::Node##Class:
10147 #define EXPR(Node, Base)
10148 #include "clang/AST/StmtNodes.inc"
10149 case Expr::PredefinedExprClass:
10150 case Expr::FloatingLiteralClass:
10151 case Expr::ImaginaryLiteralClass:
10152 case Expr::StringLiteralClass:
10153 case Expr::ArraySubscriptExprClass:
10154 case Expr::OMPArraySectionExprClass:
10155 case Expr::MemberExprClass:
10156 case Expr::CompoundAssignOperatorClass:
10157 case Expr::CompoundLiteralExprClass:
10158 case Expr::ExtVectorElementExprClass:
10159 case Expr::DesignatedInitExprClass:
10160 case Expr::ArrayInitLoopExprClass:
10161 case Expr::ArrayInitIndexExprClass:
10162 case Expr::NoInitExprClass:
10163 case Expr::DesignatedInitUpdateExprClass:
10164 case Expr::ImplicitValueInitExprClass:
10165 case Expr::ParenListExprClass:
10166 case Expr::VAArgExprClass:
10167 case Expr::AddrLabelExprClass:
10168 case Expr::StmtExprClass:
10169 case Expr::CXXMemberCallExprClass:
10170 case Expr::CUDAKernelCallExprClass:
10171 case Expr::CXXDynamicCastExprClass:
10172 case Expr::CXXTypeidExprClass:
10173 case Expr::CXXUuidofExprClass:
10174 case Expr::MSPropertyRefExprClass:
10175 case Expr::MSPropertySubscriptExprClass:
10176 case Expr::CXXNullPtrLiteralExprClass:
10177 case Expr::UserDefinedLiteralClass:
10178 case Expr::CXXThisExprClass:
10179 case Expr::CXXThrowExprClass:
10180 case Expr::CXXNewExprClass:
10181 case Expr::CXXDeleteExprClass:
10182 case Expr::CXXPseudoDestructorExprClass:
10183 case Expr::UnresolvedLookupExprClass:
10184 case Expr::TypoExprClass:
10185 case Expr::DependentScopeDeclRefExprClass:
10186 case Expr::CXXConstructExprClass:
10187 case Expr::CXXInheritedCtorInitExprClass:
10188 case Expr::CXXStdInitializerListExprClass:
10189 case Expr::CXXBindTemporaryExprClass:
10190 case Expr::ExprWithCleanupsClass:
10191 case Expr::CXXTemporaryObjectExprClass:
10192 case Expr::CXXUnresolvedConstructExprClass:
10193 case Expr::CXXDependentScopeMemberExprClass:
10194 case Expr::UnresolvedMemberExprClass:
10195 case Expr::ObjCStringLiteralClass:
10196 case Expr::ObjCBoxedExprClass:
10197 case Expr::ObjCArrayLiteralClass:
10198 case Expr::ObjCDictionaryLiteralClass:
10199 case Expr::ObjCEncodeExprClass:
10200 case Expr::ObjCMessageExprClass:
10201 case Expr::ObjCSelectorExprClass:
10202 case Expr::ObjCProtocolExprClass:
10203 case Expr::ObjCIvarRefExprClass:
10204 case Expr::ObjCPropertyRefExprClass:
10205 case Expr::ObjCSubscriptRefExprClass:
10206 case Expr::ObjCIsaExprClass:
10207 case Expr::ObjCAvailabilityCheckExprClass:
10208 case Expr::ShuffleVectorExprClass:
10209 case Expr::ConvertVectorExprClass:
10210 case Expr::BlockExprClass:
10211 case Expr::NoStmtClass:
10212 case Expr::OpaqueValueExprClass:
10213 case Expr::PackExpansionExprClass:
10214 case Expr::SubstNonTypeTemplateParmPackExprClass:
10215 case Expr::FunctionParmPackExprClass:
10216 case Expr::AsTypeExprClass:
10217 case Expr::ObjCIndirectCopyRestoreExprClass:
10218 case Expr::MaterializeTemporaryExprClass:
10219 case Expr::PseudoObjectExprClass:
10220 case Expr::AtomicExprClass:
10221 case Expr::LambdaExprClass:
10222 case Expr::CXXFoldExprClass:
10223 case Expr::CoawaitExprClass:
10224 case Expr::DependentCoawaitExprClass:
10225 case Expr::CoyieldExprClass:
10226 return ICEDiag(IK_NotICE, E->getLocStart());
10228 case Expr::InitListExprClass: {
10229 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10230 // form "T x = { a };" is equivalent to "T x = a;".
10231 // Unless we're initializing a reference, T is a scalar as it is known to be
10232 // of integral or enumeration type.
10234 if (cast<InitListExpr>(E)->getNumInits() == 1)
10235 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10236 return ICEDiag(IK_NotICE, E->getLocStart());
10239 case Expr::SizeOfPackExprClass:
10240 case Expr::GNUNullExprClass:
10241 // GCC considers the GNU __null value to be an integral constant expression.
10244 case Expr::SubstNonTypeTemplateParmExprClass:
10246 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10248 case Expr::ParenExprClass:
10249 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10250 case Expr::GenericSelectionExprClass:
10251 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10252 case Expr::IntegerLiteralClass:
10253 case Expr::CharacterLiteralClass:
10254 case Expr::ObjCBoolLiteralExprClass:
10255 case Expr::CXXBoolLiteralExprClass:
10256 case Expr::CXXScalarValueInitExprClass:
10257 case Expr::TypeTraitExprClass:
10258 case Expr::ArrayTypeTraitExprClass:
10259 case Expr::ExpressionTraitExprClass:
10260 case Expr::CXXNoexceptExprClass:
10262 case Expr::CallExprClass:
10263 case Expr::CXXOperatorCallExprClass: {
10264 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10265 // constant expressions, but they can never be ICEs because an ICE cannot
10266 // contain an operand of (pointer to) function type.
10267 const CallExpr *CE = cast<CallExpr>(E);
10268 if (CE->getBuiltinCallee())
10269 return CheckEvalInICE(E, Ctx);
10270 return ICEDiag(IK_NotICE, E->getLocStart());
10272 case Expr::DeclRefExprClass: {
10273 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10275 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10276 if (Ctx.getLangOpts().CPlusPlus &&
10277 D && IsConstNonVolatile(D->getType())) {
10278 // Parameter variables are never constants. Without this check,
10279 // getAnyInitializer() can find a default argument, which leads
10281 if (isa<ParmVarDecl>(D))
10282 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10285 // A variable of non-volatile const-qualified integral or enumeration
10286 // type initialized by an ICE can be used in ICEs.
10287 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10288 if (!Dcl->getType()->isIntegralOrEnumerationType())
10289 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10292 // Look for a declaration of this variable that has an initializer, and
10293 // check whether it is an ICE.
10294 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10297 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10300 return ICEDiag(IK_NotICE, E->getLocStart());
10302 case Expr::UnaryOperatorClass: {
10303 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10304 switch (Exp->getOpcode()) {
10312 // C99 6.6/3 allows increment and decrement within unevaluated
10313 // subexpressions of constant expressions, but they can never be ICEs
10314 // because an ICE cannot contain an lvalue operand.
10315 return ICEDiag(IK_NotICE, E->getLocStart());
10323 return CheckICE(Exp->getSubExpr(), Ctx);
10326 // OffsetOf falls through here.
10328 case Expr::OffsetOfExprClass: {
10329 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10330 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10331 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10332 // compliance: we should warn earlier for offsetof expressions with
10333 // array subscripts that aren't ICEs, and if the array subscripts
10334 // are ICEs, the value of the offsetof must be an integer constant.
10335 return CheckEvalInICE(E, Ctx);
10337 case Expr::UnaryExprOrTypeTraitExprClass: {
10338 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10339 if ((Exp->getKind() == UETT_SizeOf) &&
10340 Exp->getTypeOfArgument()->isVariableArrayType())
10341 return ICEDiag(IK_NotICE, E->getLocStart());
10344 case Expr::BinaryOperatorClass: {
10345 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10346 switch (Exp->getOpcode()) {
10360 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10361 // constant expressions, but they can never be ICEs because an ICE cannot
10362 // contain an lvalue operand.
10363 return ICEDiag(IK_NotICE, E->getLocStart());
10382 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10383 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10384 if (Exp->getOpcode() == BO_Div ||
10385 Exp->getOpcode() == BO_Rem) {
10386 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10387 // we don't evaluate one.
10388 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10389 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10391 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10392 if (REval.isSigned() && REval.isAllOnesValue()) {
10393 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10394 if (LEval.isMinSignedValue())
10395 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10399 if (Exp->getOpcode() == BO_Comma) {
10400 if (Ctx.getLangOpts().C99) {
10401 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10402 // if it isn't evaluated.
10403 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10404 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10406 // In both C89 and C++, commas in ICEs are illegal.
10407 return ICEDiag(IK_NotICE, E->getLocStart());
10410 return Worst(LHSResult, RHSResult);
10414 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10415 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10416 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10417 // Rare case where the RHS has a comma "side-effect"; we need
10418 // to actually check the condition to see whether the side
10419 // with the comma is evaluated.
10420 if ((Exp->getOpcode() == BO_LAnd) !=
10421 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10426 return Worst(LHSResult, RHSResult);
10430 case Expr::ImplicitCastExprClass:
10431 case Expr::CStyleCastExprClass:
10432 case Expr::CXXFunctionalCastExprClass:
10433 case Expr::CXXStaticCastExprClass:
10434 case Expr::CXXReinterpretCastExprClass:
10435 case Expr::CXXConstCastExprClass:
10436 case Expr::ObjCBridgedCastExprClass: {
10437 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10438 if (isa<ExplicitCastExpr>(E)) {
10439 if (const FloatingLiteral *FL
10440 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10441 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10442 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10443 APSInt IgnoredVal(DestWidth, !DestSigned);
10445 // If the value does not fit in the destination type, the behavior is
10446 // undefined, so we are not required to treat it as a constant
10448 if (FL->getValue().convertToInteger(IgnoredVal,
10449 llvm::APFloat::rmTowardZero,
10450 &Ignored) & APFloat::opInvalidOp)
10451 return ICEDiag(IK_NotICE, E->getLocStart());
10455 switch (cast<CastExpr>(E)->getCastKind()) {
10456 case CK_LValueToRValue:
10457 case CK_AtomicToNonAtomic:
10458 case CK_NonAtomicToAtomic:
10460 case CK_IntegralToBoolean:
10461 case CK_IntegralCast:
10462 return CheckICE(SubExpr, Ctx);
10464 return ICEDiag(IK_NotICE, E->getLocStart());
10467 case Expr::BinaryConditionalOperatorClass: {
10468 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10469 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10470 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10471 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10472 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10473 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10474 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10475 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10476 return FalseResult;
10478 case Expr::ConditionalOperatorClass: {
10479 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10480 // If the condition (ignoring parens) is a __builtin_constant_p call,
10481 // then only the true side is actually considered in an integer constant
10482 // expression, and it is fully evaluated. This is an important GNU
10483 // extension. See GCC PR38377 for discussion.
10484 if (const CallExpr *CallCE
10485 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10486 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10487 return CheckEvalInICE(E, Ctx);
10488 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10489 if (CondResult.Kind == IK_NotICE)
10492 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10493 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10495 if (TrueResult.Kind == IK_NotICE)
10497 if (FalseResult.Kind == IK_NotICE)
10498 return FalseResult;
10499 if (CondResult.Kind == IK_ICEIfUnevaluated)
10501 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10503 // Rare case where the diagnostics depend on which side is evaluated
10504 // Note that if we get here, CondResult is 0, and at least one of
10505 // TrueResult and FalseResult is non-zero.
10506 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10507 return FalseResult;
10510 case Expr::CXXDefaultArgExprClass:
10511 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10512 case Expr::CXXDefaultInitExprClass:
10513 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10514 case Expr::ChooseExprClass: {
10515 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10519 llvm_unreachable("Invalid StmtClass!");
10522 /// Evaluate an expression as a C++11 integral constant expression.
10523 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10525 llvm::APSInt *Value,
10526 SourceLocation *Loc) {
10527 if (!E->getType()->isIntegralOrEnumerationType()) {
10528 if (Loc) *Loc = E->getExprLoc();
10533 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10536 if (!Result.isInt()) {
10537 if (Loc) *Loc = E->getExprLoc();
10541 if (Value) *Value = Result.getInt();
10545 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10546 SourceLocation *Loc) const {
10547 if (Ctx.getLangOpts().CPlusPlus11)
10548 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10550 ICEDiag D = CheckICE(this, Ctx);
10551 if (D.Kind != IK_ICE) {
10552 if (Loc) *Loc = D.Loc;
10558 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10559 SourceLocation *Loc, bool isEvaluated) const {
10560 if (Ctx.getLangOpts().CPlusPlus11)
10561 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10563 if (!isIntegerConstantExpr(Ctx, Loc))
10565 // The only possible side-effects here are due to UB discovered in the
10566 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10567 // required to treat the expression as an ICE, so we produce the folded
10569 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10570 llvm_unreachable("ICE cannot be evaluated!");
10574 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10575 return CheckICE(this, Ctx).Kind == IK_ICE;
10578 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10579 SourceLocation *Loc) const {
10580 // We support this checking in C++98 mode in order to diagnose compatibility
10582 assert(Ctx.getLangOpts().CPlusPlus);
10584 // Build evaluation settings.
10585 Expr::EvalStatus Status;
10586 SmallVector<PartialDiagnosticAt, 8> Diags;
10587 Status.Diag = &Diags;
10588 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10591 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10593 if (!Diags.empty()) {
10594 IsConstExpr = false;
10595 if (Loc) *Loc = Diags[0].first;
10596 } else if (!IsConstExpr) {
10597 // FIXME: This shouldn't happen.
10598 if (Loc) *Loc = getExprLoc();
10601 return IsConstExpr;
10604 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10605 const FunctionDecl *Callee,
10606 ArrayRef<const Expr*> Args,
10607 const Expr *This) const {
10608 Expr::EvalStatus Status;
10609 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10612 const LValue *ThisPtr = nullptr;
10615 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10616 assert(MD && "Don't provide `this` for non-methods.");
10617 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10619 if (EvaluateObjectArgument(Info, This, ThisVal))
10620 ThisPtr = &ThisVal;
10621 if (Info.EvalStatus.HasSideEffects)
10625 ArgVector ArgValues(Args.size());
10626 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10628 if ((*I)->isValueDependent() ||
10629 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10630 // If evaluation fails, throw away the argument entirely.
10631 ArgValues[I - Args.begin()] = APValue();
10632 if (Info.EvalStatus.HasSideEffects)
10636 // Build fake call to Callee.
10637 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10639 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10642 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10644 PartialDiagnosticAt> &Diags) {
10645 // FIXME: It would be useful to check constexpr function templates, but at the
10646 // moment the constant expression evaluator cannot cope with the non-rigorous
10647 // ASTs which we build for dependent expressions.
10648 if (FD->isDependentContext())
10651 Expr::EvalStatus Status;
10652 Status.Diag = &Diags;
10654 EvalInfo Info(FD->getASTContext(), Status,
10655 EvalInfo::EM_PotentialConstantExpression);
10657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10658 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10660 // Fabricate an arbitrary expression on the stack and pretend that it
10661 // is a temporary being used as the 'this' pointer.
10663 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10664 This.set(&VIE, Info.CurrentCall->Index);
10666 ArrayRef<const Expr*> Args;
10669 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10670 // Evaluate the call as a constant initializer, to allow the construction
10671 // of objects of non-literal types.
10672 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10673 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10675 SourceLocation Loc = FD->getLocation();
10676 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10677 Args, FD->getBody(), Info, Scratch, nullptr);
10680 return Diags.empty();
10683 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10684 const FunctionDecl *FD,
10686 PartialDiagnosticAt> &Diags) {
10687 Expr::EvalStatus Status;
10688 Status.Diag = &Diags;
10690 EvalInfo Info(FD->getASTContext(), Status,
10691 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10693 // Fabricate a call stack frame to give the arguments a plausible cover story.
10694 ArrayRef<const Expr*> Args;
10695 ArgVector ArgValues(0);
10696 bool Success = EvaluateArgs(Args, ArgValues, Info);
10699 "Failed to set up arguments for potential constant evaluation");
10700 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10702 APValue ResultScratch;
10703 Evaluate(ResultScratch, Info, E);
10704 return Diags.empty();
10707 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10708 unsigned Type) const {
10709 if (!getType()->isPointerType())
10712 Expr::EvalStatus Status;
10713 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10714 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);