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, uint64_t N);
354 /// Add N to the address of this subobject.
355 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
357 if (isMostDerivedAnUnsizedArray()) {
358 // Can't verify -- trust that the user is doing the right thing (or if
359 // not, trust that the caller will catch the bad behavior).
360 Entries.back().ArrayIndex += N;
363 if (MostDerivedPathLength == Entries.size() &&
364 MostDerivedIsArrayElement) {
365 Entries.back().ArrayIndex += N;
366 if (Entries.back().ArrayIndex > getMostDerivedArraySize()) {
367 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
372 // [expr.add]p4: For the purposes of these operators, a pointer to a
373 // nonarray object behaves the same as a pointer to the first element of
374 // an array of length one with the type of the object as its element type.
375 if (IsOnePastTheEnd && N == (uint64_t)-1)
376 IsOnePastTheEnd = false;
377 else if (!IsOnePastTheEnd && N == 1)
378 IsOnePastTheEnd = true;
380 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
386 /// A stack frame in the constexpr call stack.
387 struct CallStackFrame {
390 /// Parent - The caller of this stack frame.
391 CallStackFrame *Caller;
393 /// Callee - The function which was called.
394 const FunctionDecl *Callee;
396 /// This - The binding for the this pointer in this call, if any.
399 /// Arguments - Parameter bindings for this function call, indexed by
400 /// parameters' function scope indices.
403 // Note that we intentionally use std::map here so that references to
404 // values are stable.
405 typedef std::map<const void*, APValue> MapTy;
406 typedef MapTy::const_iterator temp_iterator;
407 /// Temporaries - Temporary lvalues materialized within this stack frame.
410 /// CallLoc - The location of the call expression for this call.
411 SourceLocation CallLoc;
413 /// Index - The call index of this call.
416 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
417 const FunctionDecl *Callee, const LValue *This,
421 APValue *getTemporary(const void *Key) {
422 MapTy::iterator I = Temporaries.find(Key);
423 return I == Temporaries.end() ? nullptr : &I->second;
425 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
428 /// Temporarily override 'this'.
429 class ThisOverrideRAII {
431 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
432 : Frame(Frame), OldThis(Frame.This) {
434 Frame.This = NewThis;
436 ~ThisOverrideRAII() {
437 Frame.This = OldThis;
440 CallStackFrame &Frame;
441 const LValue *OldThis;
444 /// A partial diagnostic which we might know in advance that we are not going
446 class OptionalDiagnostic {
447 PartialDiagnostic *Diag;
450 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
454 OptionalDiagnostic &operator<<(const T &v) {
460 OptionalDiagnostic &operator<<(const APSInt &I) {
462 SmallVector<char, 32> Buffer;
464 *Diag << StringRef(Buffer.data(), Buffer.size());
469 OptionalDiagnostic &operator<<(const APFloat &F) {
471 // FIXME: Force the precision of the source value down so we don't
472 // print digits which are usually useless (we don't really care here if
473 // we truncate a digit by accident in edge cases). Ideally,
474 // APFloat::toString would automatically print the shortest
475 // representation which rounds to the correct value, but it's a bit
476 // tricky to implement.
478 llvm::APFloat::semanticsPrecision(F.getSemantics());
479 precision = (precision * 59 + 195) / 196;
480 SmallVector<char, 32> Buffer;
481 F.toString(Buffer, precision);
482 *Diag << StringRef(Buffer.data(), Buffer.size());
488 /// A cleanup, and a flag indicating whether it is lifetime-extended.
490 llvm::PointerIntPair<APValue*, 1, bool> Value;
493 Cleanup(APValue *Val, bool IsLifetimeExtended)
494 : Value(Val, IsLifetimeExtended) {}
496 bool isLifetimeExtended() const { return Value.getInt(); }
498 *Value.getPointer() = APValue();
502 /// EvalInfo - This is a private struct used by the evaluator to capture
503 /// information about a subexpression as it is folded. It retains information
504 /// about the AST context, but also maintains information about the folded
507 /// If an expression could be evaluated, it is still possible it is not a C
508 /// "integer constant expression" or constant expression. If not, this struct
509 /// captures information about how and why not.
511 /// One bit of information passed *into* the request for constant folding
512 /// indicates whether the subexpression is "evaluated" or not according to C
513 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
514 /// evaluate the expression regardless of what the RHS is, but C only allows
515 /// certain things in certain situations.
516 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
519 /// EvalStatus - Contains information about the evaluation.
520 Expr::EvalStatus &EvalStatus;
522 /// CurrentCall - The top of the constexpr call stack.
523 CallStackFrame *CurrentCall;
525 /// CallStackDepth - The number of calls in the call stack right now.
526 unsigned CallStackDepth;
528 /// NextCallIndex - The next call index to assign.
529 unsigned NextCallIndex;
531 /// StepsLeft - The remaining number of evaluation steps we're permitted
532 /// to perform. This is essentially a limit for the number of statements
533 /// we will evaluate.
536 /// BottomFrame - The frame in which evaluation started. This must be
537 /// initialized after CurrentCall and CallStackDepth.
538 CallStackFrame BottomFrame;
540 /// A stack of values whose lifetimes end at the end of some surrounding
541 /// evaluation frame.
542 llvm::SmallVector<Cleanup, 16> CleanupStack;
544 /// EvaluatingDecl - This is the declaration whose initializer is being
545 /// evaluated, if any.
546 APValue::LValueBase EvaluatingDecl;
548 /// EvaluatingDeclValue - This is the value being constructed for the
549 /// declaration whose initializer is being evaluated, if any.
550 APValue *EvaluatingDeclValue;
552 /// The current array initialization index, if we're performing array
554 uint64_t ArrayInitIndex = -1;
556 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
557 /// notes attached to it will also be stored, otherwise they will not be.
558 bool HasActiveDiagnostic;
560 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
561 /// fold (not just why it's not strictly a constant expression)?
562 bool HasFoldFailureDiagnostic;
564 /// \brief Whether or not we're currently speculatively evaluating.
565 bool IsSpeculativelyEvaluating;
567 enum EvaluationMode {
568 /// Evaluate as a constant expression. Stop if we find that the expression
569 /// is not a constant expression.
570 EM_ConstantExpression,
572 /// Evaluate as a potential constant expression. Keep going if we hit a
573 /// construct that we can't evaluate yet (because we don't yet know the
574 /// value of something) but stop if we hit something that could never be
575 /// a constant expression.
576 EM_PotentialConstantExpression,
578 /// Fold the expression to a constant. Stop if we hit a side-effect that
582 /// Evaluate the expression looking for integer overflow and similar
583 /// issues. Don't worry about side-effects, and try to visit all
585 EM_EvaluateForOverflow,
587 /// Evaluate in any way we know how. Don't worry about side-effects that
588 /// can't be modeled.
589 EM_IgnoreSideEffects,
591 /// Evaluate as a constant expression. Stop if we find that the expression
592 /// is not a constant expression. Some expressions can be retried in the
593 /// optimizer if we don't constant fold them here, but in an unevaluated
594 /// context we try to fold them immediately since the optimizer never
595 /// gets a chance to look at it.
596 EM_ConstantExpressionUnevaluated,
598 /// Evaluate as a potential constant expression. Keep going if we hit a
599 /// construct that we can't evaluate yet (because we don't yet know the
600 /// value of something) but stop if we hit something that could never be
601 /// a constant expression. Some expressions can be retried in the
602 /// optimizer if we don't constant fold them here, but in an unevaluated
603 /// context we try to fold them immediately since the optimizer never
604 /// gets a chance to look at it.
605 EM_PotentialConstantExpressionUnevaluated,
607 /// Evaluate as a constant expression. Continue evaluating if either:
608 /// - We find a MemberExpr with a base that can't be evaluated.
609 /// - We find a variable initialized with a call to a function that has
610 /// the alloc_size attribute on it.
611 /// In either case, the LValue returned shall have an invalid base; in the
612 /// former, the base will be the invalid MemberExpr, in the latter, the
613 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
618 /// Are we checking whether the expression is a potential constant
620 bool checkingPotentialConstantExpression() const {
621 return EvalMode == EM_PotentialConstantExpression ||
622 EvalMode == EM_PotentialConstantExpressionUnevaluated;
625 /// Are we checking an expression for overflow?
626 // FIXME: We should check for any kind of undefined or suspicious behavior
627 // in such constructs, not just overflow.
628 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
630 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
631 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
632 CallStackDepth(0), NextCallIndex(1),
633 StepsLeft(getLangOpts().ConstexprStepLimit),
634 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
635 EvaluatingDecl((const ValueDecl *)nullptr),
636 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
637 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
640 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
641 EvaluatingDecl = Base;
642 EvaluatingDeclValue = &Value;
645 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
647 bool CheckCallLimit(SourceLocation Loc) {
648 // Don't perform any constexpr calls (other than the call we're checking)
649 // when checking a potential constant expression.
650 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
652 if (NextCallIndex == 0) {
653 // NextCallIndex has wrapped around.
654 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
657 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
659 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
660 << getLangOpts().ConstexprCallDepth;
664 CallStackFrame *getCallFrame(unsigned CallIndex) {
665 assert(CallIndex && "no call index in getCallFrame");
666 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
667 // be null in this loop.
668 CallStackFrame *Frame = CurrentCall;
669 while (Frame->Index > CallIndex)
670 Frame = Frame->Caller;
671 return (Frame->Index == CallIndex) ? Frame : nullptr;
674 bool nextStep(const Stmt *S) {
676 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
684 /// Add a diagnostic to the diagnostics list.
685 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
686 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
687 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
688 return EvalStatus.Diag->back().second;
691 /// Add notes containing a call stack to the current point of evaluation.
692 void addCallStack(unsigned Limit);
695 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
696 unsigned ExtraNotes, bool IsCCEDiag) {
698 if (EvalStatus.Diag) {
699 // If we have a prior diagnostic, it will be noting that the expression
700 // isn't a constant expression. This diagnostic is more important,
701 // unless we require this evaluation to produce a constant expression.
703 // FIXME: We might want to show both diagnostics to the user in
704 // EM_ConstantFold mode.
705 if (!EvalStatus.Diag->empty()) {
707 case EM_ConstantFold:
708 case EM_IgnoreSideEffects:
709 case EM_EvaluateForOverflow:
710 if (!HasFoldFailureDiagnostic)
712 // We've already failed to fold something. Keep that diagnostic.
713 case EM_ConstantExpression:
714 case EM_PotentialConstantExpression:
715 case EM_ConstantExpressionUnevaluated:
716 case EM_PotentialConstantExpressionUnevaluated:
718 HasActiveDiagnostic = false;
719 return OptionalDiagnostic();
723 unsigned CallStackNotes = CallStackDepth - 1;
724 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
726 CallStackNotes = std::min(CallStackNotes, Limit + 1);
727 if (checkingPotentialConstantExpression())
730 HasActiveDiagnostic = true;
731 HasFoldFailureDiagnostic = !IsCCEDiag;
732 EvalStatus.Diag->clear();
733 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
734 addDiag(Loc, DiagId);
735 if (!checkingPotentialConstantExpression())
737 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
739 HasActiveDiagnostic = false;
740 return OptionalDiagnostic();
743 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
745 FFDiag(SourceLocation Loc,
746 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
747 unsigned ExtraNotes = 0) {
748 return Diag(Loc, DiagId, ExtraNotes, false);
751 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
752 = diag::note_invalid_subexpr_in_const_expr,
753 unsigned ExtraNotes = 0) {
755 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
756 HasActiveDiagnostic = false;
757 return OptionalDiagnostic();
760 /// Diagnose that the evaluation does not produce a C++11 core constant
763 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
764 /// EM_PotentialConstantExpression mode and we produce one of these.
765 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
766 = diag::note_invalid_subexpr_in_const_expr,
767 unsigned ExtraNotes = 0) {
768 // Don't override a previous diagnostic. Don't bother collecting
769 // diagnostics if we're evaluating for overflow.
770 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
771 HasActiveDiagnostic = false;
772 return OptionalDiagnostic();
774 return Diag(Loc, DiagId, ExtraNotes, true);
776 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
777 = diag::note_invalid_subexpr_in_const_expr,
778 unsigned ExtraNotes = 0) {
779 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
781 /// Add a note to a prior diagnostic.
782 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
783 if (!HasActiveDiagnostic)
784 return OptionalDiagnostic();
785 return OptionalDiagnostic(&addDiag(Loc, DiagId));
788 /// Add a stack of notes to a prior diagnostic.
789 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
790 if (HasActiveDiagnostic) {
791 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
792 Diags.begin(), Diags.end());
796 /// Should we continue evaluation after encountering a side-effect that we
798 bool keepEvaluatingAfterSideEffect() {
800 case EM_PotentialConstantExpression:
801 case EM_PotentialConstantExpressionUnevaluated:
802 case EM_EvaluateForOverflow:
803 case EM_IgnoreSideEffects:
806 case EM_ConstantExpression:
807 case EM_ConstantExpressionUnevaluated:
808 case EM_ConstantFold:
812 llvm_unreachable("Missed EvalMode case");
815 /// Note that we have had a side-effect, and determine whether we should
817 bool noteSideEffect() {
818 EvalStatus.HasSideEffects = true;
819 return keepEvaluatingAfterSideEffect();
822 /// Should we continue evaluation after encountering undefined behavior?
823 bool keepEvaluatingAfterUndefinedBehavior() {
825 case EM_EvaluateForOverflow:
826 case EM_IgnoreSideEffects:
827 case EM_ConstantFold:
831 case EM_PotentialConstantExpression:
832 case EM_PotentialConstantExpressionUnevaluated:
833 case EM_ConstantExpression:
834 case EM_ConstantExpressionUnevaluated:
837 llvm_unreachable("Missed EvalMode case");
840 /// Note that we hit something that was technically undefined behavior, but
841 /// that we can evaluate past it (such as signed overflow or floating-point
842 /// division by zero.)
843 bool noteUndefinedBehavior() {
844 EvalStatus.HasUndefinedBehavior = true;
845 return keepEvaluatingAfterUndefinedBehavior();
848 /// Should we continue evaluation as much as possible after encountering a
849 /// construct which can't be reduced to a value?
850 bool keepEvaluatingAfterFailure() {
855 case EM_PotentialConstantExpression:
856 case EM_PotentialConstantExpressionUnevaluated:
857 case EM_EvaluateForOverflow:
860 case EM_ConstantExpression:
861 case EM_ConstantExpressionUnevaluated:
862 case EM_ConstantFold:
863 case EM_IgnoreSideEffects:
867 llvm_unreachable("Missed EvalMode case");
870 /// Notes that we failed to evaluate an expression that other expressions
871 /// directly depend on, and determine if we should keep evaluating. This
872 /// should only be called if we actually intend to keep evaluating.
874 /// Call noteSideEffect() instead if we may be able to ignore the value that
875 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
877 /// (Foo(), 1) // use noteSideEffect
878 /// (Foo() || true) // use noteSideEffect
879 /// Foo() + 1 // use noteFailure
880 LLVM_NODISCARD bool noteFailure() {
881 // Failure when evaluating some expression often means there is some
882 // subexpression whose evaluation was skipped. Therefore, (because we
883 // don't track whether we skipped an expression when unwinding after an
884 // evaluation failure) every evaluation failure that bubbles up from a
885 // subexpression implies that a side-effect has potentially happened. We
886 // skip setting the HasSideEffects flag to true until we decide to
887 // continue evaluating after that point, which happens here.
888 bool KeepGoing = keepEvaluatingAfterFailure();
889 EvalStatus.HasSideEffects |= KeepGoing;
893 bool allowInvalidBaseExpr() const {
894 return EvalMode == EM_OffsetFold;
897 class ArrayInitLoopIndex {
902 ArrayInitLoopIndex(EvalInfo &Info)
903 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
904 Info.ArrayInitIndex = 0;
906 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
908 operator uint64_t&() { return Info.ArrayInitIndex; }
912 /// Object used to treat all foldable expressions as constant expressions.
913 struct FoldConstant {
916 bool HadNoPriorDiags;
917 EvalInfo::EvaluationMode OldMode;
919 explicit FoldConstant(EvalInfo &Info, bool Enabled)
922 HadNoPriorDiags(Info.EvalStatus.Diag &&
923 Info.EvalStatus.Diag->empty() &&
924 !Info.EvalStatus.HasSideEffects),
925 OldMode(Info.EvalMode) {
927 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
928 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
929 Info.EvalMode = EvalInfo::EM_ConstantFold;
931 void keepDiagnostics() { Enabled = false; }
933 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
934 !Info.EvalStatus.HasSideEffects)
935 Info.EvalStatus.Diag->clear();
936 Info.EvalMode = OldMode;
940 /// RAII object used to treat the current evaluation as the correct pointer
941 /// offset fold for the current EvalMode
942 struct FoldOffsetRAII {
944 EvalInfo::EvaluationMode OldMode;
945 explicit FoldOffsetRAII(EvalInfo &Info)
946 : Info(Info), OldMode(Info.EvalMode) {
947 if (!Info.checkingPotentialConstantExpression())
948 Info.EvalMode = EvalInfo::EM_OffsetFold;
951 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
954 /// RAII object used to optionally suppress diagnostics and side-effects from
955 /// a speculative evaluation.
956 class SpeculativeEvaluationRAII {
957 /// Pair of EvalInfo, and a bit that stores whether or not we were
958 /// speculatively evaluating when we created this RAII.
959 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
960 Expr::EvalStatus Old;
962 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
963 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
965 Other.InfoAndOldSpecEval.setPointer(nullptr);
968 void maybeRestoreState() {
969 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
973 Info->EvalStatus = Old;
974 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
978 SpeculativeEvaluationRAII() = default;
980 SpeculativeEvaluationRAII(
981 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
982 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
983 Old(Info.EvalStatus) {
984 Info.EvalStatus.Diag = NewDiag;
985 Info.IsSpeculativelyEvaluating = true;
988 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
989 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
990 moveFromAndCancel(std::move(Other));
993 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
995 moveFromAndCancel(std::move(Other));
999 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1002 /// RAII object wrapping a full-expression or block scope, and handling
1003 /// the ending of the lifetime of temporaries created within it.
1004 template<bool IsFullExpression>
1007 unsigned OldStackSize;
1009 ScopeRAII(EvalInfo &Info)
1010 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1012 // Body moved to a static method to encourage the compiler to inline away
1013 // instances of this class.
1014 cleanup(Info, OldStackSize);
1017 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1018 unsigned NewEnd = OldStackSize;
1019 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1021 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1022 // Full-expression cleanup of a lifetime-extended temporary: nothing
1023 // to do, just move this cleanup to the right place in the stack.
1024 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1027 // End the lifetime of the object.
1028 Info.CleanupStack[I].endLifetime();
1031 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1032 Info.CleanupStack.end());
1035 typedef ScopeRAII<false> BlockScopeRAII;
1036 typedef ScopeRAII<true> FullExpressionRAII;
1039 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1040 CheckSubobjectKind CSK) {
1043 if (isOnePastTheEnd()) {
1044 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1052 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1053 const Expr *E, uint64_t N) {
1054 // If we're complaining, we must be able to statically determine the size of
1055 // the most derived array.
1056 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1057 Info.CCEDiag(E, diag::note_constexpr_array_index)
1058 << static_cast<int>(N) << /*array*/ 0
1059 << static_cast<unsigned>(getMostDerivedArraySize());
1061 Info.CCEDiag(E, diag::note_constexpr_array_index)
1062 << static_cast<int>(N) << /*non-array*/ 1;
1066 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1067 const FunctionDecl *Callee, const LValue *This,
1069 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1070 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1071 Info.CurrentCall = this;
1072 ++Info.CallStackDepth;
1075 CallStackFrame::~CallStackFrame() {
1076 assert(Info.CurrentCall == this && "calls retired out of order");
1077 --Info.CallStackDepth;
1078 Info.CurrentCall = Caller;
1081 APValue &CallStackFrame::createTemporary(const void *Key,
1082 bool IsLifetimeExtended) {
1083 APValue &Result = Temporaries[Key];
1084 assert(Result.isUninit() && "temporary created multiple times");
1085 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1089 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1091 void EvalInfo::addCallStack(unsigned Limit) {
1092 // Determine which calls to skip, if any.
1093 unsigned ActiveCalls = CallStackDepth - 1;
1094 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1095 if (Limit && Limit < ActiveCalls) {
1096 SkipStart = Limit / 2 + Limit % 2;
1097 SkipEnd = ActiveCalls - Limit / 2;
1100 // Walk the call stack and add the diagnostics.
1101 unsigned CallIdx = 0;
1102 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1103 Frame = Frame->Caller, ++CallIdx) {
1105 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1106 if (CallIdx == SkipStart) {
1107 // Note that we're skipping calls.
1108 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1109 << unsigned(ActiveCalls - Limit);
1114 // Use a different note for an inheriting constructor, because from the
1115 // user's perspective it's not really a function at all.
1116 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1117 if (CD->isInheritingConstructor()) {
1118 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1124 SmallVector<char, 128> Buffer;
1125 llvm::raw_svector_ostream Out(Buffer);
1126 describeCall(Frame, Out);
1127 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1132 struct ComplexValue {
1137 APSInt IntReal, IntImag;
1138 APFloat FloatReal, FloatImag;
1140 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1142 void makeComplexFloat() { IsInt = false; }
1143 bool isComplexFloat() const { return !IsInt; }
1144 APFloat &getComplexFloatReal() { return FloatReal; }
1145 APFloat &getComplexFloatImag() { return FloatImag; }
1147 void makeComplexInt() { IsInt = true; }
1148 bool isComplexInt() const { return IsInt; }
1149 APSInt &getComplexIntReal() { return IntReal; }
1150 APSInt &getComplexIntImag() { return IntImag; }
1152 void moveInto(APValue &v) const {
1153 if (isComplexFloat())
1154 v = APValue(FloatReal, FloatImag);
1156 v = APValue(IntReal, IntImag);
1158 void setFrom(const APValue &v) {
1159 assert(v.isComplexFloat() || v.isComplexInt());
1160 if (v.isComplexFloat()) {
1162 FloatReal = v.getComplexFloatReal();
1163 FloatImag = v.getComplexFloatImag();
1166 IntReal = v.getComplexIntReal();
1167 IntImag = v.getComplexIntImag();
1173 APValue::LValueBase Base;
1175 unsigned InvalidBase : 1;
1176 unsigned CallIndex : 31;
1177 SubobjectDesignator Designator;
1180 const APValue::LValueBase getLValueBase() const { return Base; }
1181 CharUnits &getLValueOffset() { return Offset; }
1182 const CharUnits &getLValueOffset() const { return Offset; }
1183 unsigned getLValueCallIndex() const { return CallIndex; }
1184 SubobjectDesignator &getLValueDesignator() { return Designator; }
1185 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1186 bool isNullPointer() const { return IsNullPtr;}
1188 void moveInto(APValue &V) const {
1189 if (Designator.Invalid)
1190 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1193 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1194 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1195 "Unsized array with a valid base?");
1196 V = APValue(Base, Offset, Designator.Entries,
1197 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1200 void setFrom(ASTContext &Ctx, const APValue &V) {
1201 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1202 Base = V.getLValueBase();
1203 Offset = V.getLValueOffset();
1204 InvalidBase = false;
1205 CallIndex = V.getLValueCallIndex();
1206 Designator = SubobjectDesignator(Ctx, V);
1207 IsNullPtr = V.isNullPointer();
1210 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false,
1211 bool IsNullPtr_ = false, uint64_t Offset_ = 0) {
1213 // We only allow a few types of invalid bases. Enforce that here.
1215 const auto *E = B.get<const Expr *>();
1216 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1217 "Unexpected type of invalid base");
1222 Offset = CharUnits::fromQuantity(Offset_);
1223 InvalidBase = BInvalid;
1225 Designator = SubobjectDesignator(getType(B));
1226 IsNullPtr = IsNullPtr_;
1229 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1233 // Check that this LValue is not based on a null pointer. If it is, produce
1234 // a diagnostic and mark the designator as invalid.
1235 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1236 CheckSubobjectKind CSK) {
1237 if (Designator.Invalid)
1240 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1242 Designator.setInvalid();
1248 // Check this LValue refers to an object. If not, set the designator to be
1249 // invalid and emit a diagnostic.
1250 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1251 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1252 Designator.checkSubobject(Info, E, CSK);
1255 void addDecl(EvalInfo &Info, const Expr *E,
1256 const Decl *D, bool Virtual = false) {
1257 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1258 Designator.addDeclUnchecked(D, Virtual);
1260 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1261 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1262 assert(isBaseAnAllocSizeCall(Base) &&
1263 "Only alloc_size bases can have unsized arrays");
1264 Designator.FirstEntryIsAnUnsizedArray = true;
1265 Designator.addUnsizedArrayUnchecked(ElemTy);
1267 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1268 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1269 Designator.addArrayUnchecked(CAT);
1271 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1272 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1273 Designator.addComplexUnchecked(EltTy, Imag);
1275 void clearIsNullPointer() {
1278 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E, uint64_t Index,
1279 CharUnits ElementSize) {
1280 // Compute the new offset in the appropriate width.
1281 Offset += Index * ElementSize;
1282 if (Index && checkNullPointer(Info, E, CSK_ArrayIndex))
1283 Designator.adjustIndex(Info, E, Index);
1285 clearIsNullPointer();
1287 void adjustOffset(CharUnits N) {
1289 if (N.getQuantity())
1290 clearIsNullPointer();
1296 explicit MemberPtr(const ValueDecl *Decl) :
1297 DeclAndIsDerivedMember(Decl, false), Path() {}
1299 /// The member or (direct or indirect) field referred to by this member
1300 /// pointer, or 0 if this is a null member pointer.
1301 const ValueDecl *getDecl() const {
1302 return DeclAndIsDerivedMember.getPointer();
1304 /// Is this actually a member of some type derived from the relevant class?
1305 bool isDerivedMember() const {
1306 return DeclAndIsDerivedMember.getInt();
1308 /// Get the class which the declaration actually lives in.
1309 const CXXRecordDecl *getContainingRecord() const {
1310 return cast<CXXRecordDecl>(
1311 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1314 void moveInto(APValue &V) const {
1315 V = APValue(getDecl(), isDerivedMember(), Path);
1317 void setFrom(const APValue &V) {
1318 assert(V.isMemberPointer());
1319 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1320 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1322 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1323 Path.insert(Path.end(), P.begin(), P.end());
1326 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1327 /// whether the member is a member of some class derived from the class type
1328 /// of the member pointer.
1329 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1330 /// Path - The path of base/derived classes from the member declaration's
1331 /// class (exclusive) to the class type of the member pointer (inclusive).
1332 SmallVector<const CXXRecordDecl*, 4> Path;
1334 /// Perform a cast towards the class of the Decl (either up or down the
1336 bool castBack(const CXXRecordDecl *Class) {
1337 assert(!Path.empty());
1338 const CXXRecordDecl *Expected;
1339 if (Path.size() >= 2)
1340 Expected = Path[Path.size() - 2];
1342 Expected = getContainingRecord();
1343 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1344 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1345 // if B does not contain the original member and is not a base or
1346 // derived class of the class containing the original member, the result
1347 // of the cast is undefined.
1348 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1349 // (D::*). We consider that to be a language defect.
1355 /// Perform a base-to-derived member pointer cast.
1356 bool castToDerived(const CXXRecordDecl *Derived) {
1359 if (!isDerivedMember()) {
1360 Path.push_back(Derived);
1363 if (!castBack(Derived))
1366 DeclAndIsDerivedMember.setInt(false);
1369 /// Perform a derived-to-base member pointer cast.
1370 bool castToBase(const CXXRecordDecl *Base) {
1374 DeclAndIsDerivedMember.setInt(true);
1375 if (isDerivedMember()) {
1376 Path.push_back(Base);
1379 return castBack(Base);
1383 /// Compare two member pointers, which are assumed to be of the same type.
1384 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1385 if (!LHS.getDecl() || !RHS.getDecl())
1386 return !LHS.getDecl() && !RHS.getDecl();
1387 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1389 return LHS.Path == RHS.Path;
1393 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1394 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1395 const LValue &This, const Expr *E,
1396 bool AllowNonLiteralTypes = false);
1397 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1398 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1399 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1401 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1402 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1403 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1405 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1406 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1407 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1408 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1410 //===----------------------------------------------------------------------===//
1412 //===----------------------------------------------------------------------===//
1414 /// Produce a string describing the given constexpr call.
1415 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1416 unsigned ArgIndex = 0;
1417 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1418 !isa<CXXConstructorDecl>(Frame->Callee) &&
1419 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1422 Out << *Frame->Callee << '(';
1424 if (Frame->This && IsMemberCall) {
1426 Frame->This->moveInto(Val);
1427 Val.printPretty(Out, Frame->Info.Ctx,
1428 Frame->This->Designator.MostDerivedType);
1429 // FIXME: Add parens around Val if needed.
1430 Out << "->" << *Frame->Callee << '(';
1431 IsMemberCall = false;
1434 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1435 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1436 if (ArgIndex > (unsigned)IsMemberCall)
1439 const ParmVarDecl *Param = *I;
1440 const APValue &Arg = Frame->Arguments[ArgIndex];
1441 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1443 if (ArgIndex == 0 && IsMemberCall)
1444 Out << "->" << *Frame->Callee << '(';
1450 /// Evaluate an expression to see if it had side-effects, and discard its
1452 /// \return \c true if the caller should keep evaluating.
1453 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1455 if (!Evaluate(Scratch, Info, E))
1456 // We don't need the value, but we might have skipped a side effect here.
1457 return Info.noteSideEffect();
1461 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1462 /// return its existing value.
1463 static int64_t getExtValue(const APSInt &Value) {
1464 return Value.isSigned() ? Value.getSExtValue()
1465 : static_cast<int64_t>(Value.getZExtValue());
1468 /// Should this call expression be treated as a string literal?
1469 static bool IsStringLiteralCall(const CallExpr *E) {
1470 unsigned Builtin = E->getBuiltinCallee();
1471 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1472 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1475 static bool IsGlobalLValue(APValue::LValueBase B) {
1476 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1477 // constant expression of pointer type that evaluates to...
1479 // ... a null pointer value, or a prvalue core constant expression of type
1481 if (!B) return true;
1483 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1484 // ... the address of an object with static storage duration,
1485 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1486 return VD->hasGlobalStorage();
1487 // ... the address of a function,
1488 return isa<FunctionDecl>(D);
1491 const Expr *E = B.get<const Expr*>();
1492 switch (E->getStmtClass()) {
1495 case Expr::CompoundLiteralExprClass: {
1496 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1497 return CLE->isFileScope() && CLE->isLValue();
1499 case Expr::MaterializeTemporaryExprClass:
1500 // A materialized temporary might have been lifetime-extended to static
1501 // storage duration.
1502 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1503 // A string literal has static storage duration.
1504 case Expr::StringLiteralClass:
1505 case Expr::PredefinedExprClass:
1506 case Expr::ObjCStringLiteralClass:
1507 case Expr::ObjCEncodeExprClass:
1508 case Expr::CXXTypeidExprClass:
1509 case Expr::CXXUuidofExprClass:
1511 case Expr::CallExprClass:
1512 return IsStringLiteralCall(cast<CallExpr>(E));
1513 // For GCC compatibility, &&label has static storage duration.
1514 case Expr::AddrLabelExprClass:
1516 // A Block literal expression may be used as the initialization value for
1517 // Block variables at global or local static scope.
1518 case Expr::BlockExprClass:
1519 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1520 case Expr::ImplicitValueInitExprClass:
1522 // We can never form an lvalue with an implicit value initialization as its
1523 // base through expression evaluation, so these only appear in one case: the
1524 // implicit variable declaration we invent when checking whether a constexpr
1525 // constructor can produce a constant expression. We must assume that such
1526 // an expression might be a global lvalue.
1531 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1532 assert(Base && "no location for a null lvalue");
1533 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1535 Info.Note(VD->getLocation(), diag::note_declared_at);
1537 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1538 diag::note_constexpr_temporary_here);
1541 /// Check that this reference or pointer core constant expression is a valid
1542 /// value for an address or reference constant expression. Return true if we
1543 /// can fold this expression, whether or not it's a constant expression.
1544 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1545 QualType Type, const LValue &LVal) {
1546 bool IsReferenceType = Type->isReferenceType();
1548 APValue::LValueBase Base = LVal.getLValueBase();
1549 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1551 // Check that the object is a global. Note that the fake 'this' object we
1552 // manufacture when checking potential constant expressions is conservatively
1553 // assumed to be global here.
1554 if (!IsGlobalLValue(Base)) {
1555 if (Info.getLangOpts().CPlusPlus11) {
1556 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1557 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1558 << IsReferenceType << !Designator.Entries.empty()
1560 NoteLValueLocation(Info, Base);
1564 // Don't allow references to temporaries to escape.
1567 assert((Info.checkingPotentialConstantExpression() ||
1568 LVal.getLValueCallIndex() == 0) &&
1569 "have call index for global lvalue");
1571 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1572 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1573 // Check if this is a thread-local variable.
1574 if (Var->getTLSKind())
1577 // A dllimport variable never acts like a constant.
1578 if (Var->hasAttr<DLLImportAttr>())
1581 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1582 // __declspec(dllimport) must be handled very carefully:
1583 // We must never initialize an expression with the thunk in C++.
1584 // Doing otherwise would allow the same id-expression to yield
1585 // different addresses for the same function in different translation
1586 // units. However, this means that we must dynamically initialize the
1587 // expression with the contents of the import address table at runtime.
1589 // The C language has no notion of ODR; furthermore, it has no notion of
1590 // dynamic initialization. This means that we are permitted to
1591 // perform initialization with the address of the thunk.
1592 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1597 // Allow address constant expressions to be past-the-end pointers. This is
1598 // an extension: the standard requires them to point to an object.
1599 if (!IsReferenceType)
1602 // A reference constant expression must refer to an object.
1604 // FIXME: diagnostic
1609 // Does this refer one past the end of some object?
1610 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1611 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1612 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1613 << !Designator.Entries.empty() << !!VD << VD;
1614 NoteLValueLocation(Info, Base);
1620 /// Check that this core constant expression is of literal type, and if not,
1621 /// produce an appropriate diagnostic.
1622 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1623 const LValue *This = nullptr) {
1624 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1627 // C++1y: A constant initializer for an object o [...] may also invoke
1628 // constexpr constructors for o and its subobjects even if those objects
1629 // are of non-literal class types.
1631 // C++11 missed this detail for aggregates, so classes like this:
1632 // struct foo_t { union { int i; volatile int j; } u; };
1633 // are not (obviously) initializable like so:
1634 // __attribute__((__require_constant_initialization__))
1635 // static const foo_t x = {{0}};
1636 // because "i" is a subobject with non-literal initialization (due to the
1637 // volatile member of the union). See:
1638 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1639 // Therefore, we use the C++1y behavior.
1640 if (This && Info.EvaluatingDecl == This->getLValueBase())
1643 // Prvalue constant expressions must be of literal types.
1644 if (Info.getLangOpts().CPlusPlus11)
1645 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1648 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1652 /// Check that this core constant expression value is a valid value for a
1653 /// constant expression. If not, report an appropriate diagnostic. Does not
1654 /// check that the expression is of literal type.
1655 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1656 QualType Type, const APValue &Value) {
1657 if (Value.isUninit()) {
1658 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1663 // We allow _Atomic(T) to be initialized from anything that T can be
1664 // initialized from.
1665 if (const AtomicType *AT = Type->getAs<AtomicType>())
1666 Type = AT->getValueType();
1668 // Core issue 1454: For a literal constant expression of array or class type,
1669 // each subobject of its value shall have been initialized by a constant
1671 if (Value.isArray()) {
1672 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1673 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1674 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1675 Value.getArrayInitializedElt(I)))
1678 if (!Value.hasArrayFiller())
1680 return CheckConstantExpression(Info, DiagLoc, EltTy,
1681 Value.getArrayFiller());
1683 if (Value.isUnion() && Value.getUnionField()) {
1684 return CheckConstantExpression(Info, DiagLoc,
1685 Value.getUnionField()->getType(),
1686 Value.getUnionValue());
1688 if (Value.isStruct()) {
1689 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1690 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1691 unsigned BaseIndex = 0;
1692 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1693 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1694 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1695 Value.getStructBase(BaseIndex)))
1699 for (const auto *I : RD->fields()) {
1700 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1701 Value.getStructField(I->getFieldIndex())))
1706 if (Value.isLValue()) {
1708 LVal.setFrom(Info.Ctx, Value);
1709 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1712 // Everything else is fine.
1716 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1717 return LVal.Base.dyn_cast<const ValueDecl*>();
1720 static bool IsLiteralLValue(const LValue &Value) {
1721 if (Value.CallIndex)
1723 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1724 return E && !isa<MaterializeTemporaryExpr>(E);
1727 static bool IsWeakLValue(const LValue &Value) {
1728 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1729 return Decl && Decl->isWeak();
1732 static bool isZeroSized(const LValue &Value) {
1733 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1734 if (Decl && isa<VarDecl>(Decl)) {
1735 QualType Ty = Decl->getType();
1736 if (Ty->isArrayType())
1737 return Ty->isIncompleteType() ||
1738 Decl->getASTContext().getTypeSize(Ty) == 0;
1743 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1744 // A null base expression indicates a null pointer. These are always
1745 // evaluatable, and they are false unless the offset is zero.
1746 if (!Value.getLValueBase()) {
1747 Result = !Value.getLValueOffset().isZero();
1751 // We have a non-null base. These are generally known to be true, but if it's
1752 // a weak declaration it can be null at runtime.
1754 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1755 return !Decl || !Decl->isWeak();
1758 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1759 switch (Val.getKind()) {
1760 case APValue::Uninitialized:
1763 Result = Val.getInt().getBoolValue();
1765 case APValue::Float:
1766 Result = !Val.getFloat().isZero();
1768 case APValue::ComplexInt:
1769 Result = Val.getComplexIntReal().getBoolValue() ||
1770 Val.getComplexIntImag().getBoolValue();
1772 case APValue::ComplexFloat:
1773 Result = !Val.getComplexFloatReal().isZero() ||
1774 !Val.getComplexFloatImag().isZero();
1776 case APValue::LValue:
1777 return EvalPointerValueAsBool(Val, Result);
1778 case APValue::MemberPointer:
1779 Result = Val.getMemberPointerDecl();
1781 case APValue::Vector:
1782 case APValue::Array:
1783 case APValue::Struct:
1784 case APValue::Union:
1785 case APValue::AddrLabelDiff:
1789 llvm_unreachable("unknown APValue kind");
1792 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1794 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1796 if (!Evaluate(Val, Info, E))
1798 return HandleConversionToBool(Val, Result);
1801 template<typename T>
1802 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1803 const T &SrcValue, QualType DestType) {
1804 Info.CCEDiag(E, diag::note_constexpr_overflow)
1805 << SrcValue << DestType;
1806 return Info.noteUndefinedBehavior();
1809 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1810 QualType SrcType, const APFloat &Value,
1811 QualType DestType, APSInt &Result) {
1812 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1813 // Determine whether we are converting to unsigned or signed.
1814 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1816 Result = APSInt(DestWidth, !DestSigned);
1818 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1819 & APFloat::opInvalidOp)
1820 return HandleOverflow(Info, E, Value, DestType);
1824 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1825 QualType SrcType, QualType DestType,
1827 APFloat Value = Result;
1829 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1830 APFloat::rmNearestTiesToEven, &ignored)
1831 & APFloat::opOverflow)
1832 return HandleOverflow(Info, E, Value, DestType);
1836 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1837 QualType DestType, QualType SrcType,
1838 const APSInt &Value) {
1839 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1840 APSInt Result = Value;
1841 // Figure out if this is a truncate, extend or noop cast.
1842 // If the input is signed, do a sign extend, noop, or truncate.
1843 Result = Result.extOrTrunc(DestWidth);
1844 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1848 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1849 QualType SrcType, const APSInt &Value,
1850 QualType DestType, APFloat &Result) {
1851 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1852 if (Result.convertFromAPInt(Value, Value.isSigned(),
1853 APFloat::rmNearestTiesToEven)
1854 & APFloat::opOverflow)
1855 return HandleOverflow(Info, E, Value, DestType);
1859 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1860 APValue &Value, const FieldDecl *FD) {
1861 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1863 if (!Value.isInt()) {
1864 // Trying to store a pointer-cast-to-integer into a bitfield.
1865 // FIXME: In this case, we should provide the diagnostic for casting
1866 // a pointer to an integer.
1867 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1872 APSInt &Int = Value.getInt();
1873 unsigned OldBitWidth = Int.getBitWidth();
1874 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1875 if (NewBitWidth < OldBitWidth)
1876 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1880 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1883 if (!Evaluate(SVal, Info, E))
1886 Res = SVal.getInt();
1889 if (SVal.isFloat()) {
1890 Res = SVal.getFloat().bitcastToAPInt();
1893 if (SVal.isVector()) {
1894 QualType VecTy = E->getType();
1895 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1896 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1897 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1898 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1899 Res = llvm::APInt::getNullValue(VecSize);
1900 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1901 APValue &Elt = SVal.getVectorElt(i);
1902 llvm::APInt EltAsInt;
1904 EltAsInt = Elt.getInt();
1905 } else if (Elt.isFloat()) {
1906 EltAsInt = Elt.getFloat().bitcastToAPInt();
1908 // Don't try to handle vectors of anything other than int or float
1909 // (not sure if it's possible to hit this case).
1910 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1913 unsigned BaseEltSize = EltAsInt.getBitWidth();
1915 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1917 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1921 // Give up if the input isn't an int, float, or vector. For example, we
1922 // reject "(v4i16)(intptr_t)&a".
1923 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1927 /// Perform the given integer operation, which is known to need at most BitWidth
1928 /// bits, and check for overflow in the original type (if that type was not an
1930 template<typename Operation>
1931 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1932 const APSInt &LHS, const APSInt &RHS,
1933 unsigned BitWidth, Operation Op,
1935 if (LHS.isUnsigned()) {
1936 Result = Op(LHS, RHS);
1940 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1941 Result = Value.trunc(LHS.getBitWidth());
1942 if (Result.extend(BitWidth) != Value) {
1943 if (Info.checkingForOverflow())
1944 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1945 diag::warn_integer_constant_overflow)
1946 << Result.toString(10) << E->getType();
1948 return HandleOverflow(Info, E, Value, E->getType());
1953 /// Perform the given binary integer operation.
1954 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1955 BinaryOperatorKind Opcode, APSInt RHS,
1962 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1963 std::multiplies<APSInt>(), Result);
1965 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1966 std::plus<APSInt>(), Result);
1968 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1969 std::minus<APSInt>(), Result);
1970 case BO_And: Result = LHS & RHS; return true;
1971 case BO_Xor: Result = LHS ^ RHS; return true;
1972 case BO_Or: Result = LHS | RHS; return true;
1976 Info.FFDiag(E, diag::note_expr_divide_by_zero);
1979 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1980 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1981 // this operation and gives the two's complement result.
1982 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1983 LHS.isSigned() && LHS.isMinSignedValue())
1984 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1988 if (Info.getLangOpts().OpenCL)
1989 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1990 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1991 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1993 else if (RHS.isSigned() && RHS.isNegative()) {
1994 // During constant-folding, a negative shift is an opposite shift. Such
1995 // a shift is not a constant expression.
1996 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2001 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2002 // the shifted type.
2003 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2005 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2006 << RHS << E->getType() << LHS.getBitWidth();
2007 } else if (LHS.isSigned()) {
2008 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2009 // operand, and must not overflow the corresponding unsigned type.
2010 if (LHS.isNegative())
2011 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2012 else if (LHS.countLeadingZeros() < SA)
2013 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2019 if (Info.getLangOpts().OpenCL)
2020 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2021 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2022 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2024 else if (RHS.isSigned() && RHS.isNegative()) {
2025 // During constant-folding, a negative shift is an opposite shift. Such a
2026 // shift is not a constant expression.
2027 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2032 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2034 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2036 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2037 << RHS << E->getType() << LHS.getBitWidth();
2042 case BO_LT: Result = LHS < RHS; return true;
2043 case BO_GT: Result = LHS > RHS; return true;
2044 case BO_LE: Result = LHS <= RHS; return true;
2045 case BO_GE: Result = LHS >= RHS; return true;
2046 case BO_EQ: Result = LHS == RHS; return true;
2047 case BO_NE: Result = LHS != RHS; return true;
2051 /// Perform the given binary floating-point operation, in-place, on LHS.
2052 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2053 APFloat &LHS, BinaryOperatorKind Opcode,
2054 const APFloat &RHS) {
2060 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2063 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2066 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2069 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2073 if (LHS.isInfinity() || LHS.isNaN()) {
2074 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2075 return Info.noteUndefinedBehavior();
2080 /// Cast an lvalue referring to a base subobject to a derived class, by
2081 /// truncating the lvalue's path to the given length.
2082 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2083 const RecordDecl *TruncatedType,
2084 unsigned TruncatedElements) {
2085 SubobjectDesignator &D = Result.Designator;
2087 // Check we actually point to a derived class object.
2088 if (TruncatedElements == D.Entries.size())
2090 assert(TruncatedElements >= D.MostDerivedPathLength &&
2091 "not casting to a derived class");
2092 if (!Result.checkSubobject(Info, E, CSK_Derived))
2095 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2096 const RecordDecl *RD = TruncatedType;
2097 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2098 if (RD->isInvalidDecl()) return false;
2099 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2100 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2101 if (isVirtualBaseClass(D.Entries[I]))
2102 Result.Offset -= Layout.getVBaseClassOffset(Base);
2104 Result.Offset -= Layout.getBaseClassOffset(Base);
2107 D.Entries.resize(TruncatedElements);
2111 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2112 const CXXRecordDecl *Derived,
2113 const CXXRecordDecl *Base,
2114 const ASTRecordLayout *RL = nullptr) {
2116 if (Derived->isInvalidDecl()) return false;
2117 RL = &Info.Ctx.getASTRecordLayout(Derived);
2120 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2121 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2125 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2126 const CXXRecordDecl *DerivedDecl,
2127 const CXXBaseSpecifier *Base) {
2128 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2130 if (!Base->isVirtual())
2131 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2133 SubobjectDesignator &D = Obj.Designator;
2137 // Extract most-derived object and corresponding type.
2138 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2139 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2142 // Find the virtual base class.
2143 if (DerivedDecl->isInvalidDecl()) return false;
2144 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2145 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2146 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2150 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2151 QualType Type, LValue &Result) {
2152 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2153 PathE = E->path_end();
2154 PathI != PathE; ++PathI) {
2155 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2158 Type = (*PathI)->getType();
2163 /// Update LVal to refer to the given field, which must be a member of the type
2164 /// currently described by LVal.
2165 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2166 const FieldDecl *FD,
2167 const ASTRecordLayout *RL = nullptr) {
2169 if (FD->getParent()->isInvalidDecl()) return false;
2170 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2173 unsigned I = FD->getFieldIndex();
2174 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2175 LVal.addDecl(Info, E, FD);
2179 /// Update LVal to refer to the given indirect field.
2180 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2182 const IndirectFieldDecl *IFD) {
2183 for (const auto *C : IFD->chain())
2184 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2189 /// Get the size of the given type in char units.
2190 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2191 QualType Type, CharUnits &Size) {
2192 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2194 if (Type->isVoidType() || Type->isFunctionType()) {
2195 Size = CharUnits::One();
2199 if (Type->isDependentType()) {
2204 if (!Type->isConstantSizeType()) {
2205 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2206 // FIXME: Better diagnostic.
2211 Size = Info.Ctx.getTypeSizeInChars(Type);
2215 /// Update a pointer value to model pointer arithmetic.
2216 /// \param Info - Information about the ongoing evaluation.
2217 /// \param E - The expression being evaluated, for diagnostic purposes.
2218 /// \param LVal - The pointer value to be updated.
2219 /// \param EltTy - The pointee type represented by LVal.
2220 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2221 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2222 LValue &LVal, QualType EltTy,
2223 int64_t Adjustment) {
2224 CharUnits SizeOfPointee;
2225 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2228 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2232 /// Update an lvalue to refer to a component of a complex number.
2233 /// \param Info - Information about the ongoing evaluation.
2234 /// \param LVal - The lvalue to be updated.
2235 /// \param EltTy - The complex number's component type.
2236 /// \param Imag - False for the real component, true for the imaginary.
2237 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2238 LValue &LVal, QualType EltTy,
2241 CharUnits SizeOfComponent;
2242 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2244 LVal.Offset += SizeOfComponent;
2246 LVal.addComplex(Info, E, EltTy, Imag);
2250 /// Try to evaluate the initializer for a variable declaration.
2252 /// \param Info Information about the ongoing evaluation.
2253 /// \param E An expression to be used when printing diagnostics.
2254 /// \param VD The variable whose initializer should be obtained.
2255 /// \param Frame The frame in which the variable was created. Must be null
2256 /// if this variable is not local to the evaluation.
2257 /// \param Result Filled in with a pointer to the value of the variable.
2258 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2259 const VarDecl *VD, CallStackFrame *Frame,
2261 // If this is a parameter to an active constexpr function call, perform
2262 // argument substitution.
2263 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2264 // Assume arguments of a potential constant expression are unknown
2265 // constant expressions.
2266 if (Info.checkingPotentialConstantExpression())
2268 if (!Frame || !Frame->Arguments) {
2269 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2272 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2276 // If this is a local variable, dig out its value.
2278 Result = Frame->getTemporary(VD);
2280 // Assume variables referenced within a lambda's call operator that were
2281 // not declared within the call operator are captures and during checking
2282 // of a potential constant expression, assume they are unknown constant
2284 assert(isLambdaCallOperator(Frame->Callee) &&
2285 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2286 "missing value for local variable");
2287 if (Info.checkingPotentialConstantExpression())
2289 // FIXME: implement capture evaluation during constant expr evaluation.
2290 Info.FFDiag(E->getLocStart(),
2291 diag::note_unimplemented_constexpr_lambda_feature_ast)
2292 << "captures not currently allowed";
2298 // Dig out the initializer, and use the declaration which it's attached to.
2299 const Expr *Init = VD->getAnyInitializer(VD);
2300 if (!Init || Init->isValueDependent()) {
2301 // If we're checking a potential constant expression, the variable could be
2302 // initialized later.
2303 if (!Info.checkingPotentialConstantExpression())
2304 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2308 // If we're currently evaluating the initializer of this declaration, use that
2310 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2311 Result = Info.EvaluatingDeclValue;
2315 // Never evaluate the initializer of a weak variable. We can't be sure that
2316 // this is the definition which will be used.
2318 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2322 // Check that we can fold the initializer. In C++, we will have already done
2323 // this in the cases where it matters for conformance.
2324 SmallVector<PartialDiagnosticAt, 8> Notes;
2325 if (!VD->evaluateValue(Notes)) {
2326 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2327 Notes.size() + 1) << VD;
2328 Info.Note(VD->getLocation(), diag::note_declared_at);
2329 Info.addNotes(Notes);
2331 } else if (!VD->checkInitIsICE()) {
2332 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2333 Notes.size() + 1) << VD;
2334 Info.Note(VD->getLocation(), diag::note_declared_at);
2335 Info.addNotes(Notes);
2338 Result = VD->getEvaluatedValue();
2342 static bool IsConstNonVolatile(QualType T) {
2343 Qualifiers Quals = T.getQualifiers();
2344 return Quals.hasConst() && !Quals.hasVolatile();
2347 /// Get the base index of the given base class within an APValue representing
2348 /// the given derived class.
2349 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2350 const CXXRecordDecl *Base) {
2351 Base = Base->getCanonicalDecl();
2353 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2354 E = Derived->bases_end(); I != E; ++I, ++Index) {
2355 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2359 llvm_unreachable("base class missing from derived class's bases list");
2362 /// Extract the value of a character from a string literal.
2363 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2365 // FIXME: Support MakeStringConstant
2366 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2368 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2369 assert(Index <= Str.size() && "Index too large");
2370 return APSInt::getUnsigned(Str.c_str()[Index]);
2373 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2374 Lit = PE->getFunctionName();
2375 const StringLiteral *S = cast<StringLiteral>(Lit);
2376 const ConstantArrayType *CAT =
2377 Info.Ctx.getAsConstantArrayType(S->getType());
2378 assert(CAT && "string literal isn't an array");
2379 QualType CharType = CAT->getElementType();
2380 assert(CharType->isIntegerType() && "unexpected character type");
2382 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2383 CharType->isUnsignedIntegerType());
2384 if (Index < S->getLength())
2385 Value = S->getCodeUnit(Index);
2389 // Expand a string literal into an array of characters.
2390 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2392 const StringLiteral *S = cast<StringLiteral>(Lit);
2393 const ConstantArrayType *CAT =
2394 Info.Ctx.getAsConstantArrayType(S->getType());
2395 assert(CAT && "string literal isn't an array");
2396 QualType CharType = CAT->getElementType();
2397 assert(CharType->isIntegerType() && "unexpected character type");
2399 unsigned Elts = CAT->getSize().getZExtValue();
2400 Result = APValue(APValue::UninitArray(),
2401 std::min(S->getLength(), Elts), Elts);
2402 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2403 CharType->isUnsignedIntegerType());
2404 if (Result.hasArrayFiller())
2405 Result.getArrayFiller() = APValue(Value);
2406 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2407 Value = S->getCodeUnit(I);
2408 Result.getArrayInitializedElt(I) = APValue(Value);
2412 // Expand an array so that it has more than Index filled elements.
2413 static void expandArray(APValue &Array, unsigned Index) {
2414 unsigned Size = Array.getArraySize();
2415 assert(Index < Size);
2417 // Always at least double the number of elements for which we store a value.
2418 unsigned OldElts = Array.getArrayInitializedElts();
2419 unsigned NewElts = std::max(Index+1, OldElts * 2);
2420 NewElts = std::min(Size, std::max(NewElts, 8u));
2422 // Copy the data across.
2423 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2424 for (unsigned I = 0; I != OldElts; ++I)
2425 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2426 for (unsigned I = OldElts; I != NewElts; ++I)
2427 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2428 if (NewValue.hasArrayFiller())
2429 NewValue.getArrayFiller() = Array.getArrayFiller();
2430 Array.swap(NewValue);
2433 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2434 /// conversion. If it's of class type, we may assume that the copy operation
2435 /// is trivial. Note that this is never true for a union type with fields
2436 /// (because the copy always "reads" the active member) and always true for
2437 /// a non-class type.
2438 static bool isReadByLvalueToRvalueConversion(QualType T) {
2439 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2440 if (!RD || (RD->isUnion() && !RD->field_empty()))
2445 for (auto *Field : RD->fields())
2446 if (isReadByLvalueToRvalueConversion(Field->getType()))
2449 for (auto &BaseSpec : RD->bases())
2450 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2456 /// Diagnose an attempt to read from any unreadable field within the specified
2457 /// type, which might be a class type.
2458 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2460 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2464 if (!RD->hasMutableFields())
2467 for (auto *Field : RD->fields()) {
2468 // If we're actually going to read this field in some way, then it can't
2469 // be mutable. If we're in a union, then assigning to a mutable field
2470 // (even an empty one) can change the active member, so that's not OK.
2471 // FIXME: Add core issue number for the union case.
2472 if (Field->isMutable() &&
2473 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2474 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2475 Info.Note(Field->getLocation(), diag::note_declared_at);
2479 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2483 for (auto &BaseSpec : RD->bases())
2484 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2487 // All mutable fields were empty, and thus not actually read.
2491 /// Kinds of access we can perform on an object, for diagnostics.
2500 /// A handle to a complete object (an object that is not a subobject of
2501 /// another object).
2502 struct CompleteObject {
2503 /// The value of the complete object.
2505 /// The type of the complete object.
2508 CompleteObject() : Value(nullptr) {}
2509 CompleteObject(APValue *Value, QualType Type)
2510 : Value(Value), Type(Type) {
2511 assert(Value && "missing value for complete object");
2514 explicit operator bool() const { return Value; }
2516 } // end anonymous namespace
2518 /// Find the designated sub-object of an rvalue.
2519 template<typename SubobjectHandler>
2520 typename SubobjectHandler::result_type
2521 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2522 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2524 // A diagnostic will have already been produced.
2525 return handler.failed();
2526 if (Sub.isOnePastTheEnd()) {
2527 if (Info.getLangOpts().CPlusPlus11)
2528 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2529 << handler.AccessKind;
2532 return handler.failed();
2535 APValue *O = Obj.Value;
2536 QualType ObjType = Obj.Type;
2537 const FieldDecl *LastField = nullptr;
2539 // Walk the designator's path to find the subobject.
2540 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2541 if (O->isUninit()) {
2542 if (!Info.checkingPotentialConstantExpression())
2543 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2544 return handler.failed();
2548 // If we are reading an object of class type, there may still be more
2549 // things we need to check: if there are any mutable subobjects, we
2550 // cannot perform this read. (This only happens when performing a trivial
2551 // copy or assignment.)
2552 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2553 diagnoseUnreadableFields(Info, E, ObjType))
2554 return handler.failed();
2556 if (!handler.found(*O, ObjType))
2559 // If we modified a bit-field, truncate it to the right width.
2560 if (handler.AccessKind != AK_Read &&
2561 LastField && LastField->isBitField() &&
2562 !truncateBitfieldValue(Info, E, *O, LastField))
2568 LastField = nullptr;
2569 if (ObjType->isArrayType()) {
2570 // Next subobject is an array element.
2571 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2572 assert(CAT && "vla in literal type?");
2573 uint64_t Index = Sub.Entries[I].ArrayIndex;
2574 if (CAT->getSize().ule(Index)) {
2575 // Note, it should not be possible to form a pointer with a valid
2576 // designator which points more than one past the end of the array.
2577 if (Info.getLangOpts().CPlusPlus11)
2578 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2579 << handler.AccessKind;
2582 return handler.failed();
2585 ObjType = CAT->getElementType();
2587 // An array object is represented as either an Array APValue or as an
2588 // LValue which refers to a string literal.
2589 if (O->isLValue()) {
2590 assert(I == N - 1 && "extracting subobject of character?");
2591 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2592 if (handler.AccessKind != AK_Read)
2593 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2596 return handler.foundString(*O, ObjType, Index);
2599 if (O->getArrayInitializedElts() > Index)
2600 O = &O->getArrayInitializedElt(Index);
2601 else if (handler.AccessKind != AK_Read) {
2602 expandArray(*O, Index);
2603 O = &O->getArrayInitializedElt(Index);
2605 O = &O->getArrayFiller();
2606 } else if (ObjType->isAnyComplexType()) {
2607 // Next subobject is a complex number.
2608 uint64_t Index = Sub.Entries[I].ArrayIndex;
2610 if (Info.getLangOpts().CPlusPlus11)
2611 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2612 << handler.AccessKind;
2615 return handler.failed();
2618 bool WasConstQualified = ObjType.isConstQualified();
2619 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2620 if (WasConstQualified)
2623 assert(I == N - 1 && "extracting subobject of scalar?");
2624 if (O->isComplexInt()) {
2625 return handler.found(Index ? O->getComplexIntImag()
2626 : O->getComplexIntReal(), ObjType);
2628 assert(O->isComplexFloat());
2629 return handler.found(Index ? O->getComplexFloatImag()
2630 : O->getComplexFloatReal(), ObjType);
2632 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2633 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2634 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2636 Info.Note(Field->getLocation(), diag::note_declared_at);
2637 return handler.failed();
2640 // Next subobject is a class, struct or union field.
2641 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2642 if (RD->isUnion()) {
2643 const FieldDecl *UnionField = O->getUnionField();
2645 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2646 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2647 << handler.AccessKind << Field << !UnionField << UnionField;
2648 return handler.failed();
2650 O = &O->getUnionValue();
2652 O = &O->getStructField(Field->getFieldIndex());
2654 bool WasConstQualified = ObjType.isConstQualified();
2655 ObjType = Field->getType();
2656 if (WasConstQualified && !Field->isMutable())
2659 if (ObjType.isVolatileQualified()) {
2660 if (Info.getLangOpts().CPlusPlus) {
2661 // FIXME: Include a description of the path to the volatile subobject.
2662 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2663 << handler.AccessKind << 2 << Field;
2664 Info.Note(Field->getLocation(), diag::note_declared_at);
2666 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2668 return handler.failed();
2673 // Next subobject is a base class.
2674 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2675 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2676 O = &O->getStructBase(getBaseIndex(Derived, Base));
2678 bool WasConstQualified = ObjType.isConstQualified();
2679 ObjType = Info.Ctx.getRecordType(Base);
2680 if (WasConstQualified)
2687 struct ExtractSubobjectHandler {
2691 static const AccessKinds AccessKind = AK_Read;
2693 typedef bool result_type;
2694 bool failed() { return false; }
2695 bool found(APValue &Subobj, QualType SubobjType) {
2699 bool found(APSInt &Value, QualType SubobjType) {
2700 Result = APValue(Value);
2703 bool found(APFloat &Value, QualType SubobjType) {
2704 Result = APValue(Value);
2707 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2708 Result = APValue(extractStringLiteralCharacter(
2709 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2713 } // end anonymous namespace
2715 const AccessKinds ExtractSubobjectHandler::AccessKind;
2717 /// Extract the designated sub-object of an rvalue.
2718 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2719 const CompleteObject &Obj,
2720 const SubobjectDesignator &Sub,
2722 ExtractSubobjectHandler Handler = { Info, Result };
2723 return findSubobject(Info, E, Obj, Sub, Handler);
2727 struct ModifySubobjectHandler {
2732 typedef bool result_type;
2733 static const AccessKinds AccessKind = AK_Assign;
2735 bool checkConst(QualType QT) {
2736 // Assigning to a const object has undefined behavior.
2737 if (QT.isConstQualified()) {
2738 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2744 bool failed() { return false; }
2745 bool found(APValue &Subobj, QualType SubobjType) {
2746 if (!checkConst(SubobjType))
2748 // We've been given ownership of NewVal, so just swap it in.
2749 Subobj.swap(NewVal);
2752 bool found(APSInt &Value, QualType SubobjType) {
2753 if (!checkConst(SubobjType))
2755 if (!NewVal.isInt()) {
2756 // Maybe trying to write a cast pointer value into a complex?
2760 Value = NewVal.getInt();
2763 bool found(APFloat &Value, QualType SubobjType) {
2764 if (!checkConst(SubobjType))
2766 Value = NewVal.getFloat();
2769 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2770 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2773 } // end anonymous namespace
2775 const AccessKinds ModifySubobjectHandler::AccessKind;
2777 /// Update the designated sub-object of an rvalue to the given value.
2778 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2779 const CompleteObject &Obj,
2780 const SubobjectDesignator &Sub,
2782 ModifySubobjectHandler Handler = { Info, NewVal, E };
2783 return findSubobject(Info, E, Obj, Sub, Handler);
2786 /// Find the position where two subobject designators diverge, or equivalently
2787 /// the length of the common initial subsequence.
2788 static unsigned FindDesignatorMismatch(QualType ObjType,
2789 const SubobjectDesignator &A,
2790 const SubobjectDesignator &B,
2791 bool &WasArrayIndex) {
2792 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2793 for (/**/; I != N; ++I) {
2794 if (!ObjType.isNull() &&
2795 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2796 // Next subobject is an array element.
2797 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2798 WasArrayIndex = true;
2801 if (ObjType->isAnyComplexType())
2802 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2804 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2806 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2807 WasArrayIndex = false;
2810 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2811 // Next subobject is a field.
2812 ObjType = FD->getType();
2814 // Next subobject is a base class.
2815 ObjType = QualType();
2818 WasArrayIndex = false;
2822 /// Determine whether the given subobject designators refer to elements of the
2823 /// same array object.
2824 static bool AreElementsOfSameArray(QualType ObjType,
2825 const SubobjectDesignator &A,
2826 const SubobjectDesignator &B) {
2827 if (A.Entries.size() != B.Entries.size())
2830 bool IsArray = A.MostDerivedIsArrayElement;
2831 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2832 // A is a subobject of the array element.
2835 // If A (and B) designates an array element, the last entry will be the array
2836 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2837 // of length 1' case, and the entire path must match.
2839 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2840 return CommonLength >= A.Entries.size() - IsArray;
2843 /// Find the complete object to which an LValue refers.
2844 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2845 AccessKinds AK, const LValue &LVal,
2846 QualType LValType) {
2848 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2849 return CompleteObject();
2852 CallStackFrame *Frame = nullptr;
2853 if (LVal.CallIndex) {
2854 Frame = Info.getCallFrame(LVal.CallIndex);
2856 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2857 << AK << LVal.Base.is<const ValueDecl*>();
2858 NoteLValueLocation(Info, LVal.Base);
2859 return CompleteObject();
2863 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2864 // is not a constant expression (even if the object is non-volatile). We also
2865 // apply this rule to C++98, in order to conform to the expected 'volatile'
2867 if (LValType.isVolatileQualified()) {
2868 if (Info.getLangOpts().CPlusPlus)
2869 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2873 return CompleteObject();
2876 // Compute value storage location and type of base object.
2877 APValue *BaseVal = nullptr;
2878 QualType BaseType = getType(LVal.Base);
2880 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2881 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2882 // In C++11, constexpr, non-volatile variables initialized with constant
2883 // expressions are constant expressions too. Inside constexpr functions,
2884 // parameters are constant expressions even if they're non-const.
2885 // In C++1y, objects local to a constant expression (those with a Frame) are
2886 // both readable and writable inside constant expressions.
2887 // In C, such things can also be folded, although they are not ICEs.
2888 const VarDecl *VD = dyn_cast<VarDecl>(D);
2890 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2893 if (!VD || VD->isInvalidDecl()) {
2895 return CompleteObject();
2898 // Accesses of volatile-qualified objects are not allowed.
2899 if (BaseType.isVolatileQualified()) {
2900 if (Info.getLangOpts().CPlusPlus) {
2901 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2903 Info.Note(VD->getLocation(), diag::note_declared_at);
2907 return CompleteObject();
2910 // Unless we're looking at a local variable or argument in a constexpr call,
2911 // the variable we're reading must be const.
2913 if (Info.getLangOpts().CPlusPlus14 &&
2914 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2915 // OK, we can read and modify an object if we're in the process of
2916 // evaluating its initializer, because its lifetime began in this
2918 } else if (AK != AK_Read) {
2919 // All the remaining cases only permit reading.
2920 Info.FFDiag(E, diag::note_constexpr_modify_global);
2921 return CompleteObject();
2922 } else if (VD->isConstexpr()) {
2923 // OK, we can read this variable.
2924 } else if (BaseType->isIntegralOrEnumerationType()) {
2925 // In OpenCL if a variable is in constant address space it is a const value.
2926 if (!(BaseType.isConstQualified() ||
2927 (Info.getLangOpts().OpenCL &&
2928 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
2929 if (Info.getLangOpts().CPlusPlus) {
2930 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2931 Info.Note(VD->getLocation(), diag::note_declared_at);
2935 return CompleteObject();
2937 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2938 // We support folding of const floating-point types, in order to make
2939 // static const data members of such types (supported as an extension)
2941 if (Info.getLangOpts().CPlusPlus11) {
2942 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2943 Info.Note(VD->getLocation(), diag::note_declared_at);
2947 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
2948 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
2949 // Keep evaluating to see what we can do.
2951 // FIXME: Allow folding of values of any literal type in all languages.
2952 if (Info.checkingPotentialConstantExpression() &&
2953 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2954 // The definition of this variable could be constexpr. We can't
2955 // access it right now, but may be able to in future.
2956 } else if (Info.getLangOpts().CPlusPlus11) {
2957 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2958 Info.Note(VD->getLocation(), diag::note_declared_at);
2962 return CompleteObject();
2966 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2967 return CompleteObject();
2969 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2972 if (const MaterializeTemporaryExpr *MTE =
2973 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2974 assert(MTE->getStorageDuration() == SD_Static &&
2975 "should have a frame for a non-global materialized temporary");
2977 // Per C++1y [expr.const]p2:
2978 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2979 // - a [...] glvalue of integral or enumeration type that refers to
2980 // a non-volatile const object [...]
2982 // - a [...] glvalue of literal type that refers to a non-volatile
2983 // object whose lifetime began within the evaluation of e.
2985 // C++11 misses the 'began within the evaluation of e' check and
2986 // instead allows all temporaries, including things like:
2989 // constexpr int k = r;
2990 // Therefore we use the C++1y rules in C++11 too.
2991 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2992 const ValueDecl *ED = MTE->getExtendingDecl();
2993 if (!(BaseType.isConstQualified() &&
2994 BaseType->isIntegralOrEnumerationType()) &&
2995 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2996 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2997 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2998 return CompleteObject();
3001 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3002 assert(BaseVal && "got reference to unevaluated temporary");
3005 return CompleteObject();
3008 BaseVal = Frame->getTemporary(Base);
3009 assert(BaseVal && "missing value for temporary");
3012 // Volatile temporary objects cannot be accessed in constant expressions.
3013 if (BaseType.isVolatileQualified()) {
3014 if (Info.getLangOpts().CPlusPlus) {
3015 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3017 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3021 return CompleteObject();
3025 // During the construction of an object, it is not yet 'const'.
3026 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3027 // and this doesn't do quite the right thing for const subobjects of the
3028 // object under construction.
3029 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3030 BaseType = Info.Ctx.getCanonicalType(BaseType);
3031 BaseType.removeLocalConst();
3034 // In C++1y, we can't safely access any mutable state when we might be
3035 // evaluating after an unmodeled side effect.
3037 // FIXME: Not all local state is mutable. Allow local constant subobjects
3038 // to be read here (but take care with 'mutable' fields).
3039 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3040 Info.EvalStatus.HasSideEffects) ||
3041 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3042 return CompleteObject();
3044 return CompleteObject(BaseVal, BaseType);
3047 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3048 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3049 /// glvalue referred to by an entity of reference type.
3051 /// \param Info - Information about the ongoing evaluation.
3052 /// \param Conv - The expression for which we are performing the conversion.
3053 /// Used for diagnostics.
3054 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3055 /// case of a non-class type).
3056 /// \param LVal - The glvalue on which we are attempting to perform this action.
3057 /// \param RVal - The produced value will be placed here.
3058 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3060 const LValue &LVal, APValue &RVal) {
3061 if (LVal.Designator.Invalid)
3064 // Check for special cases where there is no existing APValue to look at.
3065 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3066 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3067 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3068 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3069 // initializer until now for such expressions. Such an expression can't be
3070 // an ICE in C, so this only matters for fold.
3071 if (Type.isVolatileQualified()) {
3076 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3078 CompleteObject LitObj(&Lit, Base->getType());
3079 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3080 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3081 // We represent a string literal array as an lvalue pointing at the
3082 // corresponding expression, rather than building an array of chars.
3083 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3084 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3085 CompleteObject StrObj(&Str, Base->getType());
3086 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3090 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3091 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3094 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3095 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3096 QualType LValType, APValue &Val) {
3097 if (LVal.Designator.Invalid)
3100 if (!Info.getLangOpts().CPlusPlus14) {
3105 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3106 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3109 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3110 return T->isSignedIntegerType() &&
3111 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3115 struct CompoundAssignSubobjectHandler {
3118 QualType PromotedLHSType;
3119 BinaryOperatorKind Opcode;
3122 static const AccessKinds AccessKind = AK_Assign;
3124 typedef bool result_type;
3126 bool checkConst(QualType QT) {
3127 // Assigning to a const object has undefined behavior.
3128 if (QT.isConstQualified()) {
3129 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3135 bool failed() { return false; }
3136 bool found(APValue &Subobj, QualType SubobjType) {
3137 switch (Subobj.getKind()) {
3139 return found(Subobj.getInt(), SubobjType);
3140 case APValue::Float:
3141 return found(Subobj.getFloat(), SubobjType);
3142 case APValue::ComplexInt:
3143 case APValue::ComplexFloat:
3144 // FIXME: Implement complex compound assignment.
3147 case APValue::LValue:
3148 return foundPointer(Subobj, SubobjType);
3150 // FIXME: can this happen?
3155 bool found(APSInt &Value, QualType SubobjType) {
3156 if (!checkConst(SubobjType))
3159 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3160 // We don't support compound assignment on integer-cast-to-pointer
3166 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3168 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3170 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3173 bool found(APFloat &Value, QualType SubobjType) {
3174 return checkConst(SubobjType) &&
3175 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3177 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3178 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3180 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3181 if (!checkConst(SubobjType))
3184 QualType PointeeType;
3185 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3186 PointeeType = PT->getPointeeType();
3188 if (PointeeType.isNull() || !RHS.isInt() ||
3189 (Opcode != BO_Add && Opcode != BO_Sub)) {
3194 int64_t Offset = getExtValue(RHS.getInt());
3195 if (Opcode == BO_Sub)
3199 LVal.setFrom(Info.Ctx, Subobj);
3200 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3202 LVal.moveInto(Subobj);
3205 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3206 llvm_unreachable("shouldn't encounter string elements here");
3209 } // end anonymous namespace
3211 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3213 /// Perform a compound assignment of LVal <op>= RVal.
3214 static bool handleCompoundAssignment(
3215 EvalInfo &Info, const Expr *E,
3216 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3217 BinaryOperatorKind Opcode, const APValue &RVal) {
3218 if (LVal.Designator.Invalid)
3221 if (!Info.getLangOpts().CPlusPlus14) {
3226 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3227 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3229 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3233 struct IncDecSubobjectHandler {
3236 AccessKinds AccessKind;
3239 typedef bool result_type;
3241 bool checkConst(QualType QT) {
3242 // Assigning to a const object has undefined behavior.
3243 if (QT.isConstQualified()) {
3244 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3250 bool failed() { return false; }
3251 bool found(APValue &Subobj, QualType SubobjType) {
3252 // Stash the old value. Also clear Old, so we don't clobber it later
3253 // if we're post-incrementing a complex.
3259 switch (Subobj.getKind()) {
3261 return found(Subobj.getInt(), SubobjType);
3262 case APValue::Float:
3263 return found(Subobj.getFloat(), SubobjType);
3264 case APValue::ComplexInt:
3265 return found(Subobj.getComplexIntReal(),
3266 SubobjType->castAs<ComplexType>()->getElementType()
3267 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3268 case APValue::ComplexFloat:
3269 return found(Subobj.getComplexFloatReal(),
3270 SubobjType->castAs<ComplexType>()->getElementType()
3271 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3272 case APValue::LValue:
3273 return foundPointer(Subobj, SubobjType);
3275 // FIXME: can this happen?
3280 bool found(APSInt &Value, QualType SubobjType) {
3281 if (!checkConst(SubobjType))
3284 if (!SubobjType->isIntegerType()) {
3285 // We don't support increment / decrement on integer-cast-to-pointer
3291 if (Old) *Old = APValue(Value);
3293 // bool arithmetic promotes to int, and the conversion back to bool
3294 // doesn't reduce mod 2^n, so special-case it.
3295 if (SubobjType->isBooleanType()) {
3296 if (AccessKind == AK_Increment)
3303 bool WasNegative = Value.isNegative();
3304 if (AccessKind == AK_Increment) {
3307 if (!WasNegative && Value.isNegative() &&
3308 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3309 APSInt ActualValue(Value, /*IsUnsigned*/true);
3310 return HandleOverflow(Info, E, ActualValue, SubobjType);
3315 if (WasNegative && !Value.isNegative() &&
3316 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3317 unsigned BitWidth = Value.getBitWidth();
3318 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3319 ActualValue.setBit(BitWidth);
3320 return HandleOverflow(Info, E, ActualValue, SubobjType);
3325 bool found(APFloat &Value, QualType SubobjType) {
3326 if (!checkConst(SubobjType))
3329 if (Old) *Old = APValue(Value);
3331 APFloat One(Value.getSemantics(), 1);
3332 if (AccessKind == AK_Increment)
3333 Value.add(One, APFloat::rmNearestTiesToEven);
3335 Value.subtract(One, APFloat::rmNearestTiesToEven);
3338 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3339 if (!checkConst(SubobjType))
3342 QualType PointeeType;
3343 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3344 PointeeType = PT->getPointeeType();
3351 LVal.setFrom(Info.Ctx, Subobj);
3352 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3353 AccessKind == AK_Increment ? 1 : -1))
3355 LVal.moveInto(Subobj);
3358 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3359 llvm_unreachable("shouldn't encounter string elements here");
3362 } // end anonymous namespace
3364 /// Perform an increment or decrement on LVal.
3365 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3366 QualType LValType, bool IsIncrement, APValue *Old) {
3367 if (LVal.Designator.Invalid)
3370 if (!Info.getLangOpts().CPlusPlus14) {
3375 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3376 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3377 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3378 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3381 /// Build an lvalue for the object argument of a member function call.
3382 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3384 if (Object->getType()->isPointerType())
3385 return EvaluatePointer(Object, This, Info);
3387 if (Object->isGLValue())
3388 return EvaluateLValue(Object, This, Info);
3390 if (Object->getType()->isLiteralType(Info.Ctx))
3391 return EvaluateTemporary(Object, This, Info);
3393 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3397 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3398 /// lvalue referring to the result.
3400 /// \param Info - Information about the ongoing evaluation.
3401 /// \param LV - An lvalue referring to the base of the member pointer.
3402 /// \param RHS - The member pointer expression.
3403 /// \param IncludeMember - Specifies whether the member itself is included in
3404 /// the resulting LValue subobject designator. This is not possible when
3405 /// creating a bound member function.
3406 /// \return The field or method declaration to which the member pointer refers,
3407 /// or 0 if evaluation fails.
3408 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3412 bool IncludeMember = true) {
3414 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3417 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3418 // member value, the behavior is undefined.
3419 if (!MemPtr.getDecl()) {
3420 // FIXME: Specific diagnostic.
3425 if (MemPtr.isDerivedMember()) {
3426 // This is a member of some derived class. Truncate LV appropriately.
3427 // The end of the derived-to-base path for the base object must match the
3428 // derived-to-base path for the member pointer.
3429 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3430 LV.Designator.Entries.size()) {
3434 unsigned PathLengthToMember =
3435 LV.Designator.Entries.size() - MemPtr.Path.size();
3436 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3437 const CXXRecordDecl *LVDecl = getAsBaseClass(
3438 LV.Designator.Entries[PathLengthToMember + I]);
3439 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3440 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3446 // Truncate the lvalue to the appropriate derived class.
3447 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3448 PathLengthToMember))
3450 } else if (!MemPtr.Path.empty()) {
3451 // Extend the LValue path with the member pointer's path.
3452 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3453 MemPtr.Path.size() + IncludeMember);
3455 // Walk down to the appropriate base class.
3456 if (const PointerType *PT = LVType->getAs<PointerType>())
3457 LVType = PT->getPointeeType();
3458 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3459 assert(RD && "member pointer access on non-class-type expression");
3460 // The first class in the path is that of the lvalue.
3461 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3462 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3463 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3467 // Finally cast to the class containing the member.
3468 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3469 MemPtr.getContainingRecord()))
3473 // Add the member. Note that we cannot build bound member functions here.
3474 if (IncludeMember) {
3475 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3476 if (!HandleLValueMember(Info, RHS, LV, FD))
3478 } else if (const IndirectFieldDecl *IFD =
3479 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3480 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3483 llvm_unreachable("can't construct reference to bound member function");
3487 return MemPtr.getDecl();
3490 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3491 const BinaryOperator *BO,
3493 bool IncludeMember = true) {
3494 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3496 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3497 if (Info.noteFailure()) {
3499 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3504 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3505 BO->getRHS(), IncludeMember);
3508 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3509 /// the provided lvalue, which currently refers to the base object.
3510 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3512 SubobjectDesignator &D = Result.Designator;
3513 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3516 QualType TargetQT = E->getType();
3517 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3518 TargetQT = PT->getPointeeType();
3520 // Check this cast lands within the final derived-to-base subobject path.
3521 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3522 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3523 << D.MostDerivedType << TargetQT;
3527 // Check the type of the final cast. We don't need to check the path,
3528 // since a cast can only be formed if the path is unique.
3529 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3530 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3531 const CXXRecordDecl *FinalType;
3532 if (NewEntriesSize == D.MostDerivedPathLength)
3533 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3535 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3536 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3537 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3538 << D.MostDerivedType << TargetQT;
3542 // Truncate the lvalue to the appropriate derived class.
3543 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3547 enum EvalStmtResult {
3548 /// Evaluation failed.
3550 /// Hit a 'return' statement.
3552 /// Evaluation succeeded.
3554 /// Hit a 'continue' statement.
3556 /// Hit a 'break' statement.
3558 /// Still scanning for 'case' or 'default' statement.
3563 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3564 // We don't need to evaluate the initializer for a static local.
3565 if (!VD->hasLocalStorage())
3569 Result.set(VD, Info.CurrentCall->Index);
3570 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3572 const Expr *InitE = VD->getInit();
3574 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3575 << false << VD->getType();
3580 if (InitE->isValueDependent())
3583 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3584 // Wipe out any partially-computed value, to allow tracking that this
3585 // evaluation failed.
3593 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3596 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3597 OK &= EvaluateVarDecl(Info, VD);
3599 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3600 for (auto *BD : DD->bindings())
3601 if (auto *VD = BD->getHoldingVar())
3602 OK &= EvaluateDecl(Info, VD);
3608 /// Evaluate a condition (either a variable declaration or an expression).
3609 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3610 const Expr *Cond, bool &Result) {
3611 FullExpressionRAII Scope(Info);
3612 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3614 return EvaluateAsBooleanCondition(Cond, Result, Info);
3618 /// \brief A location where the result (returned value) of evaluating a
3619 /// statement should be stored.
3621 /// The APValue that should be filled in with the returned value.
3623 /// The location containing the result, if any (used to support RVO).
3628 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3630 const SwitchCase *SC = nullptr);
3632 /// Evaluate the body of a loop, and translate the result as appropriate.
3633 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3635 const SwitchCase *Case = nullptr) {
3636 BlockScopeRAII Scope(Info);
3637 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3639 return ESR_Succeeded;
3642 return ESR_Continue;
3645 case ESR_CaseNotFound:
3648 llvm_unreachable("Invalid EvalStmtResult!");
3651 /// Evaluate a switch statement.
3652 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3653 const SwitchStmt *SS) {
3654 BlockScopeRAII Scope(Info);
3656 // Evaluate the switch condition.
3659 FullExpressionRAII Scope(Info);
3660 if (const Stmt *Init = SS->getInit()) {
3661 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3662 if (ESR != ESR_Succeeded)
3665 if (SS->getConditionVariable() &&
3666 !EvaluateDecl(Info, SS->getConditionVariable()))
3668 if (!EvaluateInteger(SS->getCond(), Value, Info))
3672 // Find the switch case corresponding to the value of the condition.
3673 // FIXME: Cache this lookup.
3674 const SwitchCase *Found = nullptr;
3675 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3676 SC = SC->getNextSwitchCase()) {
3677 if (isa<DefaultStmt>(SC)) {
3682 const CaseStmt *CS = cast<CaseStmt>(SC);
3683 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3684 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3686 if (LHS <= Value && Value <= RHS) {
3693 return ESR_Succeeded;
3695 // Search the switch body for the switch case and evaluate it from there.
3696 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3698 return ESR_Succeeded;
3704 case ESR_CaseNotFound:
3705 // This can only happen if the switch case is nested within a statement
3706 // expression. We have no intention of supporting that.
3707 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3710 llvm_unreachable("Invalid EvalStmtResult!");
3713 // Evaluate a statement.
3714 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3715 const Stmt *S, const SwitchCase *Case) {
3716 if (!Info.nextStep(S))
3719 // If we're hunting down a 'case' or 'default' label, recurse through
3720 // substatements until we hit the label.
3722 // FIXME: We don't start the lifetime of objects whose initialization we
3723 // jump over. However, such objects must be of class type with a trivial
3724 // default constructor that initialize all subobjects, so must be empty,
3725 // so this almost never matters.
3726 switch (S->getStmtClass()) {
3727 case Stmt::CompoundStmtClass:
3728 // FIXME: Precompute which substatement of a compound statement we
3729 // would jump to, and go straight there rather than performing a
3730 // linear scan each time.
3731 case Stmt::LabelStmtClass:
3732 case Stmt::AttributedStmtClass:
3733 case Stmt::DoStmtClass:
3736 case Stmt::CaseStmtClass:
3737 case Stmt::DefaultStmtClass:
3742 case Stmt::IfStmtClass: {
3743 // FIXME: Precompute which side of an 'if' we would jump to, and go
3744 // straight there rather than scanning both sides.
3745 const IfStmt *IS = cast<IfStmt>(S);
3747 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3748 // preceded by our switch label.
3749 BlockScopeRAII Scope(Info);
3751 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3752 if (ESR != ESR_CaseNotFound || !IS->getElse())
3754 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3757 case Stmt::WhileStmtClass: {
3758 EvalStmtResult ESR =
3759 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3760 if (ESR != ESR_Continue)
3765 case Stmt::ForStmtClass: {
3766 const ForStmt *FS = cast<ForStmt>(S);
3767 EvalStmtResult ESR =
3768 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3769 if (ESR != ESR_Continue)
3772 FullExpressionRAII IncScope(Info);
3773 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3779 case Stmt::DeclStmtClass:
3780 // FIXME: If the variable has initialization that can't be jumped over,
3781 // bail out of any immediately-surrounding compound-statement too.
3783 return ESR_CaseNotFound;
3787 switch (S->getStmtClass()) {
3789 if (const Expr *E = dyn_cast<Expr>(S)) {
3790 // Don't bother evaluating beyond an expression-statement which couldn't
3792 FullExpressionRAII Scope(Info);
3793 if (!EvaluateIgnoredValue(Info, E))
3795 return ESR_Succeeded;
3798 Info.FFDiag(S->getLocStart());
3801 case Stmt::NullStmtClass:
3802 return ESR_Succeeded;
3804 case Stmt::DeclStmtClass: {
3805 const DeclStmt *DS = cast<DeclStmt>(S);
3806 for (const auto *DclIt : DS->decls()) {
3807 // Each declaration initialization is its own full-expression.
3808 // FIXME: This isn't quite right; if we're performing aggregate
3809 // initialization, each braced subexpression is its own full-expression.
3810 FullExpressionRAII Scope(Info);
3811 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3814 return ESR_Succeeded;
3817 case Stmt::ReturnStmtClass: {
3818 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3819 FullExpressionRAII Scope(Info);
3822 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3823 : Evaluate(Result.Value, Info, RetExpr)))
3825 return ESR_Returned;
3828 case Stmt::CompoundStmtClass: {
3829 BlockScopeRAII Scope(Info);
3831 const CompoundStmt *CS = cast<CompoundStmt>(S);
3832 for (const auto *BI : CS->body()) {
3833 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3834 if (ESR == ESR_Succeeded)
3836 else if (ESR != ESR_CaseNotFound)
3839 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3842 case Stmt::IfStmtClass: {
3843 const IfStmt *IS = cast<IfStmt>(S);
3845 // Evaluate the condition, as either a var decl or as an expression.
3846 BlockScopeRAII Scope(Info);
3847 if (const Stmt *Init = IS->getInit()) {
3848 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3849 if (ESR != ESR_Succeeded)
3853 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3856 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3857 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3858 if (ESR != ESR_Succeeded)
3861 return ESR_Succeeded;
3864 case Stmt::WhileStmtClass: {
3865 const WhileStmt *WS = cast<WhileStmt>(S);
3867 BlockScopeRAII Scope(Info);
3869 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3875 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3876 if (ESR != ESR_Continue)
3879 return ESR_Succeeded;
3882 case Stmt::DoStmtClass: {
3883 const DoStmt *DS = cast<DoStmt>(S);
3886 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3887 if (ESR != ESR_Continue)
3891 FullExpressionRAII CondScope(Info);
3892 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3895 return ESR_Succeeded;
3898 case Stmt::ForStmtClass: {
3899 const ForStmt *FS = cast<ForStmt>(S);
3900 BlockScopeRAII Scope(Info);
3901 if (FS->getInit()) {
3902 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3903 if (ESR != ESR_Succeeded)
3907 BlockScopeRAII Scope(Info);
3908 bool Continue = true;
3909 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3910 FS->getCond(), Continue))
3915 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3916 if (ESR != ESR_Continue)
3920 FullExpressionRAII IncScope(Info);
3921 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3925 return ESR_Succeeded;
3928 case Stmt::CXXForRangeStmtClass: {
3929 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3930 BlockScopeRAII Scope(Info);
3932 // Initialize the __range variable.
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3934 if (ESR != ESR_Succeeded)
3937 // Create the __begin and __end iterators.
3938 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3939 if (ESR != ESR_Succeeded)
3941 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
3942 if (ESR != ESR_Succeeded)
3946 // Condition: __begin != __end.
3948 bool Continue = true;
3949 FullExpressionRAII CondExpr(Info);
3950 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3956 // User's variable declaration, initialized by *__begin.
3957 BlockScopeRAII InnerScope(Info);
3958 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3959 if (ESR != ESR_Succeeded)
3963 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3964 if (ESR != ESR_Continue)
3967 // Increment: ++__begin
3968 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3972 return ESR_Succeeded;
3975 case Stmt::SwitchStmtClass:
3976 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3978 case Stmt::ContinueStmtClass:
3979 return ESR_Continue;
3981 case Stmt::BreakStmtClass:
3984 case Stmt::LabelStmtClass:
3985 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3987 case Stmt::AttributedStmtClass:
3988 // As a general principle, C++11 attributes can be ignored without
3989 // any semantic impact.
3990 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3993 case Stmt::CaseStmtClass:
3994 case Stmt::DefaultStmtClass:
3995 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3999 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4000 /// default constructor. If so, we'll fold it whether or not it's marked as
4001 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4002 /// so we need special handling.
4003 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4004 const CXXConstructorDecl *CD,
4005 bool IsValueInitialization) {
4006 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4009 // Value-initialization does not call a trivial default constructor, so such a
4010 // call is a core constant expression whether or not the constructor is
4012 if (!CD->isConstexpr() && !IsValueInitialization) {
4013 if (Info.getLangOpts().CPlusPlus11) {
4014 // FIXME: If DiagDecl is an implicitly-declared special member function,
4015 // we should be much more explicit about why it's not constexpr.
4016 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4017 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4018 Info.Note(CD->getLocation(), diag::note_declared_at);
4020 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4026 /// CheckConstexprFunction - Check that a function can be called in a constant
4028 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4029 const FunctionDecl *Declaration,
4030 const FunctionDecl *Definition,
4032 // Potential constant expressions can contain calls to declared, but not yet
4033 // defined, constexpr functions.
4034 if (Info.checkingPotentialConstantExpression() && !Definition &&
4035 Declaration->isConstexpr())
4038 // Bail out with no diagnostic if the function declaration itself is invalid.
4039 // We will have produced a relevant diagnostic while parsing it.
4040 if (Declaration->isInvalidDecl())
4043 // Can we evaluate this function call?
4044 if (Definition && Definition->isConstexpr() &&
4045 !Definition->isInvalidDecl() && Body)
4048 if (Info.getLangOpts().CPlusPlus11) {
4049 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4051 // If this function is not constexpr because it is an inherited
4052 // non-constexpr constructor, diagnose that directly.
4053 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4054 if (CD && CD->isInheritingConstructor()) {
4055 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4056 if (!Inherited->isConstexpr())
4057 DiagDecl = CD = Inherited;
4060 // FIXME: If DiagDecl is an implicitly-declared special member function
4061 // or an inheriting constructor, we should be much more explicit about why
4062 // it's not constexpr.
4063 if (CD && CD->isInheritingConstructor())
4064 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4065 << CD->getInheritedConstructor().getConstructor()->getParent();
4067 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4068 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4069 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4071 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4076 /// Determine if a class has any fields that might need to be copied by a
4077 /// trivial copy or move operation.
4078 static bool hasFields(const CXXRecordDecl *RD) {
4079 if (!RD || RD->isEmpty())
4081 for (auto *FD : RD->fields()) {
4082 if (FD->isUnnamedBitfield())
4086 for (auto &Base : RD->bases())
4087 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4093 typedef SmallVector<APValue, 8> ArgVector;
4096 /// EvaluateArgs - Evaluate the arguments to a function call.
4097 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4099 bool Success = true;
4100 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4102 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4103 // If we're checking for a potential constant expression, evaluate all
4104 // initializers even if some of them fail.
4105 if (!Info.noteFailure())
4113 /// Evaluate a function call.
4114 static bool HandleFunctionCall(SourceLocation CallLoc,
4115 const FunctionDecl *Callee, const LValue *This,
4116 ArrayRef<const Expr*> Args, const Stmt *Body,
4117 EvalInfo &Info, APValue &Result,
4118 const LValue *ResultSlot) {
4119 ArgVector ArgValues(Args.size());
4120 if (!EvaluateArgs(Args, ArgValues, Info))
4123 if (!Info.CheckCallLimit(CallLoc))
4126 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4128 // For a trivial copy or move assignment, perform an APValue copy. This is
4129 // essential for unions, where the operations performed by the assignment
4130 // operator cannot be represented as statements.
4132 // Skip this for non-union classes with no fields; in that case, the defaulted
4133 // copy/move does not actually read the object.
4134 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4135 if (MD && MD->isDefaulted() &&
4136 (MD->getParent()->isUnion() ||
4137 (MD->isTrivial() && hasFields(MD->getParent())))) {
4139 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4141 RHS.setFrom(Info.Ctx, ArgValues[0]);
4143 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4146 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4149 This->moveInto(Result);
4153 StmtResult Ret = {Result, ResultSlot};
4154 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4155 if (ESR == ESR_Succeeded) {
4156 if (Callee->getReturnType()->isVoidType())
4158 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4160 return ESR == ESR_Returned;
4163 /// Evaluate a constructor call.
4164 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4166 const CXXConstructorDecl *Definition,
4167 EvalInfo &Info, APValue &Result) {
4168 SourceLocation CallLoc = E->getExprLoc();
4169 if (!Info.CheckCallLimit(CallLoc))
4172 const CXXRecordDecl *RD = Definition->getParent();
4173 if (RD->getNumVBases()) {
4174 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4178 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4180 // FIXME: Creating an APValue just to hold a nonexistent return value is
4183 StmtResult Ret = {RetVal, nullptr};
4185 // If it's a delegating constructor, delegate.
4186 if (Definition->isDelegatingConstructor()) {
4187 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4189 FullExpressionRAII InitScope(Info);
4190 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4193 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4196 // For a trivial copy or move constructor, perform an APValue copy. This is
4197 // essential for unions (or classes with anonymous union members), where the
4198 // operations performed by the constructor cannot be represented by
4199 // ctor-initializers.
4201 // Skip this for empty non-union classes; we should not perform an
4202 // lvalue-to-rvalue conversion on them because their copy constructor does not
4203 // actually read them.
4204 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4205 (Definition->getParent()->isUnion() ||
4206 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4208 RHS.setFrom(Info.Ctx, ArgValues[0]);
4209 return handleLValueToRValueConversion(
4210 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4214 // Reserve space for the struct members.
4215 if (!RD->isUnion() && Result.isUninit())
4216 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4217 std::distance(RD->field_begin(), RD->field_end()));
4219 if (RD->isInvalidDecl()) return false;
4220 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4222 // A scope for temporaries lifetime-extended by reference members.
4223 BlockScopeRAII LifetimeExtendedScope(Info);
4225 bool Success = true;
4226 unsigned BasesSeen = 0;
4228 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4230 for (const auto *I : Definition->inits()) {
4231 LValue Subobject = This;
4232 APValue *Value = &Result;
4234 // Determine the subobject to initialize.
4235 FieldDecl *FD = nullptr;
4236 if (I->isBaseInitializer()) {
4237 QualType BaseType(I->getBaseClass(), 0);
4239 // Non-virtual base classes are initialized in the order in the class
4240 // definition. We have already checked for virtual base classes.
4241 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4242 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4243 "base class initializers not in expected order");
4246 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4247 BaseType->getAsCXXRecordDecl(), &Layout))
4249 Value = &Result.getStructBase(BasesSeen++);
4250 } else if ((FD = I->getMember())) {
4251 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4253 if (RD->isUnion()) {
4254 Result = APValue(FD);
4255 Value = &Result.getUnionValue();
4257 Value = &Result.getStructField(FD->getFieldIndex());
4259 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4260 // Walk the indirect field decl's chain to find the object to initialize,
4261 // and make sure we've initialized every step along it.
4262 for (auto *C : IFD->chain()) {
4263 FD = cast<FieldDecl>(C);
4264 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4265 // Switch the union field if it differs. This happens if we had
4266 // preceding zero-initialization, and we're now initializing a union
4267 // subobject other than the first.
4268 // FIXME: In this case, the values of the other subobjects are
4269 // specified, since zero-initialization sets all padding bits to zero.
4270 if (Value->isUninit() ||
4271 (Value->isUnion() && Value->getUnionField() != FD)) {
4273 *Value = APValue(FD);
4275 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4276 std::distance(CD->field_begin(), CD->field_end()));
4278 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4281 Value = &Value->getUnionValue();
4283 Value = &Value->getStructField(FD->getFieldIndex());
4286 llvm_unreachable("unknown base initializer kind");
4289 FullExpressionRAII InitScope(Info);
4290 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4291 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4293 // If we're checking for a potential constant expression, evaluate all
4294 // initializers even if some of them fail.
4295 if (!Info.noteFailure())
4302 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4305 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4306 ArrayRef<const Expr*> Args,
4307 const CXXConstructorDecl *Definition,
4308 EvalInfo &Info, APValue &Result) {
4309 ArgVector ArgValues(Args.size());
4310 if (!EvaluateArgs(Args, ArgValues, Info))
4313 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4317 //===----------------------------------------------------------------------===//
4318 // Generic Evaluation
4319 //===----------------------------------------------------------------------===//
4322 template <class Derived>
4323 class ExprEvaluatorBase
4324 : public ConstStmtVisitor<Derived, bool> {
4326 Derived &getDerived() { return static_cast<Derived&>(*this); }
4327 bool DerivedSuccess(const APValue &V, const Expr *E) {
4328 return getDerived().Success(V, E);
4330 bool DerivedZeroInitialization(const Expr *E) {
4331 return getDerived().ZeroInitialization(E);
4334 // Check whether a conditional operator with a non-constant condition is a
4335 // potential constant expression. If neither arm is a potential constant
4336 // expression, then the conditional operator is not either.
4337 template<typename ConditionalOperator>
4338 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4339 assert(Info.checkingPotentialConstantExpression());
4341 // Speculatively evaluate both arms.
4342 SmallVector<PartialDiagnosticAt, 8> Diag;
4344 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4345 StmtVisitorTy::Visit(E->getFalseExpr());
4351 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4353 StmtVisitorTy::Visit(E->getTrueExpr());
4358 Error(E, diag::note_constexpr_conditional_never_const);
4362 template<typename ConditionalOperator>
4363 bool HandleConditionalOperator(const ConditionalOperator *E) {
4365 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4366 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
4367 CheckPotentialConstantConditional(E);
4371 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4372 return StmtVisitorTy::Visit(EvalExpr);
4377 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4378 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4380 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4381 return Info.CCEDiag(E, D);
4384 bool ZeroInitialization(const Expr *E) { return Error(E); }
4387 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4389 EvalInfo &getEvalInfo() { return Info; }
4391 /// Report an evaluation error. This should only be called when an error is
4392 /// first discovered. When propagating an error, just return false.
4393 bool Error(const Expr *E, diag::kind D) {
4397 bool Error(const Expr *E) {
4398 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4401 bool VisitStmt(const Stmt *) {
4402 llvm_unreachable("Expression evaluator should not be called on stmts");
4404 bool VisitExpr(const Expr *E) {
4408 bool VisitParenExpr(const ParenExpr *E)
4409 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4410 bool VisitUnaryExtension(const UnaryOperator *E)
4411 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4412 bool VisitUnaryPlus(const UnaryOperator *E)
4413 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4414 bool VisitChooseExpr(const ChooseExpr *E)
4415 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4416 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4417 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4418 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4419 { return StmtVisitorTy::Visit(E->getReplacement()); }
4420 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4421 { return StmtVisitorTy::Visit(E->getExpr()); }
4422 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4423 // The initializer may not have been parsed yet, or might be erroneous.
4426 return StmtVisitorTy::Visit(E->getExpr());
4428 // We cannot create any objects for which cleanups are required, so there is
4429 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4430 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4431 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4433 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4434 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4435 return static_cast<Derived*>(this)->VisitCastExpr(E);
4437 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4438 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4439 return static_cast<Derived*>(this)->VisitCastExpr(E);
4442 bool VisitBinaryOperator(const BinaryOperator *E) {
4443 switch (E->getOpcode()) {
4448 VisitIgnoredValue(E->getLHS());
4449 return StmtVisitorTy::Visit(E->getRHS());
4454 if (!HandleMemberPointerAccess(Info, E, Obj))
4457 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4459 return DerivedSuccess(Result, E);
4464 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4465 // Evaluate and cache the common expression. We treat it as a temporary,
4466 // even though it's not quite the same thing.
4467 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4468 Info, E->getCommon()))
4471 return HandleConditionalOperator(E);
4474 bool VisitConditionalOperator(const ConditionalOperator *E) {
4475 bool IsBcpCall = false;
4476 // If the condition (ignoring parens) is a __builtin_constant_p call,
4477 // the result is a constant expression if it can be folded without
4478 // side-effects. This is an important GNU extension. See GCC PR38377
4480 if (const CallExpr *CallCE =
4481 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4482 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4485 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4486 // constant expression; we can't check whether it's potentially foldable.
4487 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4490 FoldConstant Fold(Info, IsBcpCall);
4491 if (!HandleConditionalOperator(E)) {
4492 Fold.keepDiagnostics();
4499 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4500 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4501 return DerivedSuccess(*Value, E);
4503 const Expr *Source = E->getSourceExpr();
4506 if (Source == E) { // sanity checking.
4507 assert(0 && "OpaqueValueExpr recursively refers to itself");
4510 return StmtVisitorTy::Visit(Source);
4513 bool VisitCallExpr(const CallExpr *E) {
4515 if (!handleCallExpr(E, Result, nullptr))
4517 return DerivedSuccess(Result, E);
4520 bool handleCallExpr(const CallExpr *E, APValue &Result,
4521 const LValue *ResultSlot) {
4522 const Expr *Callee = E->getCallee()->IgnoreParens();
4523 QualType CalleeType = Callee->getType();
4525 const FunctionDecl *FD = nullptr;
4526 LValue *This = nullptr, ThisVal;
4527 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4528 bool HasQualifier = false;
4530 // Extract function decl and 'this' pointer from the callee.
4531 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4532 const ValueDecl *Member = nullptr;
4533 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4534 // Explicit bound member calls, such as x.f() or p->g();
4535 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4537 Member = ME->getMemberDecl();
4539 HasQualifier = ME->hasQualifier();
4540 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4541 // Indirect bound member calls ('.*' or '->*').
4542 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4543 if (!Member) return false;
4546 return Error(Callee);
4548 FD = dyn_cast<FunctionDecl>(Member);
4550 return Error(Callee);
4551 } else if (CalleeType->isFunctionPointerType()) {
4553 if (!EvaluatePointer(Callee, Call, Info))
4556 if (!Call.getLValueOffset().isZero())
4557 return Error(Callee);
4558 FD = dyn_cast_or_null<FunctionDecl>(
4559 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4561 return Error(Callee);
4562 // Don't call function pointers which have been cast to some other type.
4563 // Per DR (no number yet), the caller and callee can differ in noexcept.
4564 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4565 CalleeType->getPointeeType(), FD->getType())) {
4569 // Overloaded operator calls to member functions are represented as normal
4570 // calls with '*this' as the first argument.
4571 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4572 if (MD && !MD->isStatic()) {
4573 // FIXME: When selecting an implicit conversion for an overloaded
4574 // operator delete, we sometimes try to evaluate calls to conversion
4575 // operators without a 'this' parameter!
4579 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4582 Args = Args.slice(1);
4583 } else if (MD && MD->isLambdaStaticInvoker()) {
4584 // Map the static invoker for the lambda back to the call operator.
4585 // Conveniently, we don't have to slice out the 'this' argument (as is
4586 // being done for the non-static case), since a static member function
4587 // doesn't have an implicit argument passed in.
4588 const CXXRecordDecl *ClosureClass = MD->getParent();
4590 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4591 "Number of captures must be zero for conversion to function-ptr");
4593 const CXXMethodDecl *LambdaCallOp =
4594 ClosureClass->getLambdaCallOperator();
4596 // Set 'FD', the function that will be called below, to the call
4597 // operator. If the closure object represents a generic lambda, find
4598 // the corresponding specialization of the call operator.
4600 if (ClosureClass->isGenericLambda()) {
4601 assert(MD->isFunctionTemplateSpecialization() &&
4602 "A generic lambda's static-invoker function must be a "
4603 "template specialization");
4604 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4605 FunctionTemplateDecl *CallOpTemplate =
4606 LambdaCallOp->getDescribedFunctionTemplate();
4607 void *InsertPos = nullptr;
4608 FunctionDecl *CorrespondingCallOpSpecialization =
4609 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4610 assert(CorrespondingCallOpSpecialization &&
4611 "We must always have a function call operator specialization "
4612 "that corresponds to our static invoker specialization");
4613 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4622 if (This && !This->checkSubobject(Info, E, CSK_This))
4625 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4626 // calls to such functions in constant expressions.
4627 if (This && !HasQualifier &&
4628 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4629 return Error(E, diag::note_constexpr_virtual_call);
4631 const FunctionDecl *Definition = nullptr;
4632 Stmt *Body = FD->getBody(Definition);
4634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4635 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4636 Result, ResultSlot))
4642 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4643 return StmtVisitorTy::Visit(E->getInitializer());
4645 bool VisitInitListExpr(const InitListExpr *E) {
4646 if (E->getNumInits() == 0)
4647 return DerivedZeroInitialization(E);
4648 if (E->getNumInits() == 1)
4649 return StmtVisitorTy::Visit(E->getInit(0));
4652 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4653 return DerivedZeroInitialization(E);
4655 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4656 return DerivedZeroInitialization(E);
4658 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4659 return DerivedZeroInitialization(E);
4662 /// A member expression where the object is a prvalue is itself a prvalue.
4663 bool VisitMemberExpr(const MemberExpr *E) {
4664 assert(!E->isArrow() && "missing call to bound member function?");
4667 if (!Evaluate(Val, Info, E->getBase()))
4670 QualType BaseTy = E->getBase()->getType();
4672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4673 if (!FD) return Error(E);
4674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4675 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4678 CompleteObject Obj(&Val, BaseTy);
4679 SubobjectDesignator Designator(BaseTy);
4680 Designator.addDeclUnchecked(FD);
4683 return extractSubobject(Info, E, Obj, Designator, Result) &&
4684 DerivedSuccess(Result, E);
4687 bool VisitCastExpr(const CastExpr *E) {
4688 switch (E->getCastKind()) {
4692 case CK_AtomicToNonAtomic: {
4694 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4696 return DerivedSuccess(AtomicVal, E);
4700 case CK_UserDefinedConversion:
4701 return StmtVisitorTy::Visit(E->getSubExpr());
4703 case CK_LValueToRValue: {
4705 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4708 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4709 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4712 return DerivedSuccess(RVal, E);
4719 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4720 return VisitUnaryPostIncDec(UO);
4722 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4723 return VisitUnaryPostIncDec(UO);
4725 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4726 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4730 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4733 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4734 UO->isIncrementOp(), &RVal))
4736 return DerivedSuccess(RVal, UO);
4739 bool VisitStmtExpr(const StmtExpr *E) {
4740 // We will have checked the full-expressions inside the statement expression
4741 // when they were completed, and don't need to check them again now.
4742 if (Info.checkingForOverflow())
4745 BlockScopeRAII Scope(Info);
4746 const CompoundStmt *CS = E->getSubStmt();
4747 if (CS->body_empty())
4750 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4751 BE = CS->body_end();
4754 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4756 Info.FFDiag((*BI)->getLocStart(),
4757 diag::note_constexpr_stmt_expr_unsupported);
4760 return this->Visit(FinalExpr);
4763 APValue ReturnValue;
4764 StmtResult Result = { ReturnValue, nullptr };
4765 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4766 if (ESR != ESR_Succeeded) {
4767 // FIXME: If the statement-expression terminated due to 'return',
4768 // 'break', or 'continue', it would be nice to propagate that to
4769 // the outer statement evaluation rather than bailing out.
4770 if (ESR != ESR_Failed)
4771 Info.FFDiag((*BI)->getLocStart(),
4772 diag::note_constexpr_stmt_expr_unsupported);
4777 llvm_unreachable("Return from function from the loop above.");
4780 /// Visit a value which is evaluated, but whose value is ignored.
4781 void VisitIgnoredValue(const Expr *E) {
4782 EvaluateIgnoredValue(Info, E);
4785 /// Potentially visit a MemberExpr's base expression.
4786 void VisitIgnoredBaseExpression(const Expr *E) {
4787 // While MSVC doesn't evaluate the base expression, it does diagnose the
4788 // presence of side-effecting behavior.
4789 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4791 VisitIgnoredValue(E);
4797 //===----------------------------------------------------------------------===//
4798 // Common base class for lvalue and temporary evaluation.
4799 //===----------------------------------------------------------------------===//
4801 template<class Derived>
4802 class LValueExprEvaluatorBase
4803 : public ExprEvaluatorBase<Derived> {
4806 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4807 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4809 bool Success(APValue::LValueBase B) {
4815 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4816 ExprEvaluatorBaseTy(Info), Result(Result) {}
4818 bool Success(const APValue &V, const Expr *E) {
4819 Result.setFrom(this->Info.Ctx, V);
4823 bool VisitMemberExpr(const MemberExpr *E) {
4824 // Handle non-static data members.
4828 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
4829 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4830 } else if (E->getBase()->isRValue()) {
4831 assert(E->getBase()->getType()->isRecordType());
4832 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4833 BaseTy = E->getBase()->getType();
4835 EvalOK = this->Visit(E->getBase());
4836 BaseTy = E->getBase()->getType();
4839 if (!this->Info.allowInvalidBaseExpr())
4841 Result.setInvalid(E);
4845 const ValueDecl *MD = E->getMemberDecl();
4846 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4847 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4848 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4850 if (!HandleLValueMember(this->Info, E, Result, FD))
4852 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4853 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4856 return this->Error(E);
4858 if (MD->getType()->isReferenceType()) {
4860 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4863 return Success(RefValue, E);
4868 bool VisitBinaryOperator(const BinaryOperator *E) {
4869 switch (E->getOpcode()) {
4871 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4875 return HandleMemberPointerAccess(this->Info, E, Result);
4879 bool VisitCastExpr(const CastExpr *E) {
4880 switch (E->getCastKind()) {
4882 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4884 case CK_DerivedToBase:
4885 case CK_UncheckedDerivedToBase:
4886 if (!this->Visit(E->getSubExpr()))
4889 // Now figure out the necessary offset to add to the base LV to get from
4890 // the derived class to the base class.
4891 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4898 //===----------------------------------------------------------------------===//
4899 // LValue Evaluation
4901 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4902 // function designators (in C), decl references to void objects (in C), and
4903 // temporaries (if building with -Wno-address-of-temporary).
4905 // LValue evaluation produces values comprising a base expression of one of the
4911 // * CompoundLiteralExpr in C (and in global scope in C++)
4915 // * ObjCStringLiteralExpr
4919 // * CallExpr for a MakeStringConstant builtin
4920 // - Locals and temporaries
4921 // * MaterializeTemporaryExpr
4922 // * Any Expr, with a CallIndex indicating the function in which the temporary
4923 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4924 // from the AST (FIXME).
4925 // * A MaterializeTemporaryExpr that has static storage duration, with no
4926 // CallIndex, for a lifetime-extended temporary.
4927 // plus an offset in bytes.
4928 //===----------------------------------------------------------------------===//
4930 class LValueExprEvaluator
4931 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4933 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4934 LValueExprEvaluatorBaseTy(Info, Result) {}
4936 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4937 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4939 bool VisitDeclRefExpr(const DeclRefExpr *E);
4940 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4941 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4942 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4943 bool VisitMemberExpr(const MemberExpr *E);
4944 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4945 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4946 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4947 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4948 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4949 bool VisitUnaryDeref(const UnaryOperator *E);
4950 bool VisitUnaryReal(const UnaryOperator *E);
4951 bool VisitUnaryImag(const UnaryOperator *E);
4952 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4953 return VisitUnaryPreIncDec(UO);
4955 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4956 return VisitUnaryPreIncDec(UO);
4958 bool VisitBinAssign(const BinaryOperator *BO);
4959 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4961 bool VisitCastExpr(const CastExpr *E) {
4962 switch (E->getCastKind()) {
4964 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4966 case CK_LValueBitCast:
4967 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4968 if (!Visit(E->getSubExpr()))
4970 Result.Designator.setInvalid();
4973 case CK_BaseToDerived:
4974 if (!Visit(E->getSubExpr()))
4976 return HandleBaseToDerivedCast(Info, E, Result);
4980 } // end anonymous namespace
4982 /// Evaluate an expression as an lvalue. This can be legitimately called on
4983 /// expressions which are not glvalues, in three cases:
4984 /// * function designators in C, and
4985 /// * "extern void" objects
4986 /// * @selector() expressions in Objective-C
4987 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4988 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4989 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
4990 return LValueExprEvaluator(Info, Result).Visit(E);
4993 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4994 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4996 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4997 return VisitVarDecl(E, VD);
4998 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
4999 return Visit(BD->getBinding());
5004 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5005 CallStackFrame *Frame = nullptr;
5006 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5007 // Only if a local variable was declared in the function currently being
5008 // evaluated, do we expect to be able to find its value in the current
5009 // frame. (Otherwise it was likely declared in an enclosing context and
5010 // could either have a valid evaluatable value (for e.g. a constexpr
5011 // variable) or be ill-formed (and trigger an appropriate evaluation
5013 if (Info.CurrentCall->Callee &&
5014 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5015 Frame = Info.CurrentCall;
5019 if (!VD->getType()->isReferenceType()) {
5021 Result.set(VD, Frame->Index);
5028 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5030 if (V->isUninit()) {
5031 if (!Info.checkingPotentialConstantExpression())
5032 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5035 return Success(*V, E);
5038 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5039 const MaterializeTemporaryExpr *E) {
5040 // Walk through the expression to find the materialized temporary itself.
5041 SmallVector<const Expr *, 2> CommaLHSs;
5042 SmallVector<SubobjectAdjustment, 2> Adjustments;
5043 const Expr *Inner = E->GetTemporaryExpr()->
5044 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5046 // If we passed any comma operators, evaluate their LHSs.
5047 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5048 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5051 // A materialized temporary with static storage duration can appear within the
5052 // result of a constant expression evaluation, so we need to preserve its
5053 // value for use outside this evaluation.
5055 if (E->getStorageDuration() == SD_Static) {
5056 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5060 Value = &Info.CurrentCall->
5061 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5062 Result.set(E, Info.CurrentCall->Index);
5065 QualType Type = Inner->getType();
5067 // Materialize the temporary itself.
5068 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5069 (E->getStorageDuration() == SD_Static &&
5070 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5075 // Adjust our lvalue to refer to the desired subobject.
5076 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5078 switch (Adjustments[I].Kind) {
5079 case SubobjectAdjustment::DerivedToBaseAdjustment:
5080 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5083 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5086 case SubobjectAdjustment::FieldAdjustment:
5087 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5089 Type = Adjustments[I].Field->getType();
5092 case SubobjectAdjustment::MemberPointerAdjustment:
5093 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5094 Adjustments[I].Ptr.RHS))
5096 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5105 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5106 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5107 "lvalue compound literal in c++?");
5108 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5109 // only see this when folding in C, so there's no standard to follow here.
5113 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5114 if (!E->isPotentiallyEvaluated())
5117 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5118 << E->getExprOperand()->getType()
5119 << E->getExprOperand()->getSourceRange();
5123 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5127 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5128 // Handle static data members.
5129 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5130 VisitIgnoredBaseExpression(E->getBase());
5131 return VisitVarDecl(E, VD);
5134 // Handle static member functions.
5135 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5136 if (MD->isStatic()) {
5137 VisitIgnoredBaseExpression(E->getBase());
5142 // Handle non-static data members.
5143 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5146 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5147 // FIXME: Deal with vectors as array subscript bases.
5148 if (E->getBase()->getType()->isVectorType())
5151 if (!EvaluatePointer(E->getBase(), Result, Info))
5155 if (!EvaluateInteger(E->getIdx(), Index, Info))
5158 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
5159 getExtValue(Index));
5162 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5163 return EvaluatePointer(E->getSubExpr(), Result, Info);
5166 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5167 if (!Visit(E->getSubExpr()))
5169 // __real is a no-op on scalar lvalues.
5170 if (E->getSubExpr()->getType()->isAnyComplexType())
5171 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5175 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5176 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5177 "lvalue __imag__ on scalar?");
5178 if (!Visit(E->getSubExpr()))
5180 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5184 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5185 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5188 if (!this->Visit(UO->getSubExpr()))
5191 return handleIncDec(
5192 this->Info, UO, Result, UO->getSubExpr()->getType(),
5193 UO->isIncrementOp(), nullptr);
5196 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5197 const CompoundAssignOperator *CAO) {
5198 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5203 // The overall lvalue result is the result of evaluating the LHS.
5204 if (!this->Visit(CAO->getLHS())) {
5205 if (Info.noteFailure())
5206 Evaluate(RHS, this->Info, CAO->getRHS());
5210 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5213 return handleCompoundAssignment(
5215 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5216 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5219 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5220 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5225 if (!this->Visit(E->getLHS())) {
5226 if (Info.noteFailure())
5227 Evaluate(NewVal, this->Info, E->getRHS());
5231 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5234 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5238 //===----------------------------------------------------------------------===//
5239 // Pointer Evaluation
5240 //===----------------------------------------------------------------------===//
5242 /// \brief Attempts to compute the number of bytes available at the pointer
5243 /// returned by a function with the alloc_size attribute. Returns true if we
5244 /// were successful. Places an unsigned number into `Result`.
5246 /// This expects the given CallExpr to be a call to a function with an
5247 /// alloc_size attribute.
5248 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5249 const CallExpr *Call,
5250 llvm::APInt &Result) {
5251 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5253 // alloc_size args are 1-indexed, 0 means not present.
5254 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5255 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5256 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5257 if (Call->getNumArgs() <= SizeArgNo)
5260 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5261 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5263 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5265 Into = Into.zextOrSelf(BitsInSizeT);
5270 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5273 if (!AllocSize->getNumElemsParam()) {
5274 Result = std::move(SizeOfElem);
5278 APSInt NumberOfElems;
5279 // Argument numbers start at 1
5280 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5281 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5285 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5289 Result = std::move(BytesAvailable);
5293 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5295 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5297 llvm::APInt &Result) {
5298 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5299 "Can't get the size of a non alloc_size function");
5300 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5301 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5302 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5305 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5306 /// a function with the alloc_size attribute. If it was possible to do so, this
5307 /// function will return true, make Result's Base point to said function call,
5308 /// and mark Result's Base as invalid.
5309 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5311 if (!Info.allowInvalidBaseExpr() || Base.isNull())
5314 // Because we do no form of static analysis, we only support const variables.
5316 // Additionally, we can't support parameters, nor can we support static
5317 // variables (in the latter case, use-before-assign isn't UB; in the former,
5318 // we have no clue what they'll be assigned to).
5320 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5321 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5324 const Expr *Init = VD->getAnyInitializer();
5328 const Expr *E = Init->IgnoreParens();
5329 if (!tryUnwrapAllocSizeCall(E))
5332 // Store E instead of E unwrapped so that the type of the LValue's base is
5333 // what the user wanted.
5334 Result.setInvalid(E);
5336 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5337 Result.addUnsizedArray(Info, Pointee);
5342 class PointerExprEvaluator
5343 : public ExprEvaluatorBase<PointerExprEvaluator> {
5346 bool Success(const Expr *E) {
5351 bool visitNonBuiltinCallExpr(const CallExpr *E);
5354 PointerExprEvaluator(EvalInfo &info, LValue &Result)
5355 : ExprEvaluatorBaseTy(info), Result(Result) {}
5357 bool Success(const APValue &V, const Expr *E) {
5358 Result.setFrom(Info.Ctx, V);
5361 bool ZeroInitialization(const Expr *E) {
5362 auto Offset = Info.Ctx.getTargetNullPointerValue(E->getType());
5363 Result.set((Expr*)nullptr, 0, false, true, Offset);
5367 bool VisitBinaryOperator(const BinaryOperator *E);
5368 bool VisitCastExpr(const CastExpr* E);
5369 bool VisitUnaryAddrOf(const UnaryOperator *E);
5370 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5371 { return Success(E); }
5372 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
5373 { return Success(E); }
5374 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5375 { return Success(E); }
5376 bool VisitCallExpr(const CallExpr *E);
5377 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5378 bool VisitBlockExpr(const BlockExpr *E) {
5379 if (!E->getBlockDecl()->hasCaptures())
5383 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5384 // Can't look at 'this' when checking a potential constant expression.
5385 if (Info.checkingPotentialConstantExpression())
5387 if (!Info.CurrentCall->This) {
5388 if (Info.getLangOpts().CPlusPlus11)
5389 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5394 Result = *Info.CurrentCall->This;
5398 // FIXME: Missing: @protocol, @selector
5400 } // end anonymous namespace
5402 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
5403 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5404 return PointerExprEvaluator(Info, Result).Visit(E);
5407 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5408 if (E->getOpcode() != BO_Add &&
5409 E->getOpcode() != BO_Sub)
5410 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5412 const Expr *PExp = E->getLHS();
5413 const Expr *IExp = E->getRHS();
5414 if (IExp->getType()->isPointerType())
5415 std::swap(PExp, IExp);
5417 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
5418 if (!EvalPtrOK && !Info.noteFailure())
5421 llvm::APSInt Offset;
5422 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5425 int64_t AdditionalOffset = getExtValue(Offset);
5426 if (E->getOpcode() == BO_Sub)
5427 AdditionalOffset = -AdditionalOffset;
5429 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5430 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5434 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5435 return EvaluateLValue(E->getSubExpr(), Result, Info);
5438 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5439 const Expr* SubExpr = E->getSubExpr();
5441 switch (E->getCastKind()) {
5446 case CK_CPointerToObjCPointerCast:
5447 case CK_BlockPointerToObjCPointerCast:
5448 case CK_AnyPointerToBlockPointerCast:
5449 case CK_AddressSpaceConversion:
5450 if (!Visit(SubExpr))
5452 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5453 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5454 // also static_casts, but we disallow them as a resolution to DR1312.
5455 if (!E->getType()->isVoidPointerType()) {
5456 Result.Designator.setInvalid();
5457 if (SubExpr->getType()->isVoidPointerType())
5458 CCEDiag(E, diag::note_constexpr_invalid_cast)
5459 << 3 << SubExpr->getType();
5461 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5463 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5464 ZeroInitialization(E);
5467 case CK_DerivedToBase:
5468 case CK_UncheckedDerivedToBase:
5469 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
5471 if (!Result.Base && Result.Offset.isZero())
5474 // Now figure out the necessary offset to add to the base LV to get from
5475 // the derived class to the base class.
5476 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5477 castAs<PointerType>()->getPointeeType(),
5480 case CK_BaseToDerived:
5481 if (!Visit(E->getSubExpr()))
5483 if (!Result.Base && Result.Offset.isZero())
5485 return HandleBaseToDerivedCast(Info, E, Result);
5487 case CK_NullToPointer:
5488 VisitIgnoredValue(E->getSubExpr());
5489 return ZeroInitialization(E);
5491 case CK_IntegralToPointer: {
5492 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5495 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5498 if (Value.isInt()) {
5499 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5500 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5501 Result.Base = (Expr*)nullptr;
5502 Result.InvalidBase = false;
5503 Result.Offset = CharUnits::fromQuantity(N);
5504 Result.CallIndex = 0;
5505 Result.Designator.setInvalid();
5506 Result.IsNullPtr = false;
5509 // Cast is of an lvalue, no need to change value.
5510 Result.setFrom(Info.Ctx, Value);
5514 case CK_ArrayToPointerDecay:
5515 if (SubExpr->isGLValue()) {
5516 if (!EvaluateLValue(SubExpr, Result, Info))
5519 Result.set(SubExpr, Info.CurrentCall->Index);
5520 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5521 Info, Result, SubExpr))
5524 // The result is a pointer to the first element of the array.
5525 if (const ConstantArrayType *CAT
5526 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5527 Result.addArray(Info, E, CAT);
5529 Result.Designator.setInvalid();
5532 case CK_FunctionToPointerDecay:
5533 return EvaluateLValue(SubExpr, Result, Info);
5535 case CK_LValueToRValue: {
5537 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5541 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5542 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5544 return evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5545 return Success(RVal, E);
5549 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5552 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5553 // C++ [expr.alignof]p3:
5554 // When alignof is applied to a reference type, the result is the
5555 // alignment of the referenced type.
5556 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5557 T = Ref->getPointeeType();
5559 // __alignof is defined to return the preferred alignment.
5560 return Info.Ctx.toCharUnitsFromBits(
5561 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5564 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5565 E = E->IgnoreParens();
5567 // The kinds of expressions that we have special-case logic here for
5568 // should be kept up to date with the special checks for those
5569 // expressions in Sema.
5571 // alignof decl is always accepted, even if it doesn't make sense: we default
5572 // to 1 in those cases.
5573 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5574 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5575 /*RefAsPointee*/true);
5577 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5578 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5579 /*RefAsPointee*/true);
5581 return GetAlignOfType(Info, E->getType());
5584 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5585 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5586 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5589 if (!(Info.allowInvalidBaseExpr() && getAllocSizeAttr(E)))
5592 Result.setInvalid(E);
5593 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5594 Result.addUnsizedArray(Info, PointeeTy);
5598 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5599 if (IsStringLiteralCall(E))
5602 if (unsigned BuiltinOp = E->getBuiltinCallee())
5603 return VisitBuiltinCallExpr(E, BuiltinOp);
5605 return visitNonBuiltinCallExpr(E);
5608 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5609 unsigned BuiltinOp) {
5610 switch (BuiltinOp) {
5611 case Builtin::BI__builtin_addressof:
5612 return EvaluateLValue(E->getArg(0), Result, Info);
5613 case Builtin::BI__builtin_assume_aligned: {
5614 // We need to be very careful here because: if the pointer does not have the
5615 // asserted alignment, then the behavior is undefined, and undefined
5616 // behavior is non-constant.
5617 if (!EvaluatePointer(E->getArg(0), Result, Info))
5620 LValue OffsetResult(Result);
5622 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5624 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5626 if (E->getNumArgs() > 2) {
5628 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5631 int64_t AdditionalOffset = -getExtValue(Offset);
5632 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5635 // If there is a base object, then it must have the correct alignment.
5636 if (OffsetResult.Base) {
5637 CharUnits BaseAlignment;
5638 if (const ValueDecl *VD =
5639 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5640 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5643 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5646 if (BaseAlignment < Align) {
5647 Result.Designator.setInvalid();
5648 // FIXME: Quantities here cast to integers because the plural modifier
5649 // does not work on APSInts yet.
5650 CCEDiag(E->getArg(0),
5651 diag::note_constexpr_baa_insufficient_alignment) << 0
5652 << (int) BaseAlignment.getQuantity()
5653 << (unsigned) getExtValue(Alignment);
5658 // The offset must also have the correct alignment.
5659 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5660 Result.Designator.setInvalid();
5661 APSInt Offset(64, false);
5662 Offset = OffsetResult.Offset.getQuantity();
5664 if (OffsetResult.Base)
5665 CCEDiag(E->getArg(0),
5666 diag::note_constexpr_baa_insufficient_alignment) << 1
5667 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5669 CCEDiag(E->getArg(0),
5670 diag::note_constexpr_baa_value_insufficient_alignment)
5671 << Offset << (unsigned) getExtValue(Alignment);
5679 case Builtin::BIstrchr:
5680 case Builtin::BIwcschr:
5681 case Builtin::BImemchr:
5682 case Builtin::BIwmemchr:
5683 if (Info.getLangOpts().CPlusPlus11)
5684 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5685 << /*isConstexpr*/0 << /*isConstructor*/0
5686 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5688 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5690 case Builtin::BI__builtin_strchr:
5691 case Builtin::BI__builtin_wcschr:
5692 case Builtin::BI__builtin_memchr:
5693 case Builtin::BI__builtin_char_memchr:
5694 case Builtin::BI__builtin_wmemchr: {
5695 if (!Visit(E->getArg(0)))
5698 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5700 uint64_t MaxLength = uint64_t(-1);
5701 if (BuiltinOp != Builtin::BIstrchr &&
5702 BuiltinOp != Builtin::BIwcschr &&
5703 BuiltinOp != Builtin::BI__builtin_strchr &&
5704 BuiltinOp != Builtin::BI__builtin_wcschr) {
5706 if (!EvaluateInteger(E->getArg(2), N, Info))
5708 MaxLength = N.getExtValue();
5711 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5713 // Figure out what value we're actually looking for (after converting to
5714 // the corresponding unsigned type if necessary).
5715 uint64_t DesiredVal;
5716 bool StopAtNull = false;
5717 switch (BuiltinOp) {
5718 case Builtin::BIstrchr:
5719 case Builtin::BI__builtin_strchr:
5720 // strchr compares directly to the passed integer, and therefore
5721 // always fails if given an int that is not a char.
5722 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5723 E->getArg(1)->getType(),
5726 return ZeroInitialization(E);
5729 case Builtin::BImemchr:
5730 case Builtin::BI__builtin_memchr:
5731 case Builtin::BI__builtin_char_memchr:
5732 // memchr compares by converting both sides to unsigned char. That's also
5733 // correct for strchr if we get this far (to cope with plain char being
5734 // unsigned in the strchr case).
5735 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5738 case Builtin::BIwcschr:
5739 case Builtin::BI__builtin_wcschr:
5742 case Builtin::BIwmemchr:
5743 case Builtin::BI__builtin_wmemchr:
5744 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5745 DesiredVal = Desired.getZExtValue();
5749 for (; MaxLength; --MaxLength) {
5751 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5754 if (Char.getInt().getZExtValue() == DesiredVal)
5756 if (StopAtNull && !Char.getInt())
5758 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5761 // Not found: return nullptr.
5762 return ZeroInitialization(E);
5766 return visitNonBuiltinCallExpr(E);
5770 //===----------------------------------------------------------------------===//
5771 // Member Pointer Evaluation
5772 //===----------------------------------------------------------------------===//
5775 class MemberPointerExprEvaluator
5776 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5779 bool Success(const ValueDecl *D) {
5780 Result = MemberPtr(D);
5785 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5786 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5788 bool Success(const APValue &V, const Expr *E) {
5792 bool ZeroInitialization(const Expr *E) {
5793 return Success((const ValueDecl*)nullptr);
5796 bool VisitCastExpr(const CastExpr *E);
5797 bool VisitUnaryAddrOf(const UnaryOperator *E);
5799 } // end anonymous namespace
5801 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5803 assert(E->isRValue() && E->getType()->isMemberPointerType());
5804 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5807 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5808 switch (E->getCastKind()) {
5810 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5812 case CK_NullToMemberPointer:
5813 VisitIgnoredValue(E->getSubExpr());
5814 return ZeroInitialization(E);
5816 case CK_BaseToDerivedMemberPointer: {
5817 if (!Visit(E->getSubExpr()))
5819 if (E->path_empty())
5821 // Base-to-derived member pointer casts store the path in derived-to-base
5822 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5823 // the wrong end of the derived->base arc, so stagger the path by one class.
5824 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5825 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5826 PathI != PathE; ++PathI) {
5827 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5828 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5829 if (!Result.castToDerived(Derived))
5832 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5833 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5838 case CK_DerivedToBaseMemberPointer:
5839 if (!Visit(E->getSubExpr()))
5841 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5842 PathE = E->path_end(); PathI != PathE; ++PathI) {
5843 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5844 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5845 if (!Result.castToBase(Base))
5852 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5853 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5854 // member can be formed.
5855 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5858 //===----------------------------------------------------------------------===//
5859 // Record Evaluation
5860 //===----------------------------------------------------------------------===//
5863 class RecordExprEvaluator
5864 : public ExprEvaluatorBase<RecordExprEvaluator> {
5869 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5870 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5872 bool Success(const APValue &V, const Expr *E) {
5876 bool ZeroInitialization(const Expr *E) {
5877 return ZeroInitialization(E, E->getType());
5879 bool ZeroInitialization(const Expr *E, QualType T);
5881 bool VisitCallExpr(const CallExpr *E) {
5882 return handleCallExpr(E, Result, &This);
5884 bool VisitCastExpr(const CastExpr *E);
5885 bool VisitInitListExpr(const InitListExpr *E);
5886 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5887 return VisitCXXConstructExpr(E, E->getType());
5889 bool VisitLambdaExpr(const LambdaExpr *E);
5890 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
5891 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
5892 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
5896 /// Perform zero-initialization on an object of non-union class type.
5897 /// C++11 [dcl.init]p5:
5898 /// To zero-initialize an object or reference of type T means:
5900 /// -- if T is a (possibly cv-qualified) non-union class type,
5901 /// each non-static data member and each base-class subobject is
5902 /// zero-initialized
5903 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5904 const RecordDecl *RD,
5905 const LValue &This, APValue &Result) {
5906 assert(!RD->isUnion() && "Expected non-union class type");
5907 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5908 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
5909 std::distance(RD->field_begin(), RD->field_end()));
5911 if (RD->isInvalidDecl()) return false;
5912 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5916 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
5917 End = CD->bases_end(); I != End; ++I, ++Index) {
5918 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5919 LValue Subobject = This;
5920 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5922 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
5923 Result.getStructBase(Index)))
5928 for (const auto *I : RD->fields()) {
5929 // -- if T is a reference type, no initialization is performed.
5930 if (I->getType()->isReferenceType())
5933 LValue Subobject = This;
5934 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
5937 ImplicitValueInitExpr VIE(I->getType());
5938 if (!EvaluateInPlace(
5939 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
5946 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5947 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5948 if (RD->isInvalidDecl()) return false;
5949 if (RD->isUnion()) {
5950 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5951 // object's first non-static named data member is zero-initialized
5952 RecordDecl::field_iterator I = RD->field_begin();
5953 if (I == RD->field_end()) {
5954 Result = APValue((const FieldDecl*)nullptr);
5958 LValue Subobject = This;
5959 if (!HandleLValueMember(Info, E, Subobject, *I))
5961 Result = APValue(*I);
5962 ImplicitValueInitExpr VIE(I->getType());
5963 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
5966 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
5967 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
5971 return HandleClassZeroInitialization(Info, E, RD, This, Result);
5974 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5975 switch (E->getCastKind()) {
5977 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5979 case CK_ConstructorConversion:
5980 return Visit(E->getSubExpr());
5982 case CK_DerivedToBase:
5983 case CK_UncheckedDerivedToBase: {
5984 APValue DerivedObject;
5985 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
5987 if (!DerivedObject.isStruct())
5988 return Error(E->getSubExpr());
5990 // Derived-to-base rvalue conversion: just slice off the derived part.
5991 APValue *Value = &DerivedObject;
5992 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5993 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5994 PathE = E->path_end(); PathI != PathE; ++PathI) {
5995 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5996 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5997 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6006 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6007 if (E->isTransparent())
6008 return Visit(E->getInit(0));
6010 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6011 if (RD->isInvalidDecl()) return false;
6012 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6014 if (RD->isUnion()) {
6015 const FieldDecl *Field = E->getInitializedFieldInUnion();
6016 Result = APValue(Field);
6020 // If the initializer list for a union does not contain any elements, the
6021 // first element of the union is value-initialized.
6022 // FIXME: The element should be initialized from an initializer list.
6023 // Is this difference ever observable for initializer lists which
6025 ImplicitValueInitExpr VIE(Field->getType());
6026 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6028 LValue Subobject = This;
6029 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6032 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6033 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6034 isa<CXXDefaultInitExpr>(InitExpr));
6036 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6039 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6040 if (Result.isUninit())
6041 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6042 std::distance(RD->field_begin(), RD->field_end()));
6043 unsigned ElementNo = 0;
6044 bool Success = true;
6046 // Initialize base classes.
6048 for (const auto &Base : CXXRD->bases()) {
6049 assert(ElementNo < E->getNumInits() && "missing init for base class");
6050 const Expr *Init = E->getInit(ElementNo);
6052 LValue Subobject = This;
6053 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6056 APValue &FieldVal = Result.getStructBase(ElementNo);
6057 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6058 if (!Info.noteFailure())
6066 // Initialize members.
6067 for (const auto *Field : RD->fields()) {
6068 // Anonymous bit-fields are not considered members of the class for
6069 // purposes of aggregate initialization.
6070 if (Field->isUnnamedBitfield())
6073 LValue Subobject = This;
6075 bool HaveInit = ElementNo < E->getNumInits();
6077 // FIXME: Diagnostics here should point to the end of the initializer
6078 // list, not the start.
6079 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6080 Subobject, Field, &Layout))
6083 // Perform an implicit value-initialization for members beyond the end of
6084 // the initializer list.
6085 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6086 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6088 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6089 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6090 isa<CXXDefaultInitExpr>(Init));
6092 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6093 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6094 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6095 FieldVal, Field))) {
6096 if (!Info.noteFailure())
6105 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6107 // Note that E's type is not necessarily the type of our class here; we might
6108 // be initializing an array element instead.
6109 const CXXConstructorDecl *FD = E->getConstructor();
6110 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6112 bool ZeroInit = E->requiresZeroInitialization();
6113 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6114 // If we've already performed zero-initialization, we're already done.
6115 if (!Result.isUninit())
6118 // We can get here in two different ways:
6119 // 1) We're performing value-initialization, and should zero-initialize
6121 // 2) We're performing default-initialization of an object with a trivial
6122 // constexpr default constructor, in which case we should start the
6123 // lifetimes of all the base subobjects (there can be no data member
6124 // subobjects in this case) per [basic.life]p1.
6125 // Either way, ZeroInitialization is appropriate.
6126 return ZeroInitialization(E, T);
6129 const FunctionDecl *Definition = nullptr;
6130 auto Body = FD->getBody(Definition);
6132 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6135 // Avoid materializing a temporary for an elidable copy/move constructor.
6136 if (E->isElidable() && !ZeroInit)
6137 if (const MaterializeTemporaryExpr *ME
6138 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6139 return Visit(ME->GetTemporaryExpr());
6141 if (ZeroInit && !ZeroInitialization(E, T))
6144 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6145 return HandleConstructorCall(E, This, Args,
6146 cast<CXXConstructorDecl>(Definition), Info,
6150 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6151 const CXXInheritedCtorInitExpr *E) {
6152 if (!Info.CurrentCall) {
6153 assert(Info.checkingPotentialConstantExpression());
6157 const CXXConstructorDecl *FD = E->getConstructor();
6158 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6161 const FunctionDecl *Definition = nullptr;
6162 auto Body = FD->getBody(Definition);
6164 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6167 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6168 cast<CXXConstructorDecl>(Definition), Info,
6172 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6173 const CXXStdInitializerListExpr *E) {
6174 const ConstantArrayType *ArrayType =
6175 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6178 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6181 // Get a pointer to the first element of the array.
6182 Array.addArray(Info, E, ArrayType);
6184 // FIXME: Perform the checks on the field types in SemaInit.
6185 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6186 RecordDecl::field_iterator Field = Record->field_begin();
6187 if (Field == Record->field_end())
6191 if (!Field->getType()->isPointerType() ||
6192 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6193 ArrayType->getElementType()))
6196 // FIXME: What if the initializer_list type has base classes, etc?
6197 Result = APValue(APValue::UninitStruct(), 0, 2);
6198 Array.moveInto(Result.getStructField(0));
6200 if (++Field == Record->field_end())
6203 if (Field->getType()->isPointerType() &&
6204 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6205 ArrayType->getElementType())) {
6207 if (!HandleLValueArrayAdjustment(Info, E, Array,
6208 ArrayType->getElementType(),
6209 ArrayType->getSize().getZExtValue()))
6211 Array.moveInto(Result.getStructField(1));
6212 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6214 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6218 if (++Field != Record->field_end())
6224 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6225 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6226 if (ClosureClass->isInvalidDecl()) return false;
6228 if (Info.checkingPotentialConstantExpression()) return true;
6229 if (E->capture_size()) {
6230 Info.FFDiag(E, diag::note_unimplemented_constexpr_lambda_feature_ast)
6231 << "can not evaluate lambda expressions with captures";
6234 // FIXME: Implement captures.
6235 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, /*NumFields*/0);
6239 static bool EvaluateRecord(const Expr *E, const LValue &This,
6240 APValue &Result, EvalInfo &Info) {
6241 assert(E->isRValue() && E->getType()->isRecordType() &&
6242 "can't evaluate expression as a record rvalue");
6243 return RecordExprEvaluator(Info, This, Result).Visit(E);
6246 //===----------------------------------------------------------------------===//
6247 // Temporary Evaluation
6249 // Temporaries are represented in the AST as rvalues, but generally behave like
6250 // lvalues. The full-object of which the temporary is a subobject is implicitly
6251 // materialized so that a reference can bind to it.
6252 //===----------------------------------------------------------------------===//
6254 class TemporaryExprEvaluator
6255 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6257 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6258 LValueExprEvaluatorBaseTy(Info, Result) {}
6260 /// Visit an expression which constructs the value of this temporary.
6261 bool VisitConstructExpr(const Expr *E) {
6262 Result.set(E, Info.CurrentCall->Index);
6263 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6267 bool VisitCastExpr(const CastExpr *E) {
6268 switch (E->getCastKind()) {
6270 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6272 case CK_ConstructorConversion:
6273 return VisitConstructExpr(E->getSubExpr());
6276 bool VisitInitListExpr(const InitListExpr *E) {
6277 return VisitConstructExpr(E);
6279 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6280 return VisitConstructExpr(E);
6282 bool VisitCallExpr(const CallExpr *E) {
6283 return VisitConstructExpr(E);
6285 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6286 return VisitConstructExpr(E);
6288 bool VisitLambdaExpr(const LambdaExpr *E) {
6289 return VisitConstructExpr(E);
6292 } // end anonymous namespace
6294 /// Evaluate an expression of record type as a temporary.
6295 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6296 assert(E->isRValue() && E->getType()->isRecordType());
6297 return TemporaryExprEvaluator(Info, Result).Visit(E);
6300 //===----------------------------------------------------------------------===//
6301 // Vector Evaluation
6302 //===----------------------------------------------------------------------===//
6305 class VectorExprEvaluator
6306 : public ExprEvaluatorBase<VectorExprEvaluator> {
6310 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6311 : ExprEvaluatorBaseTy(info), Result(Result) {}
6313 bool Success(ArrayRef<APValue> V, const Expr *E) {
6314 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6315 // FIXME: remove this APValue copy.
6316 Result = APValue(V.data(), V.size());
6319 bool Success(const APValue &V, const Expr *E) {
6320 assert(V.isVector());
6324 bool ZeroInitialization(const Expr *E);
6326 bool VisitUnaryReal(const UnaryOperator *E)
6327 { return Visit(E->getSubExpr()); }
6328 bool VisitCastExpr(const CastExpr* E);
6329 bool VisitInitListExpr(const InitListExpr *E);
6330 bool VisitUnaryImag(const UnaryOperator *E);
6331 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6332 // binary comparisons, binary and/or/xor,
6333 // shufflevector, ExtVectorElementExpr
6335 } // end anonymous namespace
6337 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6338 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6339 return VectorExprEvaluator(Info, Result).Visit(E);
6342 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6343 const VectorType *VTy = E->getType()->castAs<VectorType>();
6344 unsigned NElts = VTy->getNumElements();
6346 const Expr *SE = E->getSubExpr();
6347 QualType SETy = SE->getType();
6349 switch (E->getCastKind()) {
6350 case CK_VectorSplat: {
6351 APValue Val = APValue();
6352 if (SETy->isIntegerType()) {
6354 if (!EvaluateInteger(SE, IntResult, Info))
6356 Val = APValue(std::move(IntResult));
6357 } else if (SETy->isRealFloatingType()) {
6358 APFloat FloatResult(0.0);
6359 if (!EvaluateFloat(SE, FloatResult, Info))
6361 Val = APValue(std::move(FloatResult));
6366 // Splat and create vector APValue.
6367 SmallVector<APValue, 4> Elts(NElts, Val);
6368 return Success(Elts, E);
6371 // Evaluate the operand into an APInt we can extract from.
6372 llvm::APInt SValInt;
6373 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6375 // Extract the elements
6376 QualType EltTy = VTy->getElementType();
6377 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6378 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6379 SmallVector<APValue, 4> Elts;
6380 if (EltTy->isRealFloatingType()) {
6381 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6382 unsigned FloatEltSize = EltSize;
6383 if (&Sem == &APFloat::x87DoubleExtended())
6385 for (unsigned i = 0; i < NElts; i++) {
6388 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6390 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6391 Elts.push_back(APValue(APFloat(Sem, Elt)));
6393 } else if (EltTy->isIntegerType()) {
6394 for (unsigned i = 0; i < NElts; i++) {
6397 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6399 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6400 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6405 return Success(Elts, E);
6408 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6413 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6414 const VectorType *VT = E->getType()->castAs<VectorType>();
6415 unsigned NumInits = E->getNumInits();
6416 unsigned NumElements = VT->getNumElements();
6418 QualType EltTy = VT->getElementType();
6419 SmallVector<APValue, 4> Elements;
6421 // The number of initializers can be less than the number of
6422 // vector elements. For OpenCL, this can be due to nested vector
6423 // initialization. For GCC compatibility, missing trailing elements
6424 // should be initialized with zeroes.
6425 unsigned CountInits = 0, CountElts = 0;
6426 while (CountElts < NumElements) {
6427 // Handle nested vector initialization.
6428 if (CountInits < NumInits
6429 && E->getInit(CountInits)->getType()->isVectorType()) {
6431 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6433 unsigned vlen = v.getVectorLength();
6434 for (unsigned j = 0; j < vlen; j++)
6435 Elements.push_back(v.getVectorElt(j));
6437 } else if (EltTy->isIntegerType()) {
6438 llvm::APSInt sInt(32);
6439 if (CountInits < NumInits) {
6440 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6442 } else // trailing integer zero.
6443 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6444 Elements.push_back(APValue(sInt));
6447 llvm::APFloat f(0.0);
6448 if (CountInits < NumInits) {
6449 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6451 } else // trailing float zero.
6452 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6453 Elements.push_back(APValue(f));
6458 return Success(Elements, E);
6462 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6463 const VectorType *VT = E->getType()->getAs<VectorType>();
6464 QualType EltTy = VT->getElementType();
6465 APValue ZeroElement;
6466 if (EltTy->isIntegerType())
6467 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6470 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6472 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6473 return Success(Elements, E);
6476 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6477 VisitIgnoredValue(E->getSubExpr());
6478 return ZeroInitialization(E);
6481 //===----------------------------------------------------------------------===//
6483 //===----------------------------------------------------------------------===//
6486 class ArrayExprEvaluator
6487 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6492 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6493 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6495 bool Success(const APValue &V, const Expr *E) {
6496 assert((V.isArray() || V.isLValue()) &&
6497 "expected array or string literal");
6502 bool ZeroInitialization(const Expr *E) {
6503 const ConstantArrayType *CAT =
6504 Info.Ctx.getAsConstantArrayType(E->getType());
6508 Result = APValue(APValue::UninitArray(), 0,
6509 CAT->getSize().getZExtValue());
6510 if (!Result.hasArrayFiller()) return true;
6512 // Zero-initialize all elements.
6513 LValue Subobject = This;
6514 Subobject.addArray(Info, E, CAT);
6515 ImplicitValueInitExpr VIE(CAT->getElementType());
6516 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6519 bool VisitCallExpr(const CallExpr *E) {
6520 return handleCallExpr(E, Result, &This);
6522 bool VisitInitListExpr(const InitListExpr *E);
6523 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6524 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6525 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6526 const LValue &Subobject,
6527 APValue *Value, QualType Type);
6529 } // end anonymous namespace
6531 static bool EvaluateArray(const Expr *E, const LValue &This,
6532 APValue &Result, EvalInfo &Info) {
6533 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6534 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6537 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6538 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6542 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6543 // an appropriately-typed string literal enclosed in braces.
6544 if (E->isStringLiteralInit()) {
6546 if (!EvaluateLValue(E->getInit(0), LV, Info))
6550 return Success(Val, E);
6553 bool Success = true;
6555 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6556 "zero-initialized array shouldn't have any initialized elts");
6558 if (Result.isArray() && Result.hasArrayFiller())
6559 Filler = Result.getArrayFiller();
6561 unsigned NumEltsToInit = E->getNumInits();
6562 unsigned NumElts = CAT->getSize().getZExtValue();
6563 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6565 // If the initializer might depend on the array index, run it for each
6566 // array element. For now, just whitelist non-class value-initialization.
6567 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6568 NumEltsToInit = NumElts;
6570 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6572 // If the array was previously zero-initialized, preserve the
6573 // zero-initialized values.
6574 if (!Filler.isUninit()) {
6575 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6576 Result.getArrayInitializedElt(I) = Filler;
6577 if (Result.hasArrayFiller())
6578 Result.getArrayFiller() = Filler;
6581 LValue Subobject = This;
6582 Subobject.addArray(Info, E, CAT);
6583 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6585 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6586 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6587 Info, Subobject, Init) ||
6588 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6589 CAT->getElementType(), 1)) {
6590 if (!Info.noteFailure())
6596 if (!Result.hasArrayFiller())
6599 // If we get here, we have a trivial filler, which we can just evaluate
6600 // once and splat over the rest of the array elements.
6601 assert(FillerExpr && "no array filler for incomplete init list");
6602 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6603 FillerExpr) && Success;
6606 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6607 if (E->getCommonExpr() &&
6608 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6609 Info, E->getCommonExpr()->getSourceExpr()))
6612 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6614 uint64_t Elements = CAT->getSize().getZExtValue();
6615 Result = APValue(APValue::UninitArray(), Elements, Elements);
6617 LValue Subobject = This;
6618 Subobject.addArray(Info, E, CAT);
6620 bool Success = true;
6621 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6622 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6623 Info, Subobject, E->getSubExpr()) ||
6624 !HandleLValueArrayAdjustment(Info, E, Subobject,
6625 CAT->getElementType(), 1)) {
6626 if (!Info.noteFailure())
6635 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6636 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6639 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6640 const LValue &Subobject,
6643 bool HadZeroInit = !Value->isUninit();
6645 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6646 unsigned N = CAT->getSize().getZExtValue();
6648 // Preserve the array filler if we had prior zero-initialization.
6650 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6653 *Value = APValue(APValue::UninitArray(), N, N);
6656 for (unsigned I = 0; I != N; ++I)
6657 Value->getArrayInitializedElt(I) = Filler;
6659 // Initialize the elements.
6660 LValue ArrayElt = Subobject;
6661 ArrayElt.addArray(Info, E, CAT);
6662 for (unsigned I = 0; I != N; ++I)
6663 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6664 CAT->getElementType()) ||
6665 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6666 CAT->getElementType(), 1))
6672 if (!Type->isRecordType())
6675 return RecordExprEvaluator(Info, Subobject, *Value)
6676 .VisitCXXConstructExpr(E, Type);
6679 //===----------------------------------------------------------------------===//
6680 // Integer Evaluation
6682 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6683 // types and back in constant folding. Integer values are thus represented
6684 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6685 //===----------------------------------------------------------------------===//
6688 class IntExprEvaluator
6689 : public ExprEvaluatorBase<IntExprEvaluator> {
6692 IntExprEvaluator(EvalInfo &info, APValue &result)
6693 : ExprEvaluatorBaseTy(info), Result(result) {}
6695 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6696 assert(E->getType()->isIntegralOrEnumerationType() &&
6697 "Invalid evaluation result.");
6698 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6699 "Invalid evaluation result.");
6700 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6701 "Invalid evaluation result.");
6702 Result = APValue(SI);
6705 bool Success(const llvm::APSInt &SI, const Expr *E) {
6706 return Success(SI, E, Result);
6709 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6710 assert(E->getType()->isIntegralOrEnumerationType() &&
6711 "Invalid evaluation result.");
6712 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6713 "Invalid evaluation result.");
6714 Result = APValue(APSInt(I));
6715 Result.getInt().setIsUnsigned(
6716 E->getType()->isUnsignedIntegerOrEnumerationType());
6719 bool Success(const llvm::APInt &I, const Expr *E) {
6720 return Success(I, E, Result);
6723 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6724 assert(E->getType()->isIntegralOrEnumerationType() &&
6725 "Invalid evaluation result.");
6726 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6729 bool Success(uint64_t Value, const Expr *E) {
6730 return Success(Value, E, Result);
6733 bool Success(CharUnits Size, const Expr *E) {
6734 return Success(Size.getQuantity(), E);
6737 bool Success(const APValue &V, const Expr *E) {
6738 if (V.isLValue() || V.isAddrLabelDiff()) {
6742 return Success(V.getInt(), E);
6745 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6747 //===--------------------------------------------------------------------===//
6749 //===--------------------------------------------------------------------===//
6751 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6752 return Success(E->getValue(), E);
6754 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6755 return Success(E->getValue(), E);
6758 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6759 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6760 if (CheckReferencedDecl(E, E->getDecl()))
6763 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6765 bool VisitMemberExpr(const MemberExpr *E) {
6766 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6767 VisitIgnoredBaseExpression(E->getBase());
6771 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6774 bool VisitCallExpr(const CallExpr *E);
6775 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6776 bool VisitBinaryOperator(const BinaryOperator *E);
6777 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6778 bool VisitUnaryOperator(const UnaryOperator *E);
6780 bool VisitCastExpr(const CastExpr* E);
6781 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6783 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6784 return Success(E->getValue(), E);
6787 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6788 return Success(E->getValue(), E);
6791 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6792 if (Info.ArrayInitIndex == uint64_t(-1)) {
6793 // We were asked to evaluate this subexpression independent of the
6794 // enclosing ArrayInitLoopExpr. We can't do that.
6798 return Success(Info.ArrayInitIndex, E);
6801 // Note, GNU defines __null as an integer, not a pointer.
6802 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6803 return ZeroInitialization(E);
6806 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6807 return Success(E->getValue(), E);
6810 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6811 return Success(E->getValue(), E);
6814 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6815 return Success(E->getValue(), E);
6818 bool VisitUnaryReal(const UnaryOperator *E);
6819 bool VisitUnaryImag(const UnaryOperator *E);
6821 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
6822 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
6824 // FIXME: Missing: array subscript of vector, member of vector
6826 } // end anonymous namespace
6828 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6829 /// produce either the integer value or a pointer.
6831 /// GCC has a heinous extension which folds casts between pointer types and
6832 /// pointer-sized integral types. We support this by allowing the evaluation of
6833 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6834 /// Some simple arithmetic on such values is supported (they are treated much
6836 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
6838 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
6839 return IntExprEvaluator(Info, Result).Visit(E);
6842 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
6844 if (!EvaluateIntegerOrLValue(E, Val, Info))
6847 // FIXME: It would be better to produce the diagnostic for casting
6848 // a pointer to an integer.
6849 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
6852 Result = Val.getInt();
6856 /// Check whether the given declaration can be directly converted to an integral
6857 /// rvalue. If not, no diagnostic is produced; there are other things we can
6859 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
6860 // Enums are integer constant exprs.
6861 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
6862 // Check for signedness/width mismatches between E type and ECD value.
6863 bool SameSign = (ECD->getInitVal().isSigned()
6864 == E->getType()->isSignedIntegerOrEnumerationType());
6865 bool SameWidth = (ECD->getInitVal().getBitWidth()
6866 == Info.Ctx.getIntWidth(E->getType()));
6867 if (SameSign && SameWidth)
6868 return Success(ECD->getInitVal(), E);
6870 // Get rid of mismatch (otherwise Success assertions will fail)
6871 // by computing a new value matching the type of E.
6872 llvm::APSInt Val = ECD->getInitVal();
6874 Val.setIsSigned(!ECD->getInitVal().isSigned());
6876 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6877 return Success(Val, E);
6883 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6885 static int EvaluateBuiltinClassifyType(const CallExpr *E,
6886 const LangOptions &LangOpts) {
6887 // The following enum mimics the values returned by GCC.
6888 // FIXME: Does GCC differ between lvalue and rvalue references here?
6889 enum gcc_type_class {
6891 void_type_class, integer_type_class, char_type_class,
6892 enumeral_type_class, boolean_type_class,
6893 pointer_type_class, reference_type_class, offset_type_class,
6894 real_type_class, complex_type_class,
6895 function_type_class, method_type_class,
6896 record_type_class, union_type_class,
6897 array_type_class, string_type_class,
6901 // If no argument was supplied, default to "no_type_class". This isn't
6902 // ideal, however it is what gcc does.
6903 if (E->getNumArgs() == 0)
6904 return no_type_class;
6906 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6907 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6909 switch (CanTy->getTypeClass()) {
6910 #define TYPE(ID, BASE)
6911 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6912 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6913 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6914 #include "clang/AST/TypeNodes.def"
6915 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6918 switch (BT->getKind()) {
6919 #define BUILTIN_TYPE(ID, SINGLETON_ID)
6920 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6921 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6922 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6923 #include "clang/AST/BuiltinTypes.def"
6924 case BuiltinType::Void:
6925 return void_type_class;
6927 case BuiltinType::Bool:
6928 return boolean_type_class;
6930 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6931 case BuiltinType::UChar:
6932 case BuiltinType::UShort:
6933 case BuiltinType::UInt:
6934 case BuiltinType::ULong:
6935 case BuiltinType::ULongLong:
6936 case BuiltinType::UInt128:
6937 return integer_type_class;
6939 case BuiltinType::NullPtr:
6940 return pointer_type_class;
6942 case BuiltinType::WChar_U:
6943 case BuiltinType::Char16:
6944 case BuiltinType::Char32:
6945 case BuiltinType::ObjCId:
6946 case BuiltinType::ObjCClass:
6947 case BuiltinType::ObjCSel:
6948 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6949 case BuiltinType::Id:
6950 #include "clang/Basic/OpenCLImageTypes.def"
6951 case BuiltinType::OCLSampler:
6952 case BuiltinType::OCLEvent:
6953 case BuiltinType::OCLClkEvent:
6954 case BuiltinType::OCLQueue:
6955 case BuiltinType::OCLNDRange:
6956 case BuiltinType::OCLReserveID:
6957 case BuiltinType::Dependent:
6958 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6962 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6966 return pointer_type_class;
6969 case Type::MemberPointer:
6970 if (CanTy->isMemberDataPointerType())
6971 return offset_type_class;
6973 // We expect member pointers to be either data or function pointers,
6975 assert(CanTy->isMemberFunctionPointerType());
6976 return method_type_class;
6980 return complex_type_class;
6982 case Type::FunctionNoProto:
6983 case Type::FunctionProto:
6984 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6987 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6988 switch (RT->getDecl()->getTagKind()) {
6989 case TagTypeKind::TTK_Struct:
6990 case TagTypeKind::TTK_Class:
6991 case TagTypeKind::TTK_Interface:
6992 return record_type_class;
6994 case TagTypeKind::TTK_Enum:
6995 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6997 case TagTypeKind::TTK_Union:
6998 return union_type_class;
7001 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7003 case Type::ConstantArray:
7004 case Type::VariableArray:
7005 case Type::IncompleteArray:
7006 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7008 case Type::BlockPointer:
7009 case Type::LValueReference:
7010 case Type::RValueReference:
7012 case Type::ExtVector:
7014 case Type::ObjCObject:
7015 case Type::ObjCInterface:
7016 case Type::ObjCObjectPointer:
7019 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7022 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7025 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7026 /// __builtin_constant_p when applied to the given lvalue.
7028 /// An lvalue is only "constant" if it is a pointer or reference to the first
7029 /// character of a string literal.
7030 template<typename LValue>
7031 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7032 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7033 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7036 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7037 /// GCC as we can manage.
7038 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7039 QualType ArgType = Arg->getType();
7041 // __builtin_constant_p always has one operand. The rules which gcc follows
7042 // are not precisely documented, but are as follows:
7044 // - If the operand is of integral, floating, complex or enumeration type,
7045 // and can be folded to a known value of that type, it returns 1.
7046 // - If the operand and can be folded to a pointer to the first character
7047 // of a string literal (or such a pointer cast to an integral type), it
7050 // Otherwise, it returns 0.
7052 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7053 // its support for this does not currently work.
7054 if (ArgType->isIntegralOrEnumerationType()) {
7055 Expr::EvalResult Result;
7056 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7059 APValue &V = Result.Val;
7060 if (V.getKind() == APValue::Int)
7062 if (V.getKind() == APValue::LValue)
7063 return EvaluateBuiltinConstantPForLValue(V);
7064 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7065 return Arg->isEvaluatable(Ctx);
7066 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7068 Expr::EvalStatus Status;
7069 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7070 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7071 : EvaluatePointer(Arg, LV, Info)) &&
7072 !Status.HasSideEffects)
7073 return EvaluateBuiltinConstantPForLValue(LV);
7076 // Anything else isn't considered to be sufficiently constant.
7080 /// Retrieves the "underlying object type" of the given expression,
7081 /// as used by __builtin_object_size.
7082 static QualType getObjectType(APValue::LValueBase B) {
7083 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7084 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7085 return VD->getType();
7086 } else if (const Expr *E = B.get<const Expr*>()) {
7087 if (isa<CompoundLiteralExpr>(E))
7088 return E->getType();
7094 /// A more selective version of E->IgnoreParenCasts for
7095 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7096 /// to change the type of E.
7097 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7099 /// Always returns an RValue with a pointer representation.
7100 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7101 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7103 auto *NoParens = E->IgnoreParens();
7104 auto *Cast = dyn_cast<CastExpr>(NoParens);
7105 if (Cast == nullptr)
7108 // We only conservatively allow a few kinds of casts, because this code is
7109 // inherently a simple solution that seeks to support the common case.
7110 auto CastKind = Cast->getCastKind();
7111 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7112 CastKind != CK_AddressSpaceConversion)
7115 auto *SubExpr = Cast->getSubExpr();
7116 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7118 return ignorePointerCastsAndParens(SubExpr);
7121 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7122 /// record layout. e.g.
7123 /// struct { struct { int a, b; } fst, snd; } obj;
7129 /// obj.snd.b // yes
7131 /// Please note: this function is specialized for how __builtin_object_size
7132 /// views "objects".
7134 /// If this encounters an invalid RecordDecl, it will always return true.
7135 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7136 assert(!LVal.Designator.Invalid);
7138 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7139 const RecordDecl *Parent = FD->getParent();
7140 Invalid = Parent->isInvalidDecl();
7141 if (Invalid || Parent->isUnion())
7143 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7144 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7147 auto &Base = LVal.getLValueBase();
7148 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7149 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7151 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7153 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7154 for (auto *FD : IFD->chain()) {
7156 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7163 QualType BaseType = getType(Base);
7164 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7165 assert(isBaseAnAllocSizeCall(Base) &&
7166 "Unsized array in non-alloc_size call?");
7167 // If this is an alloc_size base, we should ignore the initial array index
7169 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7172 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7173 const auto &Entry = LVal.Designator.Entries[I];
7174 if (BaseType->isArrayType()) {
7175 // Because __builtin_object_size treats arrays as objects, we can ignore
7176 // the index iff this is the last array in the Designator.
7179 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7180 uint64_t Index = Entry.ArrayIndex;
7181 if (Index + 1 != CAT->getSize())
7183 BaseType = CAT->getElementType();
7184 } else if (BaseType->isAnyComplexType()) {
7185 const auto *CT = BaseType->castAs<ComplexType>();
7186 uint64_t Index = Entry.ArrayIndex;
7189 BaseType = CT->getElementType();
7190 } else if (auto *FD = getAsField(Entry)) {
7192 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7194 BaseType = FD->getType();
7196 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7203 /// Tests to see if the LValue has a user-specified designator (that isn't
7204 /// necessarily valid). Note that this always returns 'true' if the LValue has
7205 /// an unsized array as its first designator entry, because there's currently no
7206 /// way to tell if the user typed *foo or foo[0].
7207 static bool refersToCompleteObject(const LValue &LVal) {
7208 if (LVal.Designator.Invalid)
7211 if (!LVal.Designator.Entries.empty())
7212 return LVal.Designator.isMostDerivedAnUnsizedArray();
7214 if (!LVal.InvalidBase)
7217 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7219 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7220 return !E || !isa<MemberExpr>(E);
7223 /// Attempts to detect a user writing into a piece of memory that's impossible
7224 /// to figure out the size of by just using types.
7225 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7226 const SubobjectDesignator &Designator = LVal.Designator;
7228 // - Users can only write off of the end when we have an invalid base. Invalid
7229 // bases imply we don't know where the memory came from.
7230 // - We used to be a bit more aggressive here; we'd only be conservative if
7231 // the array at the end was flexible, or if it had 0 or 1 elements. This
7232 // broke some common standard library extensions (PR30346), but was
7233 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7234 // with some sort of whitelist. OTOH, it seems that GCC is always
7235 // conservative with the last element in structs (if it's an array), so our
7236 // current behavior is more compatible than a whitelisting approach would
7238 return LVal.InvalidBase &&
7239 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7240 Designator.MostDerivedIsArrayElement &&
7241 isDesignatorAtObjectEnd(Ctx, LVal);
7244 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7245 /// Fails if the conversion would cause loss of precision.
7246 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7247 CharUnits &Result) {
7248 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7249 if (Int.ugt(CharUnitsMax))
7251 Result = CharUnits::fromQuantity(Int.getZExtValue());
7255 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7256 /// determine how many bytes exist from the beginning of the object to either
7257 /// the end of the current subobject, or the end of the object itself, depending
7258 /// on what the LValue looks like + the value of Type.
7260 /// If this returns false, the value of Result is undefined.
7261 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7262 unsigned Type, const LValue &LVal,
7263 CharUnits &EndOffset) {
7264 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7266 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7267 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7269 return HandleSizeof(Info, ExprLoc, Ty, Result);
7272 // We want to evaluate the size of the entire object. This is a valid fallback
7273 // for when Type=1 and the designator is invalid, because we're asked for an
7275 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7276 // Type=3 wants a lower bound, so we can't fall back to this.
7277 if (Type == 3 && !DetermineForCompleteObject)
7280 llvm::APInt APEndOffset;
7281 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7282 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7283 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7285 if (LVal.InvalidBase)
7288 QualType BaseTy = getObjectType(LVal.getLValueBase());
7289 return CheckedHandleSizeof(BaseTy, EndOffset);
7292 // We want to evaluate the size of a subobject.
7293 const SubobjectDesignator &Designator = LVal.Designator;
7295 // The following is a moderately common idiom in C:
7297 // struct Foo { int a; char c[1]; };
7298 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7299 // strcpy(&F->c[0], Bar);
7301 // In order to not break too much legacy code, we need to support it.
7302 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7303 // If we can resolve this to an alloc_size call, we can hand that back,
7304 // because we know for certain how many bytes there are to write to.
7305 llvm::APInt APEndOffset;
7306 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7307 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7308 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7310 // If we cannot determine the size of the initial allocation, then we can't
7311 // given an accurate upper-bound. However, we are still able to give
7312 // conservative lower-bounds for Type=3.
7317 CharUnits BytesPerElem;
7318 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7321 // According to the GCC documentation, we want the size of the subobject
7322 // denoted by the pointer. But that's not quite right -- what we actually
7323 // want is the size of the immediately-enclosing array, if there is one.
7324 int64_t ElemsRemaining;
7325 if (Designator.MostDerivedIsArrayElement &&
7326 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7327 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7328 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7329 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7331 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7334 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7338 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7339 /// returns true and stores the result in @p Size.
7341 /// If @p WasError is non-null, this will report whether the failure to evaluate
7342 /// is to be treated as an Error in IntExprEvaluator.
7343 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7344 EvalInfo &Info, uint64_t &Size) {
7345 // Determine the denoted object.
7348 // The operand of __builtin_object_size is never evaluated for side-effects.
7349 // If there are any, but we can determine the pointed-to object anyway, then
7350 // ignore the side-effects.
7351 SpeculativeEvaluationRAII SpeculativeEval(Info);
7352 FoldOffsetRAII Fold(Info);
7354 if (E->isGLValue()) {
7355 // It's possible for us to be given GLValues if we're called via
7356 // Expr::tryEvaluateObjectSize.
7358 if (!EvaluateAsRValue(Info, E, RVal))
7360 LVal.setFrom(Info.Ctx, RVal);
7361 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info))
7365 // If we point to before the start of the object, there are no accessible
7367 if (LVal.getLValueOffset().isNegative()) {
7372 CharUnits EndOffset;
7373 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7376 // If we've fallen outside of the end offset, just pretend there's nothing to
7377 // write to/read from.
7378 if (EndOffset <= LVal.getLValueOffset())
7381 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7385 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7386 if (unsigned BuiltinOp = E->getBuiltinCallee())
7387 return VisitBuiltinCallExpr(E, BuiltinOp);
7389 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7392 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7393 unsigned BuiltinOp) {
7394 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7396 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7398 case Builtin::BI__builtin_object_size: {
7399 // The type was checked when we built the expression.
7401 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7402 assert(Type <= 3 && "unexpected type");
7405 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7406 return Success(Size, E);
7408 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7409 return Success((Type & 2) ? 0 : -1, E);
7411 // Expression had no side effects, but we couldn't statically determine the
7412 // size of the referenced object.
7413 switch (Info.EvalMode) {
7414 case EvalInfo::EM_ConstantExpression:
7415 case EvalInfo::EM_PotentialConstantExpression:
7416 case EvalInfo::EM_ConstantFold:
7417 case EvalInfo::EM_EvaluateForOverflow:
7418 case EvalInfo::EM_IgnoreSideEffects:
7419 case EvalInfo::EM_OffsetFold:
7420 // Leave it to IR generation.
7422 case EvalInfo::EM_ConstantExpressionUnevaluated:
7423 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7424 // Reduce it to a constant now.
7425 return Success((Type & 2) ? 0 : -1, E);
7428 llvm_unreachable("unexpected EvalMode");
7431 case Builtin::BI__builtin_bswap16:
7432 case Builtin::BI__builtin_bswap32:
7433 case Builtin::BI__builtin_bswap64: {
7435 if (!EvaluateInteger(E->getArg(0), Val, Info))
7438 return Success(Val.byteSwap(), E);
7441 case Builtin::BI__builtin_classify_type:
7442 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7444 // FIXME: BI__builtin_clrsb
7445 // FIXME: BI__builtin_clrsbl
7446 // FIXME: BI__builtin_clrsbll
7448 case Builtin::BI__builtin_clz:
7449 case Builtin::BI__builtin_clzl:
7450 case Builtin::BI__builtin_clzll:
7451 case Builtin::BI__builtin_clzs: {
7453 if (!EvaluateInteger(E->getArg(0), Val, Info))
7458 return Success(Val.countLeadingZeros(), E);
7461 case Builtin::BI__builtin_constant_p:
7462 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7464 case Builtin::BI__builtin_ctz:
7465 case Builtin::BI__builtin_ctzl:
7466 case Builtin::BI__builtin_ctzll:
7467 case Builtin::BI__builtin_ctzs: {
7469 if (!EvaluateInteger(E->getArg(0), Val, Info))
7474 return Success(Val.countTrailingZeros(), E);
7477 case Builtin::BI__builtin_eh_return_data_regno: {
7478 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7479 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7480 return Success(Operand, E);
7483 case Builtin::BI__builtin_expect:
7484 return Visit(E->getArg(0));
7486 case Builtin::BI__builtin_ffs:
7487 case Builtin::BI__builtin_ffsl:
7488 case Builtin::BI__builtin_ffsll: {
7490 if (!EvaluateInteger(E->getArg(0), Val, Info))
7493 unsigned N = Val.countTrailingZeros();
7494 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7497 case Builtin::BI__builtin_fpclassify: {
7499 if (!EvaluateFloat(E->getArg(5), Val, Info))
7502 switch (Val.getCategory()) {
7503 case APFloat::fcNaN: Arg = 0; break;
7504 case APFloat::fcInfinity: Arg = 1; break;
7505 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7506 case APFloat::fcZero: Arg = 4; break;
7508 return Visit(E->getArg(Arg));
7511 case Builtin::BI__builtin_isinf_sign: {
7513 return EvaluateFloat(E->getArg(0), Val, Info) &&
7514 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7517 case Builtin::BI__builtin_isinf: {
7519 return EvaluateFloat(E->getArg(0), Val, Info) &&
7520 Success(Val.isInfinity() ? 1 : 0, E);
7523 case Builtin::BI__builtin_isfinite: {
7525 return EvaluateFloat(E->getArg(0), Val, Info) &&
7526 Success(Val.isFinite() ? 1 : 0, E);
7529 case Builtin::BI__builtin_isnan: {
7531 return EvaluateFloat(E->getArg(0), Val, Info) &&
7532 Success(Val.isNaN() ? 1 : 0, E);
7535 case Builtin::BI__builtin_isnormal: {
7537 return EvaluateFloat(E->getArg(0), Val, Info) &&
7538 Success(Val.isNormal() ? 1 : 0, E);
7541 case Builtin::BI__builtin_parity:
7542 case Builtin::BI__builtin_parityl:
7543 case Builtin::BI__builtin_parityll: {
7545 if (!EvaluateInteger(E->getArg(0), Val, Info))
7548 return Success(Val.countPopulation() % 2, E);
7551 case Builtin::BI__builtin_popcount:
7552 case Builtin::BI__builtin_popcountl:
7553 case Builtin::BI__builtin_popcountll: {
7555 if (!EvaluateInteger(E->getArg(0), Val, Info))
7558 return Success(Val.countPopulation(), E);
7561 case Builtin::BIstrlen:
7562 case Builtin::BIwcslen:
7563 // A call to strlen is not a constant expression.
7564 if (Info.getLangOpts().CPlusPlus11)
7565 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7566 << /*isConstexpr*/0 << /*isConstructor*/0
7567 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7569 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7571 case Builtin::BI__builtin_strlen:
7572 case Builtin::BI__builtin_wcslen: {
7573 // As an extension, we support __builtin_strlen() as a constant expression,
7574 // and support folding strlen() to a constant.
7576 if (!EvaluatePointer(E->getArg(0), String, Info))
7579 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7581 // Fast path: if it's a string literal, search the string value.
7582 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7583 String.getLValueBase().dyn_cast<const Expr *>())) {
7584 // The string literal may have embedded null characters. Find the first
7585 // one and truncate there.
7586 StringRef Str = S->getBytes();
7587 int64_t Off = String.Offset.getQuantity();
7588 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7589 S->getCharByteWidth() == 1 &&
7590 // FIXME: Add fast-path for wchar_t too.
7591 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7592 Str = Str.substr(Off);
7594 StringRef::size_type Pos = Str.find(0);
7595 if (Pos != StringRef::npos)
7596 Str = Str.substr(0, Pos);
7598 return Success(Str.size(), E);
7601 // Fall through to slow path to issue appropriate diagnostic.
7604 // Slow path: scan the bytes of the string looking for the terminating 0.
7605 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7607 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7611 return Success(Strlen, E);
7612 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7617 case Builtin::BIstrcmp:
7618 case Builtin::BIwcscmp:
7619 case Builtin::BIstrncmp:
7620 case Builtin::BIwcsncmp:
7621 case Builtin::BImemcmp:
7622 case Builtin::BIwmemcmp:
7623 // A call to strlen is not a constant expression.
7624 if (Info.getLangOpts().CPlusPlus11)
7625 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7626 << /*isConstexpr*/0 << /*isConstructor*/0
7627 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7629 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7631 case Builtin::BI__builtin_strcmp:
7632 case Builtin::BI__builtin_wcscmp:
7633 case Builtin::BI__builtin_strncmp:
7634 case Builtin::BI__builtin_wcsncmp:
7635 case Builtin::BI__builtin_memcmp:
7636 case Builtin::BI__builtin_wmemcmp: {
7637 LValue String1, String2;
7638 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7639 !EvaluatePointer(E->getArg(1), String2, Info))
7642 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7644 uint64_t MaxLength = uint64_t(-1);
7645 if (BuiltinOp != Builtin::BIstrcmp &&
7646 BuiltinOp != Builtin::BIwcscmp &&
7647 BuiltinOp != Builtin::BI__builtin_strcmp &&
7648 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7650 if (!EvaluateInteger(E->getArg(2), N, Info))
7652 MaxLength = N.getExtValue();
7654 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7655 BuiltinOp != Builtin::BIwmemcmp &&
7656 BuiltinOp != Builtin::BI__builtin_memcmp &&
7657 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7658 for (; MaxLength; --MaxLength) {
7659 APValue Char1, Char2;
7660 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7661 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7662 !Char1.isInt() || !Char2.isInt())
7664 if (Char1.getInt() != Char2.getInt())
7665 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7666 if (StopAtNull && !Char1.getInt())
7667 return Success(0, E);
7668 assert(!(StopAtNull && !Char2.getInt()));
7669 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7670 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7673 // We hit the strncmp / memcmp limit.
7674 return Success(0, E);
7677 case Builtin::BI__atomic_always_lock_free:
7678 case Builtin::BI__atomic_is_lock_free:
7679 case Builtin::BI__c11_atomic_is_lock_free: {
7681 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7684 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7685 // of two less than the maximum inline atomic width, we know it is
7686 // lock-free. If the size isn't a power of two, or greater than the
7687 // maximum alignment where we promote atomics, we know it is not lock-free
7688 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7689 // the answer can only be determined at runtime; for example, 16-byte
7690 // atomics have lock-free implementations on some, but not all,
7691 // x86-64 processors.
7693 // Check power-of-two.
7694 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7695 if (Size.isPowerOfTwo()) {
7696 // Check against inlining width.
7697 unsigned InlineWidthBits =
7698 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7699 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7700 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7701 Size == CharUnits::One() ||
7702 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7703 Expr::NPC_NeverValueDependent))
7704 // OK, we will inline appropriately-aligned operations of this size,
7705 // and _Atomic(T) is appropriately-aligned.
7706 return Success(1, E);
7708 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7709 castAs<PointerType>()->getPointeeType();
7710 if (!PointeeType->isIncompleteType() &&
7711 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7712 // OK, we will inline operations on this object.
7713 return Success(1, E);
7718 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7719 Success(0, E) : Error(E);
7724 static bool HasSameBase(const LValue &A, const LValue &B) {
7725 if (!A.getLValueBase())
7726 return !B.getLValueBase();
7727 if (!B.getLValueBase())
7730 if (A.getLValueBase().getOpaqueValue() !=
7731 B.getLValueBase().getOpaqueValue()) {
7732 const Decl *ADecl = GetLValueBaseDecl(A);
7735 const Decl *BDecl = GetLValueBaseDecl(B);
7736 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7740 return IsGlobalLValue(A.getLValueBase()) ||
7741 A.getLValueCallIndex() == B.getLValueCallIndex();
7744 /// \brief Determine whether this is a pointer past the end of the complete
7745 /// object referred to by the lvalue.
7746 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7748 // A null pointer can be viewed as being "past the end" but we don't
7749 // choose to look at it that way here.
7750 if (!LV.getLValueBase())
7753 // If the designator is valid and refers to a subobject, we're not pointing
7755 if (!LV.getLValueDesignator().Invalid &&
7756 !LV.getLValueDesignator().isOnePastTheEnd())
7759 // A pointer to an incomplete type might be past-the-end if the type's size is
7760 // zero. We cannot tell because the type is incomplete.
7761 QualType Ty = getType(LV.getLValueBase());
7762 if (Ty->isIncompleteType())
7765 // We're a past-the-end pointer if we point to the byte after the object,
7766 // no matter what our type or path is.
7767 auto Size = Ctx.getTypeSizeInChars(Ty);
7768 return LV.getLValueOffset() == Size;
7773 /// \brief Data recursive integer evaluator of certain binary operators.
7775 /// We use a data recursive algorithm for binary operators so that we are able
7776 /// to handle extreme cases of chained binary operators without causing stack
7778 class DataRecursiveIntBinOpEvaluator {
7783 EvalResult() : Failed(false) { }
7785 void swap(EvalResult &RHS) {
7787 Failed = RHS.Failed;
7794 EvalResult LHSResult; // meaningful only for binary operator expression.
7795 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7798 Job(Job &&) = default;
7800 void startSpeculativeEval(EvalInfo &Info) {
7801 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7805 SpeculativeEvaluationRAII SpecEvalRAII;
7808 SmallVector<Job, 16> Queue;
7810 IntExprEvaluator &IntEval;
7812 APValue &FinalResult;
7815 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7816 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7818 /// \brief True if \param E is a binary operator that we are going to handle
7819 /// data recursively.
7820 /// We handle binary operators that are comma, logical, or that have operands
7821 /// with integral or enumeration type.
7822 static bool shouldEnqueue(const BinaryOperator *E) {
7823 return E->getOpcode() == BO_Comma ||
7826 E->getType()->isIntegralOrEnumerationType() &&
7827 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7828 E->getRHS()->getType()->isIntegralOrEnumerationType());
7831 bool Traverse(const BinaryOperator *E) {
7833 EvalResult PrevResult;
7834 while (!Queue.empty())
7835 process(PrevResult);
7837 if (PrevResult.Failed) return false;
7839 FinalResult.swap(PrevResult.Val);
7844 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7845 return IntEval.Success(Value, E, Result);
7847 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7848 return IntEval.Success(Value, E, Result);
7850 bool Error(const Expr *E) {
7851 return IntEval.Error(E);
7853 bool Error(const Expr *E, diag::kind D) {
7854 return IntEval.Error(E, D);
7857 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7858 return Info.CCEDiag(E, D);
7861 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7862 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7863 bool &SuppressRHSDiags);
7865 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7866 const BinaryOperator *E, APValue &Result);
7868 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7869 Result.Failed = !Evaluate(Result.Val, Info, E);
7871 Result.Val = APValue();
7874 void process(EvalResult &Result);
7876 void enqueue(const Expr *E) {
7877 E = E->IgnoreParens();
7878 Queue.resize(Queue.size()+1);
7880 Queue.back().Kind = Job::AnyExprKind;
7886 bool DataRecursiveIntBinOpEvaluator::
7887 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
7888 bool &SuppressRHSDiags) {
7889 if (E->getOpcode() == BO_Comma) {
7890 // Ignore LHS but note if we could not evaluate it.
7891 if (LHSResult.Failed)
7892 return Info.noteSideEffect();
7896 if (E->isLogicalOp()) {
7898 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
7899 // We were able to evaluate the LHS, see if we can get away with not
7900 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
7901 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7902 Success(LHSAsBool, E, LHSResult.Val);
7903 return false; // Ignore RHS
7906 LHSResult.Failed = true;
7908 // Since we weren't able to evaluate the left hand side, it
7909 // might have had side effects.
7910 if (!Info.noteSideEffect())
7913 // We can't evaluate the LHS; however, sometimes the result
7914 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7915 // Don't ignore RHS and suppress diagnostics from this arm.
7916 SuppressRHSDiags = true;
7922 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7923 E->getRHS()->getType()->isIntegralOrEnumerationType());
7925 if (LHSResult.Failed && !Info.noteFailure())
7926 return false; // Ignore RHS;
7931 bool DataRecursiveIntBinOpEvaluator::
7932 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7933 const BinaryOperator *E, APValue &Result) {
7934 if (E->getOpcode() == BO_Comma) {
7935 if (RHSResult.Failed)
7937 Result = RHSResult.Val;
7941 if (E->isLogicalOp()) {
7942 bool lhsResult, rhsResult;
7943 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7944 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7948 if (E->getOpcode() == BO_LOr)
7949 return Success(lhsResult || rhsResult, E, Result);
7951 return Success(lhsResult && rhsResult, E, Result);
7955 // We can't evaluate the LHS; however, sometimes the result
7956 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7957 if (rhsResult == (E->getOpcode() == BO_LOr))
7958 return Success(rhsResult, E, Result);
7965 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7966 E->getRHS()->getType()->isIntegralOrEnumerationType());
7968 if (LHSResult.Failed || RHSResult.Failed)
7971 const APValue &LHSVal = LHSResult.Val;
7972 const APValue &RHSVal = RHSResult.Val;
7974 // Handle cases like (unsigned long)&a + 4.
7975 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7977 CharUnits AdditionalOffset =
7978 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
7979 if (E->getOpcode() == BO_Add)
7980 Result.getLValueOffset() += AdditionalOffset;
7982 Result.getLValueOffset() -= AdditionalOffset;
7986 // Handle cases like 4 + (unsigned long)&a
7987 if (E->getOpcode() == BO_Add &&
7988 RHSVal.isLValue() && LHSVal.isInt()) {
7990 Result.getLValueOffset() +=
7991 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
7995 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7996 // Handle (intptr_t)&&A - (intptr_t)&&B.
7997 if (!LHSVal.getLValueOffset().isZero() ||
7998 !RHSVal.getLValueOffset().isZero())
8000 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8001 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8002 if (!LHSExpr || !RHSExpr)
8004 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8005 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8006 if (!LHSAddrExpr || !RHSAddrExpr)
8008 // Make sure both labels come from the same function.
8009 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8010 RHSAddrExpr->getLabel()->getDeclContext())
8012 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8016 // All the remaining cases expect both operands to be an integer
8017 if (!LHSVal.isInt() || !RHSVal.isInt())
8020 // Set up the width and signedness manually, in case it can't be deduced
8021 // from the operation we're performing.
8022 // FIXME: Don't do this in the cases where we can deduce it.
8023 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8024 E->getType()->isUnsignedIntegerOrEnumerationType());
8025 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8026 RHSVal.getInt(), Value))
8028 return Success(Value, E, Result);
8031 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8032 Job &job = Queue.back();
8035 case Job::AnyExprKind: {
8036 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8037 if (shouldEnqueue(Bop)) {
8038 job.Kind = Job::BinOpKind;
8039 enqueue(Bop->getLHS());
8044 EvaluateExpr(job.E, Result);
8049 case Job::BinOpKind: {
8050 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8051 bool SuppressRHSDiags = false;
8052 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8056 if (SuppressRHSDiags)
8057 job.startSpeculativeEval(Info);
8058 job.LHSResult.swap(Result);
8059 job.Kind = Job::BinOpVisitedLHSKind;
8060 enqueue(Bop->getRHS());
8064 case Job::BinOpVisitedLHSKind: {
8065 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8068 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8074 llvm_unreachable("Invalid Job::Kind!");
8078 /// Used when we determine that we should fail, but can keep evaluating prior to
8079 /// noting that we had a failure.
8080 class DelayedNoteFailureRAII {
8085 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8086 : Info(Info), NoteFailure(NoteFailure) {}
8087 ~DelayedNoteFailureRAII() {
8089 bool ContinueAfterFailure = Info.noteFailure();
8090 (void)ContinueAfterFailure;
8091 assert(ContinueAfterFailure &&
8092 "Shouldn't have kept evaluating on failure.");
8098 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8099 // We don't call noteFailure immediately because the assignment happens after
8100 // we evaluate LHS and RHS.
8101 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8104 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8105 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8106 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8108 QualType LHSTy = E->getLHS()->getType();
8109 QualType RHSTy = E->getRHS()->getType();
8111 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8112 ComplexValue LHS, RHS;
8114 if (E->isAssignmentOp()) {
8116 EvaluateLValue(E->getLHS(), LV, Info);
8118 } else if (LHSTy->isRealFloatingType()) {
8119 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8121 LHS.makeComplexFloat();
8122 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8125 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8127 if (!LHSOK && !Info.noteFailure())
8130 if (E->getRHS()->getType()->isRealFloatingType()) {
8131 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8133 RHS.makeComplexFloat();
8134 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8135 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8138 if (LHS.isComplexFloat()) {
8139 APFloat::cmpResult CR_r =
8140 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8141 APFloat::cmpResult CR_i =
8142 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8144 if (E->getOpcode() == BO_EQ)
8145 return Success((CR_r == APFloat::cmpEqual &&
8146 CR_i == APFloat::cmpEqual), E);
8148 assert(E->getOpcode() == BO_NE &&
8149 "Invalid complex comparison.");
8150 return Success(((CR_r == APFloat::cmpGreaterThan ||
8151 CR_r == APFloat::cmpLessThan ||
8152 CR_r == APFloat::cmpUnordered) ||
8153 (CR_i == APFloat::cmpGreaterThan ||
8154 CR_i == APFloat::cmpLessThan ||
8155 CR_i == APFloat::cmpUnordered)), E);
8158 if (E->getOpcode() == BO_EQ)
8159 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8160 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8162 assert(E->getOpcode() == BO_NE &&
8163 "Invalid compex comparison.");
8164 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8165 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8170 if (LHSTy->isRealFloatingType() &&
8171 RHSTy->isRealFloatingType()) {
8172 APFloat RHS(0.0), LHS(0.0);
8174 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8175 if (!LHSOK && !Info.noteFailure())
8178 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8181 APFloat::cmpResult CR = LHS.compare(RHS);
8183 switch (E->getOpcode()) {
8185 llvm_unreachable("Invalid binary operator!");
8187 return Success(CR == APFloat::cmpLessThan, E);
8189 return Success(CR == APFloat::cmpGreaterThan, E);
8191 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8193 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8196 return Success(CR == APFloat::cmpEqual, E);
8198 return Success(CR == APFloat::cmpGreaterThan
8199 || CR == APFloat::cmpLessThan
8200 || CR == APFloat::cmpUnordered, E);
8204 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8205 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8206 LValue LHSValue, RHSValue;
8208 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8209 if (!LHSOK && !Info.noteFailure())
8212 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8215 // Reject differing bases from the normal codepath; we special-case
8216 // comparisons to null.
8217 if (!HasSameBase(LHSValue, RHSValue)) {
8218 if (E->getOpcode() == BO_Sub) {
8219 // Handle &&A - &&B.
8220 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8222 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8223 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8224 if (!LHSExpr || !RHSExpr)
8226 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8227 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8228 if (!LHSAddrExpr || !RHSAddrExpr)
8230 // Make sure both labels come from the same function.
8231 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8232 RHSAddrExpr->getLabel()->getDeclContext())
8234 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8236 // Inequalities and subtractions between unrelated pointers have
8237 // unspecified or undefined behavior.
8238 if (!E->isEqualityOp())
8240 // A constant address may compare equal to the address of a symbol.
8241 // The one exception is that address of an object cannot compare equal
8242 // to a null pointer constant.
8243 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8244 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8246 // It's implementation-defined whether distinct literals will have
8247 // distinct addresses. In clang, the result of such a comparison is
8248 // unspecified, so it is not a constant expression. However, we do know
8249 // that the address of a literal will be non-null.
8250 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8251 LHSValue.Base && RHSValue.Base)
8253 // We can't tell whether weak symbols will end up pointing to the same
8255 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8257 // We can't compare the address of the start of one object with the
8258 // past-the-end address of another object, per C++ DR1652.
8259 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8260 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8261 (RHSValue.Base && RHSValue.Offset.isZero() &&
8262 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8264 // We can't tell whether an object is at the same address as another
8265 // zero sized object.
8266 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8267 (LHSValue.Base && isZeroSized(RHSValue)))
8269 // Pointers with different bases cannot represent the same object.
8270 // (Note that clang defaults to -fmerge-all-constants, which can
8271 // lead to inconsistent results for comparisons involving the address
8272 // of a constant; this generally doesn't matter in practice.)
8273 return Success(E->getOpcode() == BO_NE, E);
8276 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8277 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8279 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8280 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8282 if (E->getOpcode() == BO_Sub) {
8283 // C++11 [expr.add]p6:
8284 // Unless both pointers point to elements of the same array object, or
8285 // one past the last element of the array object, the behavior is
8287 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8288 !AreElementsOfSameArray(getType(LHSValue.Base),
8289 LHSDesignator, RHSDesignator))
8290 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8292 QualType Type = E->getLHS()->getType();
8293 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8295 CharUnits ElementSize;
8296 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8299 // As an extension, a type may have zero size (empty struct or union in
8300 // C, array of zero length). Pointer subtraction in such cases has
8301 // undefined behavior, so is not constant.
8302 if (ElementSize.isZero()) {
8303 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8308 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8309 // and produce incorrect results when it overflows. Such behavior
8310 // appears to be non-conforming, but is common, so perhaps we should
8311 // assume the standard intended for such cases to be undefined behavior
8312 // and check for them.
8314 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8315 // overflow in the final conversion to ptrdiff_t.
8317 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8319 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8321 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8322 APSInt TrueResult = (LHS - RHS) / ElemSize;
8323 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8325 if (Result.extend(65) != TrueResult &&
8326 !HandleOverflow(Info, E, TrueResult, E->getType()))
8328 return Success(Result, E);
8331 // C++11 [expr.rel]p3:
8332 // Pointers to void (after pointer conversions) can be compared, with a
8333 // result defined as follows: If both pointers represent the same
8334 // address or are both the null pointer value, the result is true if the
8335 // operator is <= or >= and false otherwise; otherwise the result is
8337 // We interpret this as applying to pointers to *cv* void.
8338 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8339 E->isRelationalOp())
8340 CCEDiag(E, diag::note_constexpr_void_comparison);
8342 // C++11 [expr.rel]p2:
8343 // - If two pointers point to non-static data members of the same object,
8344 // or to subobjects or array elements fo such members, recursively, the
8345 // pointer to the later declared member compares greater provided the
8346 // two members have the same access control and provided their class is
8349 // - Otherwise pointer comparisons are unspecified.
8350 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8351 E->isRelationalOp()) {
8354 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8355 RHSDesignator, WasArrayIndex);
8356 // At the point where the designators diverge, the comparison has a
8357 // specified value if:
8358 // - we are comparing array indices
8359 // - we are comparing fields of a union, or fields with the same access
8360 // Otherwise, the result is unspecified and thus the comparison is not a
8361 // constant expression.
8362 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8363 Mismatch < RHSDesignator.Entries.size()) {
8364 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8365 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8367 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8369 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8370 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8371 << RF->getParent() << RF;
8373 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8374 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8375 << LF->getParent() << LF;
8376 else if (!LF->getParent()->isUnion() &&
8377 LF->getAccess() != RF->getAccess())
8378 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8379 << LF << LF->getAccess() << RF << RF->getAccess()
8384 // The comparison here must be unsigned, and performed with the same
8385 // width as the pointer.
8386 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8387 uint64_t CompareLHS = LHSOffset.getQuantity();
8388 uint64_t CompareRHS = RHSOffset.getQuantity();
8389 assert(PtrSize <= 64 && "Unexpected pointer width");
8390 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8394 // If there is a base and this is a relational operator, we can only
8395 // compare pointers within the object in question; otherwise, the result
8396 // depends on where the object is located in memory.
8397 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8398 QualType BaseTy = getType(LHSValue.Base);
8399 if (BaseTy->isIncompleteType())
8401 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8402 uint64_t OffsetLimit = Size.getQuantity();
8403 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8407 switch (E->getOpcode()) {
8408 default: llvm_unreachable("missing comparison operator");
8409 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8410 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8411 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8412 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8413 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8414 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8419 if (LHSTy->isMemberPointerType()) {
8420 assert(E->isEqualityOp() && "unexpected member pointer operation");
8421 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8423 MemberPtr LHSValue, RHSValue;
8425 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8426 if (!LHSOK && !Info.noteFailure())
8429 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8432 // C++11 [expr.eq]p2:
8433 // If both operands are null, they compare equal. Otherwise if only one is
8434 // null, they compare unequal.
8435 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8436 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8437 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8440 // Otherwise if either is a pointer to a virtual member function, the
8441 // result is unspecified.
8442 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8443 if (MD->isVirtual())
8444 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8445 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8446 if (MD->isVirtual())
8447 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8449 // Otherwise they compare equal if and only if they would refer to the
8450 // same member of the same most derived object or the same subobject if
8451 // they were dereferenced with a hypothetical object of the associated
8453 bool Equal = LHSValue == RHSValue;
8454 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8457 if (LHSTy->isNullPtrType()) {
8458 assert(E->isComparisonOp() && "unexpected nullptr operation");
8459 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8460 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8461 // are compared, the result is true of the operator is <=, >= or ==, and
8463 BinaryOperator::Opcode Opcode = E->getOpcode();
8464 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8467 assert((!LHSTy->isIntegralOrEnumerationType() ||
8468 !RHSTy->isIntegralOrEnumerationType()) &&
8469 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8470 // We can't continue from here for non-integral types.
8471 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8474 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8475 /// a result as the expression's type.
8476 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8477 const UnaryExprOrTypeTraitExpr *E) {
8478 switch(E->getKind()) {
8479 case UETT_AlignOf: {
8480 if (E->isArgumentType())
8481 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8483 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8486 case UETT_VecStep: {
8487 QualType Ty = E->getTypeOfArgument();
8489 if (Ty->isVectorType()) {
8490 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8492 // The vec_step built-in functions that take a 3-component
8493 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8497 return Success(n, E);
8499 return Success(1, E);
8503 QualType SrcTy = E->getTypeOfArgument();
8504 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8505 // the result is the size of the referenced type."
8506 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8507 SrcTy = Ref->getPointeeType();
8510 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8512 return Success(Sizeof, E);
8514 case UETT_OpenMPRequiredSimdAlign:
8515 assert(E->isArgumentType());
8517 Info.Ctx.toCharUnitsFromBits(
8518 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8523 llvm_unreachable("unknown expr/type trait");
8526 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8528 unsigned n = OOE->getNumComponents();
8531 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8532 for (unsigned i = 0; i != n; ++i) {
8533 OffsetOfNode ON = OOE->getComponent(i);
8534 switch (ON.getKind()) {
8535 case OffsetOfNode::Array: {
8536 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8538 if (!EvaluateInteger(Idx, IdxResult, Info))
8540 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8543 CurrentType = AT->getElementType();
8544 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8545 Result += IdxResult.getSExtValue() * ElementSize;
8549 case OffsetOfNode::Field: {
8550 FieldDecl *MemberDecl = ON.getField();
8551 const RecordType *RT = CurrentType->getAs<RecordType>();
8554 RecordDecl *RD = RT->getDecl();
8555 if (RD->isInvalidDecl()) return false;
8556 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8557 unsigned i = MemberDecl->getFieldIndex();
8558 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8559 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8560 CurrentType = MemberDecl->getType().getNonReferenceType();
8564 case OffsetOfNode::Identifier:
8565 llvm_unreachable("dependent __builtin_offsetof");
8567 case OffsetOfNode::Base: {
8568 CXXBaseSpecifier *BaseSpec = ON.getBase();
8569 if (BaseSpec->isVirtual())
8572 // Find the layout of the class whose base we are looking into.
8573 const RecordType *RT = CurrentType->getAs<RecordType>();
8576 RecordDecl *RD = RT->getDecl();
8577 if (RD->isInvalidDecl()) return false;
8578 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8580 // Find the base class itself.
8581 CurrentType = BaseSpec->getType();
8582 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8586 // Add the offset to the base.
8587 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8592 return Success(Result, OOE);
8595 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8596 switch (E->getOpcode()) {
8598 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8602 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8603 // If so, we could clear the diagnostic ID.
8604 return Visit(E->getSubExpr());
8606 // The result is just the value.
8607 return Visit(E->getSubExpr());
8609 if (!Visit(E->getSubExpr()))
8611 if (!Result.isInt()) return Error(E);
8612 const APSInt &Value = Result.getInt();
8613 if (Value.isSigned() && Value.isMinSignedValue() &&
8614 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8617 return Success(-Value, E);
8620 if (!Visit(E->getSubExpr()))
8622 if (!Result.isInt()) return Error(E);
8623 return Success(~Result.getInt(), E);
8627 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8629 return Success(!bres, E);
8634 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8635 /// result type is integer.
8636 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8637 const Expr *SubExpr = E->getSubExpr();
8638 QualType DestType = E->getType();
8639 QualType SrcType = SubExpr->getType();
8641 switch (E->getCastKind()) {
8642 case CK_BaseToDerived:
8643 case CK_DerivedToBase:
8644 case CK_UncheckedDerivedToBase:
8647 case CK_ArrayToPointerDecay:
8648 case CK_FunctionToPointerDecay:
8649 case CK_NullToPointer:
8650 case CK_NullToMemberPointer:
8651 case CK_BaseToDerivedMemberPointer:
8652 case CK_DerivedToBaseMemberPointer:
8653 case CK_ReinterpretMemberPointer:
8654 case CK_ConstructorConversion:
8655 case CK_IntegralToPointer:
8657 case CK_VectorSplat:
8658 case CK_IntegralToFloating:
8659 case CK_FloatingCast:
8660 case CK_CPointerToObjCPointerCast:
8661 case CK_BlockPointerToObjCPointerCast:
8662 case CK_AnyPointerToBlockPointerCast:
8663 case CK_ObjCObjectLValueCast:
8664 case CK_FloatingRealToComplex:
8665 case CK_FloatingComplexToReal:
8666 case CK_FloatingComplexCast:
8667 case CK_FloatingComplexToIntegralComplex:
8668 case CK_IntegralRealToComplex:
8669 case CK_IntegralComplexCast:
8670 case CK_IntegralComplexToFloatingComplex:
8671 case CK_BuiltinFnToFnPtr:
8672 case CK_ZeroToOCLEvent:
8673 case CK_ZeroToOCLQueue:
8674 case CK_NonAtomicToAtomic:
8675 case CK_AddressSpaceConversion:
8676 case CK_IntToOCLSampler:
8677 llvm_unreachable("invalid cast kind for integral value");
8681 case CK_LValueBitCast:
8682 case CK_ARCProduceObject:
8683 case CK_ARCConsumeObject:
8684 case CK_ARCReclaimReturnedObject:
8685 case CK_ARCExtendBlockObject:
8686 case CK_CopyAndAutoreleaseBlockObject:
8689 case CK_UserDefinedConversion:
8690 case CK_LValueToRValue:
8691 case CK_AtomicToNonAtomic:
8693 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8695 case CK_MemberPointerToBoolean:
8696 case CK_PointerToBoolean:
8697 case CK_IntegralToBoolean:
8698 case CK_FloatingToBoolean:
8699 case CK_BooleanToSignedIntegral:
8700 case CK_FloatingComplexToBoolean:
8701 case CK_IntegralComplexToBoolean: {
8703 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8705 uint64_t IntResult = BoolResult;
8706 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8707 IntResult = (uint64_t)-1;
8708 return Success(IntResult, E);
8711 case CK_IntegralCast: {
8712 if (!Visit(SubExpr))
8715 if (!Result.isInt()) {
8716 // Allow casts of address-of-label differences if they are no-ops
8717 // or narrowing. (The narrowing case isn't actually guaranteed to
8718 // be constant-evaluatable except in some narrow cases which are hard
8719 // to detect here. We let it through on the assumption the user knows
8720 // what they are doing.)
8721 if (Result.isAddrLabelDiff())
8722 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8723 // Only allow casts of lvalues if they are lossless.
8724 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8727 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8728 Result.getInt()), E);
8731 case CK_PointerToIntegral: {
8732 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8735 if (!EvaluatePointer(SubExpr, LV, Info))
8738 if (LV.getLValueBase()) {
8739 // Only allow based lvalue casts if they are lossless.
8740 // FIXME: Allow a larger integer size than the pointer size, and allow
8741 // narrowing back down to pointer width in subsequent integral casts.
8742 // FIXME: Check integer type's active bits, not its type size.
8743 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8746 LV.Designator.setInvalid();
8747 LV.moveInto(Result);
8752 if (LV.isNullPointer())
8753 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8755 V = LV.getLValueOffset().getQuantity();
8757 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8758 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8761 case CK_IntegralComplexToReal: {
8763 if (!EvaluateComplex(SubExpr, C, Info))
8765 return Success(C.getComplexIntReal(), E);
8768 case CK_FloatingToIntegral: {
8770 if (!EvaluateFloat(SubExpr, F, Info))
8774 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8776 return Success(Value, E);
8780 llvm_unreachable("unknown cast resulting in integral value");
8783 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8784 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8786 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8788 if (!LV.isComplexInt())
8790 return Success(LV.getComplexIntReal(), E);
8793 return Visit(E->getSubExpr());
8796 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8797 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8799 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8801 if (!LV.isComplexInt())
8803 return Success(LV.getComplexIntImag(), E);
8806 VisitIgnoredValue(E->getSubExpr());
8807 return Success(0, E);
8810 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8811 return Success(E->getPackLength(), E);
8814 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8815 return Success(E->getValue(), E);
8818 //===----------------------------------------------------------------------===//
8820 //===----------------------------------------------------------------------===//
8823 class FloatExprEvaluator
8824 : public ExprEvaluatorBase<FloatExprEvaluator> {
8827 FloatExprEvaluator(EvalInfo &info, APFloat &result)
8828 : ExprEvaluatorBaseTy(info), Result(result) {}
8830 bool Success(const APValue &V, const Expr *e) {
8831 Result = V.getFloat();
8835 bool ZeroInitialization(const Expr *E) {
8836 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8840 bool VisitCallExpr(const CallExpr *E);
8842 bool VisitUnaryOperator(const UnaryOperator *E);
8843 bool VisitBinaryOperator(const BinaryOperator *E);
8844 bool VisitFloatingLiteral(const FloatingLiteral *E);
8845 bool VisitCastExpr(const CastExpr *E);
8847 bool VisitUnaryReal(const UnaryOperator *E);
8848 bool VisitUnaryImag(const UnaryOperator *E);
8850 // FIXME: Missing: array subscript of vector, member of vector
8852 } // end anonymous namespace
8854 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
8855 assert(E->isRValue() && E->getType()->isRealFloatingType());
8856 return FloatExprEvaluator(Info, Result).Visit(E);
8859 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
8863 llvm::APFloat &Result) {
8864 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8865 if (!S) return false;
8867 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8871 // Treat empty strings as if they were zero.
8872 if (S->getString().empty())
8873 fill = llvm::APInt(32, 0);
8874 else if (S->getString().getAsInteger(0, fill))
8877 if (Context.getTargetInfo().isNan2008()) {
8879 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8881 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8883 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8884 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8885 // a different encoding to what became a standard in 2008, and for pre-
8886 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8887 // sNaN. This is now known as "legacy NaN" encoding.
8889 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8891 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8897 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
8898 switch (E->getBuiltinCallee()) {
8900 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8902 case Builtin::BI__builtin_huge_val:
8903 case Builtin::BI__builtin_huge_valf:
8904 case Builtin::BI__builtin_huge_vall:
8905 case Builtin::BI__builtin_inf:
8906 case Builtin::BI__builtin_inff:
8907 case Builtin::BI__builtin_infl: {
8908 const llvm::fltSemantics &Sem =
8909 Info.Ctx.getFloatTypeSemantics(E->getType());
8910 Result = llvm::APFloat::getInf(Sem);
8914 case Builtin::BI__builtin_nans:
8915 case Builtin::BI__builtin_nansf:
8916 case Builtin::BI__builtin_nansl:
8917 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8922 case Builtin::BI__builtin_nan:
8923 case Builtin::BI__builtin_nanf:
8924 case Builtin::BI__builtin_nanl:
8925 // If this is __builtin_nan() turn this into a nan, otherwise we
8926 // can't constant fold it.
8927 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8932 case Builtin::BI__builtin_fabs:
8933 case Builtin::BI__builtin_fabsf:
8934 case Builtin::BI__builtin_fabsl:
8935 if (!EvaluateFloat(E->getArg(0), Result, Info))
8938 if (Result.isNegative())
8939 Result.changeSign();
8942 // FIXME: Builtin::BI__builtin_powi
8943 // FIXME: Builtin::BI__builtin_powif
8944 // FIXME: Builtin::BI__builtin_powil
8946 case Builtin::BI__builtin_copysign:
8947 case Builtin::BI__builtin_copysignf:
8948 case Builtin::BI__builtin_copysignl: {
8950 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8951 !EvaluateFloat(E->getArg(1), RHS, Info))
8953 Result.copySign(RHS);
8959 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8960 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8962 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8964 Result = CV.FloatReal;
8968 return Visit(E->getSubExpr());
8971 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8972 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8974 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8976 Result = CV.FloatImag;
8980 VisitIgnoredValue(E->getSubExpr());
8981 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8982 Result = llvm::APFloat::getZero(Sem);
8986 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8987 switch (E->getOpcode()) {
8988 default: return Error(E);
8990 return EvaluateFloat(E->getSubExpr(), Result, Info);
8992 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8994 Result.changeSign();
8999 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9000 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9001 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9004 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9005 if (!LHSOK && !Info.noteFailure())
9007 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9008 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9011 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9012 Result = E->getValue();
9016 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9017 const Expr* SubExpr = E->getSubExpr();
9019 switch (E->getCastKind()) {
9021 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9023 case CK_IntegralToFloating: {
9025 return EvaluateInteger(SubExpr, IntResult, Info) &&
9026 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9027 E->getType(), Result);
9030 case CK_FloatingCast: {
9031 if (!Visit(SubExpr))
9033 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9037 case CK_FloatingComplexToReal: {
9039 if (!EvaluateComplex(SubExpr, V, Info))
9041 Result = V.getComplexFloatReal();
9047 //===----------------------------------------------------------------------===//
9048 // Complex Evaluation (for float and integer)
9049 //===----------------------------------------------------------------------===//
9052 class ComplexExprEvaluator
9053 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9054 ComplexValue &Result;
9057 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9058 : ExprEvaluatorBaseTy(info), Result(Result) {}
9060 bool Success(const APValue &V, const Expr *e) {
9065 bool ZeroInitialization(const Expr *E);
9067 //===--------------------------------------------------------------------===//
9069 //===--------------------------------------------------------------------===//
9071 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9072 bool VisitCastExpr(const CastExpr *E);
9073 bool VisitBinaryOperator(const BinaryOperator *E);
9074 bool VisitUnaryOperator(const UnaryOperator *E);
9075 bool VisitInitListExpr(const InitListExpr *E);
9077 } // end anonymous namespace
9079 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9081 assert(E->isRValue() && E->getType()->isAnyComplexType());
9082 return ComplexExprEvaluator(Info, Result).Visit(E);
9085 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9086 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9087 if (ElemTy->isRealFloatingType()) {
9088 Result.makeComplexFloat();
9089 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9090 Result.FloatReal = Zero;
9091 Result.FloatImag = Zero;
9093 Result.makeComplexInt();
9094 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9095 Result.IntReal = Zero;
9096 Result.IntImag = Zero;
9101 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9102 const Expr* SubExpr = E->getSubExpr();
9104 if (SubExpr->getType()->isRealFloatingType()) {
9105 Result.makeComplexFloat();
9106 APFloat &Imag = Result.FloatImag;
9107 if (!EvaluateFloat(SubExpr, Imag, Info))
9110 Result.FloatReal = APFloat(Imag.getSemantics());
9113 assert(SubExpr->getType()->isIntegerType() &&
9114 "Unexpected imaginary literal.");
9116 Result.makeComplexInt();
9117 APSInt &Imag = Result.IntImag;
9118 if (!EvaluateInteger(SubExpr, Imag, Info))
9121 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9126 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9128 switch (E->getCastKind()) {
9130 case CK_BaseToDerived:
9131 case CK_DerivedToBase:
9132 case CK_UncheckedDerivedToBase:
9135 case CK_ArrayToPointerDecay:
9136 case CK_FunctionToPointerDecay:
9137 case CK_NullToPointer:
9138 case CK_NullToMemberPointer:
9139 case CK_BaseToDerivedMemberPointer:
9140 case CK_DerivedToBaseMemberPointer:
9141 case CK_MemberPointerToBoolean:
9142 case CK_ReinterpretMemberPointer:
9143 case CK_ConstructorConversion:
9144 case CK_IntegralToPointer:
9145 case CK_PointerToIntegral:
9146 case CK_PointerToBoolean:
9148 case CK_VectorSplat:
9149 case CK_IntegralCast:
9150 case CK_BooleanToSignedIntegral:
9151 case CK_IntegralToBoolean:
9152 case CK_IntegralToFloating:
9153 case CK_FloatingToIntegral:
9154 case CK_FloatingToBoolean:
9155 case CK_FloatingCast:
9156 case CK_CPointerToObjCPointerCast:
9157 case CK_BlockPointerToObjCPointerCast:
9158 case CK_AnyPointerToBlockPointerCast:
9159 case CK_ObjCObjectLValueCast:
9160 case CK_FloatingComplexToReal:
9161 case CK_FloatingComplexToBoolean:
9162 case CK_IntegralComplexToReal:
9163 case CK_IntegralComplexToBoolean:
9164 case CK_ARCProduceObject:
9165 case CK_ARCConsumeObject:
9166 case CK_ARCReclaimReturnedObject:
9167 case CK_ARCExtendBlockObject:
9168 case CK_CopyAndAutoreleaseBlockObject:
9169 case CK_BuiltinFnToFnPtr:
9170 case CK_ZeroToOCLEvent:
9171 case CK_ZeroToOCLQueue:
9172 case CK_NonAtomicToAtomic:
9173 case CK_AddressSpaceConversion:
9174 case CK_IntToOCLSampler:
9175 llvm_unreachable("invalid cast kind for complex value");
9177 case CK_LValueToRValue:
9178 case CK_AtomicToNonAtomic:
9180 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9183 case CK_LValueBitCast:
9184 case CK_UserDefinedConversion:
9187 case CK_FloatingRealToComplex: {
9188 APFloat &Real = Result.FloatReal;
9189 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9192 Result.makeComplexFloat();
9193 Result.FloatImag = APFloat(Real.getSemantics());
9197 case CK_FloatingComplexCast: {
9198 if (!Visit(E->getSubExpr()))
9201 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9203 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9205 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9206 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9209 case CK_FloatingComplexToIntegralComplex: {
9210 if (!Visit(E->getSubExpr()))
9213 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9215 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9216 Result.makeComplexInt();
9217 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9218 To, Result.IntReal) &&
9219 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9220 To, Result.IntImag);
9223 case CK_IntegralRealToComplex: {
9224 APSInt &Real = Result.IntReal;
9225 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9228 Result.makeComplexInt();
9229 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9233 case CK_IntegralComplexCast: {
9234 if (!Visit(E->getSubExpr()))
9237 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9239 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9241 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9242 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9246 case CK_IntegralComplexToFloatingComplex: {
9247 if (!Visit(E->getSubExpr()))
9250 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9252 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9253 Result.makeComplexFloat();
9254 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9255 To, Result.FloatReal) &&
9256 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9257 To, Result.FloatImag);
9261 llvm_unreachable("unknown cast resulting in complex value");
9264 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9265 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9266 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9268 // Track whether the LHS or RHS is real at the type system level. When this is
9269 // the case we can simplify our evaluation strategy.
9270 bool LHSReal = false, RHSReal = false;
9273 if (E->getLHS()->getType()->isRealFloatingType()) {
9275 APFloat &Real = Result.FloatReal;
9276 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9278 Result.makeComplexFloat();
9279 Result.FloatImag = APFloat(Real.getSemantics());
9282 LHSOK = Visit(E->getLHS());
9284 if (!LHSOK && !Info.noteFailure())
9288 if (E->getRHS()->getType()->isRealFloatingType()) {
9290 APFloat &Real = RHS.FloatReal;
9291 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9293 RHS.makeComplexFloat();
9294 RHS.FloatImag = APFloat(Real.getSemantics());
9295 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9298 assert(!(LHSReal && RHSReal) &&
9299 "Cannot have both operands of a complex operation be real.");
9300 switch (E->getOpcode()) {
9301 default: return Error(E);
9303 if (Result.isComplexFloat()) {
9304 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9305 APFloat::rmNearestTiesToEven);
9307 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9309 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9310 APFloat::rmNearestTiesToEven);
9312 Result.getComplexIntReal() += RHS.getComplexIntReal();
9313 Result.getComplexIntImag() += RHS.getComplexIntImag();
9317 if (Result.isComplexFloat()) {
9318 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9319 APFloat::rmNearestTiesToEven);
9321 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9322 Result.getComplexFloatImag().changeSign();
9323 } else if (!RHSReal) {
9324 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9325 APFloat::rmNearestTiesToEven);
9328 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9329 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9333 if (Result.isComplexFloat()) {
9334 // This is an implementation of complex multiplication according to the
9335 // constraints laid out in C11 Annex G. The implemantion uses the
9336 // following naming scheme:
9337 // (a + ib) * (c + id)
9338 ComplexValue LHS = Result;
9339 APFloat &A = LHS.getComplexFloatReal();
9340 APFloat &B = LHS.getComplexFloatImag();
9341 APFloat &C = RHS.getComplexFloatReal();
9342 APFloat &D = RHS.getComplexFloatImag();
9343 APFloat &ResR = Result.getComplexFloatReal();
9344 APFloat &ResI = Result.getComplexFloatImag();
9346 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9349 } else if (RHSReal) {
9353 // In the fully general case, we need to handle NaNs and infinities
9361 if (ResR.isNaN() && ResI.isNaN()) {
9362 bool Recalc = false;
9363 if (A.isInfinity() || B.isInfinity()) {
9364 A = APFloat::copySign(
9365 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9366 B = APFloat::copySign(
9367 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9369 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9371 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9374 if (C.isInfinity() || D.isInfinity()) {
9375 C = APFloat::copySign(
9376 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9377 D = APFloat::copySign(
9378 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9380 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9382 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9385 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9386 AD.isInfinity() || BC.isInfinity())) {
9388 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9390 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9392 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9394 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9398 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9399 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9404 ComplexValue LHS = Result;
9405 Result.getComplexIntReal() =
9406 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9407 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9408 Result.getComplexIntImag() =
9409 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9410 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9414 if (Result.isComplexFloat()) {
9415 // This is an implementation of complex division according to the
9416 // constraints laid out in C11 Annex G. The implemantion uses the
9417 // following naming scheme:
9418 // (a + ib) / (c + id)
9419 ComplexValue LHS = Result;
9420 APFloat &A = LHS.getComplexFloatReal();
9421 APFloat &B = LHS.getComplexFloatImag();
9422 APFloat &C = RHS.getComplexFloatReal();
9423 APFloat &D = RHS.getComplexFloatImag();
9424 APFloat &ResR = Result.getComplexFloatReal();
9425 APFloat &ResI = Result.getComplexFloatImag();
9431 // No real optimizations we can do here, stub out with zero.
9432 B = APFloat::getZero(A.getSemantics());
9435 APFloat MaxCD = maxnum(abs(C), abs(D));
9436 if (MaxCD.isFinite()) {
9437 DenomLogB = ilogb(MaxCD);
9438 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9439 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9441 APFloat Denom = C * C + D * D;
9442 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9443 APFloat::rmNearestTiesToEven);
9444 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9445 APFloat::rmNearestTiesToEven);
9446 if (ResR.isNaN() && ResI.isNaN()) {
9447 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9448 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9449 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9450 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9452 A = APFloat::copySign(
9453 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9454 B = APFloat::copySign(
9455 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9456 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9457 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9458 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9459 C = APFloat::copySign(
9460 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9461 D = APFloat::copySign(
9462 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9463 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9464 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9469 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9470 return Error(E, diag::note_expr_divide_by_zero);
9472 ComplexValue LHS = Result;
9473 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9474 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9475 Result.getComplexIntReal() =
9476 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9477 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9478 Result.getComplexIntImag() =
9479 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9480 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9488 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9489 // Get the operand value into 'Result'.
9490 if (!Visit(E->getSubExpr()))
9493 switch (E->getOpcode()) {
9499 // The result is always just the subexpr.
9502 if (Result.isComplexFloat()) {
9503 Result.getComplexFloatReal().changeSign();
9504 Result.getComplexFloatImag().changeSign();
9507 Result.getComplexIntReal() = -Result.getComplexIntReal();
9508 Result.getComplexIntImag() = -Result.getComplexIntImag();
9512 if (Result.isComplexFloat())
9513 Result.getComplexFloatImag().changeSign();
9515 Result.getComplexIntImag() = -Result.getComplexIntImag();
9520 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9521 if (E->getNumInits() == 2) {
9522 if (E->getType()->isComplexType()) {
9523 Result.makeComplexFloat();
9524 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9526 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9529 Result.makeComplexInt();
9530 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9532 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9537 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9540 //===----------------------------------------------------------------------===//
9541 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9542 // implicit conversion.
9543 //===----------------------------------------------------------------------===//
9546 class AtomicExprEvaluator :
9547 public ExprEvaluatorBase<AtomicExprEvaluator> {
9550 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
9551 : ExprEvaluatorBaseTy(Info), Result(Result) {}
9553 bool Success(const APValue &V, const Expr *E) {
9558 bool ZeroInitialization(const Expr *E) {
9559 ImplicitValueInitExpr VIE(
9560 E->getType()->castAs<AtomicType>()->getValueType());
9561 return Evaluate(Result, Info, &VIE);
9564 bool VisitCastExpr(const CastExpr *E) {
9565 switch (E->getCastKind()) {
9567 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9568 case CK_NonAtomicToAtomic:
9569 return Evaluate(Result, Info, E->getSubExpr());
9573 } // end anonymous namespace
9575 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
9576 assert(E->isRValue() && E->getType()->isAtomicType());
9577 return AtomicExprEvaluator(Info, Result).Visit(E);
9580 //===----------------------------------------------------------------------===//
9581 // Void expression evaluation, primarily for a cast to void on the LHS of a
9583 //===----------------------------------------------------------------------===//
9586 class VoidExprEvaluator
9587 : public ExprEvaluatorBase<VoidExprEvaluator> {
9589 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9591 bool Success(const APValue &V, const Expr *e) { return true; }
9593 bool VisitCastExpr(const CastExpr *E) {
9594 switch (E->getCastKind()) {
9596 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9598 VisitIgnoredValue(E->getSubExpr());
9603 bool VisitCallExpr(const CallExpr *E) {
9604 switch (E->getBuiltinCallee()) {
9606 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9607 case Builtin::BI__assume:
9608 case Builtin::BI__builtin_assume:
9609 // The argument is not evaluated!
9614 } // end anonymous namespace
9616 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9617 assert(E->isRValue() && E->getType()->isVoidType());
9618 return VoidExprEvaluator(Info).Visit(E);
9621 //===----------------------------------------------------------------------===//
9622 // Top level Expr::EvaluateAsRValue method.
9623 //===----------------------------------------------------------------------===//
9625 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9626 // In C, function designators are not lvalues, but we evaluate them as if they
9628 QualType T = E->getType();
9629 if (E->isGLValue() || T->isFunctionType()) {
9631 if (!EvaluateLValue(E, LV, Info))
9633 LV.moveInto(Result);
9634 } else if (T->isVectorType()) {
9635 if (!EvaluateVector(E, Result, Info))
9637 } else if (T->isIntegralOrEnumerationType()) {
9638 if (!IntExprEvaluator(Info, Result).Visit(E))
9640 } else if (T->hasPointerRepresentation()) {
9642 if (!EvaluatePointer(E, LV, Info))
9644 LV.moveInto(Result);
9645 } else if (T->isRealFloatingType()) {
9646 llvm::APFloat F(0.0);
9647 if (!EvaluateFloat(E, F, Info))
9649 Result = APValue(F);
9650 } else if (T->isAnyComplexType()) {
9652 if (!EvaluateComplex(E, C, Info))
9655 } else if (T->isMemberPointerType()) {
9657 if (!EvaluateMemberPointer(E, P, Info))
9661 } else if (T->isArrayType()) {
9663 LV.set(E, Info.CurrentCall->Index);
9664 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9665 if (!EvaluateArray(E, LV, Value, Info))
9668 } else if (T->isRecordType()) {
9670 LV.set(E, Info.CurrentCall->Index);
9671 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9672 if (!EvaluateRecord(E, LV, Value, Info))
9675 } else if (T->isVoidType()) {
9676 if (!Info.getLangOpts().CPlusPlus11)
9677 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9679 if (!EvaluateVoid(E, Info))
9681 } else if (T->isAtomicType()) {
9682 if (!EvaluateAtomic(E, Result, Info))
9684 } else if (Info.getLangOpts().CPlusPlus11) {
9685 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9688 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9695 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9696 /// cases, the in-place evaluation is essential, since later initializers for
9697 /// an object can indirectly refer to subobjects which were initialized earlier.
9698 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9699 const Expr *E, bool AllowNonLiteralTypes) {
9700 assert(!E->isValueDependent());
9702 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9705 if (E->isRValue()) {
9706 // Evaluate arrays and record types in-place, so that later initializers can
9707 // refer to earlier-initialized members of the object.
9708 if (E->getType()->isArrayType())
9709 return EvaluateArray(E, This, Result, Info);
9710 else if (E->getType()->isRecordType())
9711 return EvaluateRecord(E, This, Result, Info);
9714 // For any other type, in-place evaluation is unimportant.
9715 return Evaluate(Result, Info, E);
9718 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9719 /// lvalue-to-rvalue cast if it is an lvalue.
9720 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9721 if (E->getType().isNull())
9724 if (!CheckLiteralType(Info, E))
9727 if (!::Evaluate(Result, Info, E))
9730 if (E->isGLValue()) {
9732 LV.setFrom(Info.Ctx, Result);
9733 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9737 // Check this core constant expression is a constant expression.
9738 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9741 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9742 const ASTContext &Ctx, bool &IsConst) {
9743 // Fast-path evaluations of integer literals, since we sometimes see files
9744 // containing vast quantities of these.
9745 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9746 Result.Val = APValue(APSInt(L->getValue(),
9747 L->getType()->isUnsignedIntegerType()));
9752 // This case should be rare, but we need to check it before we check on
9754 if (Exp->getType().isNull()) {
9759 // FIXME: Evaluating values of large array and record types can cause
9760 // performance problems. Only do so in C++11 for now.
9761 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9762 Exp->getType()->isRecordType()) &&
9763 !Ctx.getLangOpts().CPlusPlus11) {
9771 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9772 /// any crazy technique (that has nothing to do with language standards) that
9773 /// we want to. If this function returns true, it returns the folded constant
9774 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9775 /// will be applied to the result.
9776 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9778 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9781 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9782 return ::EvaluateAsRValue(Info, this, Result.Val);
9785 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9786 const ASTContext &Ctx) const {
9788 return EvaluateAsRValue(Scratch, Ctx) &&
9789 HandleConversionToBool(Scratch.Val, Result);
9792 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9793 Expr::SideEffectsKind SEK) {
9794 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9795 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9798 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9799 SideEffectsKind AllowSideEffects) const {
9800 if (!getType()->isIntegralOrEnumerationType())
9803 EvalResult ExprResult;
9804 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
9805 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9808 Result = ExprResult.Val.getInt();
9812 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9813 SideEffectsKind AllowSideEffects) const {
9814 if (!getType()->isRealFloatingType())
9817 EvalResult ExprResult;
9818 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9819 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9822 Result = ExprResult.Val.getFloat();
9826 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
9827 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
9830 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9831 !CheckLValueConstantExpression(Info, getExprLoc(),
9832 Ctx.getLValueReferenceType(getType()), LV))
9835 LV.moveInto(Result.Val);
9839 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9841 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
9842 // FIXME: Evaluating initializers for large array and record types can cause
9843 // performance problems. Only do so in C++11 for now.
9844 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
9845 !Ctx.getLangOpts().CPlusPlus11)
9848 Expr::EvalStatus EStatus;
9849 EStatus.Diag = &Notes;
9851 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9852 ? EvalInfo::EM_ConstantExpression
9853 : EvalInfo::EM_ConstantFold);
9854 InitInfo.setEvaluatingDecl(VD, Value);
9859 // C++11 [basic.start.init]p2:
9860 // Variables with static storage duration or thread storage duration shall be
9861 // zero-initialized before any other initialization takes place.
9862 // This behavior is not present in C.
9863 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
9864 !VD->getType()->isReferenceType()) {
9865 ImplicitValueInitExpr VIE(VD->getType());
9866 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
9867 /*AllowNonLiteralTypes=*/true))
9871 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9872 /*AllowNonLiteralTypes=*/true) ||
9873 EStatus.HasSideEffects)
9876 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9880 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9881 /// constant folded, but discard the result.
9882 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
9884 return EvaluateAsRValue(Result, Ctx) &&
9885 !hasUnacceptableSideEffect(Result, SEK);
9888 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
9889 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
9890 EvalResult EvalResult;
9891 EvalResult.Diag = Diag;
9892 bool Result = EvaluateAsRValue(EvalResult, Ctx);
9894 assert(Result && "Could not evaluate expression");
9895 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
9897 return EvalResult.Val.getInt();
9900 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
9902 EvalResult EvalResult;
9903 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
9904 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
9905 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9909 bool Expr::EvalResult::isGlobalLValue() const {
9910 assert(Val.isLValue());
9911 return IsGlobalLValue(Val.getLValueBase());
9915 /// isIntegerConstantExpr - this recursive routine will test if an expression is
9916 /// an integer constant expression.
9918 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9921 // CheckICE - This function does the fundamental ICE checking: the returned
9922 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9923 // and a (possibly null) SourceLocation indicating the location of the problem.
9925 // Note that to reduce code duplication, this helper does no evaluation
9926 // itself; the caller checks whether the expression is evaluatable, and
9927 // in the rare cases where CheckICE actually cares about the evaluated
9928 // value, it calls into Evalute.
9933 /// This expression is an ICE.
9935 /// This expression is not an ICE, but if it isn't evaluated, it's
9936 /// a legal subexpression for an ICE. This return value is used to handle
9937 /// the comma operator in C99 mode, and non-constant subexpressions.
9938 IK_ICEIfUnevaluated,
9939 /// This expression is not an ICE, and is not a legal subexpression for one.
9947 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
9952 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9954 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
9956 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
9957 Expr::EvalResult EVResult;
9958 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
9959 !EVResult.Val.isInt())
9960 return ICEDiag(IK_NotICE, E->getLocStart());
9965 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
9966 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
9967 if (!E->getType()->isIntegralOrEnumerationType())
9968 return ICEDiag(IK_NotICE, E->getLocStart());
9970 switch (E->getStmtClass()) {
9971 #define ABSTRACT_STMT(Node)
9972 #define STMT(Node, Base) case Expr::Node##Class:
9973 #define EXPR(Node, Base)
9974 #include "clang/AST/StmtNodes.inc"
9975 case Expr::PredefinedExprClass:
9976 case Expr::FloatingLiteralClass:
9977 case Expr::ImaginaryLiteralClass:
9978 case Expr::StringLiteralClass:
9979 case Expr::ArraySubscriptExprClass:
9980 case Expr::OMPArraySectionExprClass:
9981 case Expr::MemberExprClass:
9982 case Expr::CompoundAssignOperatorClass:
9983 case Expr::CompoundLiteralExprClass:
9984 case Expr::ExtVectorElementExprClass:
9985 case Expr::DesignatedInitExprClass:
9986 case Expr::ArrayInitLoopExprClass:
9987 case Expr::ArrayInitIndexExprClass:
9988 case Expr::NoInitExprClass:
9989 case Expr::DesignatedInitUpdateExprClass:
9990 case Expr::ImplicitValueInitExprClass:
9991 case Expr::ParenListExprClass:
9992 case Expr::VAArgExprClass:
9993 case Expr::AddrLabelExprClass:
9994 case Expr::StmtExprClass:
9995 case Expr::CXXMemberCallExprClass:
9996 case Expr::CUDAKernelCallExprClass:
9997 case Expr::CXXDynamicCastExprClass:
9998 case Expr::CXXTypeidExprClass:
9999 case Expr::CXXUuidofExprClass:
10000 case Expr::MSPropertyRefExprClass:
10001 case Expr::MSPropertySubscriptExprClass:
10002 case Expr::CXXNullPtrLiteralExprClass:
10003 case Expr::UserDefinedLiteralClass:
10004 case Expr::CXXThisExprClass:
10005 case Expr::CXXThrowExprClass:
10006 case Expr::CXXNewExprClass:
10007 case Expr::CXXDeleteExprClass:
10008 case Expr::CXXPseudoDestructorExprClass:
10009 case Expr::UnresolvedLookupExprClass:
10010 case Expr::TypoExprClass:
10011 case Expr::DependentScopeDeclRefExprClass:
10012 case Expr::CXXConstructExprClass:
10013 case Expr::CXXInheritedCtorInitExprClass:
10014 case Expr::CXXStdInitializerListExprClass:
10015 case Expr::CXXBindTemporaryExprClass:
10016 case Expr::ExprWithCleanupsClass:
10017 case Expr::CXXTemporaryObjectExprClass:
10018 case Expr::CXXUnresolvedConstructExprClass:
10019 case Expr::CXXDependentScopeMemberExprClass:
10020 case Expr::UnresolvedMemberExprClass:
10021 case Expr::ObjCStringLiteralClass:
10022 case Expr::ObjCBoxedExprClass:
10023 case Expr::ObjCArrayLiteralClass:
10024 case Expr::ObjCDictionaryLiteralClass:
10025 case Expr::ObjCEncodeExprClass:
10026 case Expr::ObjCMessageExprClass:
10027 case Expr::ObjCSelectorExprClass:
10028 case Expr::ObjCProtocolExprClass:
10029 case Expr::ObjCIvarRefExprClass:
10030 case Expr::ObjCPropertyRefExprClass:
10031 case Expr::ObjCSubscriptRefExprClass:
10032 case Expr::ObjCIsaExprClass:
10033 case Expr::ObjCAvailabilityCheckExprClass:
10034 case Expr::ShuffleVectorExprClass:
10035 case Expr::ConvertVectorExprClass:
10036 case Expr::BlockExprClass:
10037 case Expr::NoStmtClass:
10038 case Expr::OpaqueValueExprClass:
10039 case Expr::PackExpansionExprClass:
10040 case Expr::SubstNonTypeTemplateParmPackExprClass:
10041 case Expr::FunctionParmPackExprClass:
10042 case Expr::AsTypeExprClass:
10043 case Expr::ObjCIndirectCopyRestoreExprClass:
10044 case Expr::MaterializeTemporaryExprClass:
10045 case Expr::PseudoObjectExprClass:
10046 case Expr::AtomicExprClass:
10047 case Expr::LambdaExprClass:
10048 case Expr::CXXFoldExprClass:
10049 case Expr::CoawaitExprClass:
10050 case Expr::CoyieldExprClass:
10051 return ICEDiag(IK_NotICE, E->getLocStart());
10053 case Expr::InitListExprClass: {
10054 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10055 // form "T x = { a };" is equivalent to "T x = a;".
10056 // Unless we're initializing a reference, T is a scalar as it is known to be
10057 // of integral or enumeration type.
10059 if (cast<InitListExpr>(E)->getNumInits() == 1)
10060 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10061 return ICEDiag(IK_NotICE, E->getLocStart());
10064 case Expr::SizeOfPackExprClass:
10065 case Expr::GNUNullExprClass:
10066 // GCC considers the GNU __null value to be an integral constant expression.
10069 case Expr::SubstNonTypeTemplateParmExprClass:
10071 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10073 case Expr::ParenExprClass:
10074 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10075 case Expr::GenericSelectionExprClass:
10076 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10077 case Expr::IntegerLiteralClass:
10078 case Expr::CharacterLiteralClass:
10079 case Expr::ObjCBoolLiteralExprClass:
10080 case Expr::CXXBoolLiteralExprClass:
10081 case Expr::CXXScalarValueInitExprClass:
10082 case Expr::TypeTraitExprClass:
10083 case Expr::ArrayTypeTraitExprClass:
10084 case Expr::ExpressionTraitExprClass:
10085 case Expr::CXXNoexceptExprClass:
10087 case Expr::CallExprClass:
10088 case Expr::CXXOperatorCallExprClass: {
10089 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10090 // constant expressions, but they can never be ICEs because an ICE cannot
10091 // contain an operand of (pointer to) function type.
10092 const CallExpr *CE = cast<CallExpr>(E);
10093 if (CE->getBuiltinCallee())
10094 return CheckEvalInICE(E, Ctx);
10095 return ICEDiag(IK_NotICE, E->getLocStart());
10097 case Expr::DeclRefExprClass: {
10098 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10100 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10101 if (Ctx.getLangOpts().CPlusPlus &&
10102 D && IsConstNonVolatile(D->getType())) {
10103 // Parameter variables are never constants. Without this check,
10104 // getAnyInitializer() can find a default argument, which leads
10106 if (isa<ParmVarDecl>(D))
10107 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10110 // A variable of non-volatile const-qualified integral or enumeration
10111 // type initialized by an ICE can be used in ICEs.
10112 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10113 if (!Dcl->getType()->isIntegralOrEnumerationType())
10114 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10117 // Look for a declaration of this variable that has an initializer, and
10118 // check whether it is an ICE.
10119 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10122 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10125 return ICEDiag(IK_NotICE, E->getLocStart());
10127 case Expr::UnaryOperatorClass: {
10128 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10129 switch (Exp->getOpcode()) {
10137 // C99 6.6/3 allows increment and decrement within unevaluated
10138 // subexpressions of constant expressions, but they can never be ICEs
10139 // because an ICE cannot contain an lvalue operand.
10140 return ICEDiag(IK_NotICE, E->getLocStart());
10148 return CheckICE(Exp->getSubExpr(), Ctx);
10151 // OffsetOf falls through here.
10153 case Expr::OffsetOfExprClass: {
10154 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10155 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10156 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10157 // compliance: we should warn earlier for offsetof expressions with
10158 // array subscripts that aren't ICEs, and if the array subscripts
10159 // are ICEs, the value of the offsetof must be an integer constant.
10160 return CheckEvalInICE(E, Ctx);
10162 case Expr::UnaryExprOrTypeTraitExprClass: {
10163 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10164 if ((Exp->getKind() == UETT_SizeOf) &&
10165 Exp->getTypeOfArgument()->isVariableArrayType())
10166 return ICEDiag(IK_NotICE, E->getLocStart());
10169 case Expr::BinaryOperatorClass: {
10170 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10171 switch (Exp->getOpcode()) {
10185 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10186 // constant expressions, but they can never be ICEs because an ICE cannot
10187 // contain an lvalue operand.
10188 return ICEDiag(IK_NotICE, E->getLocStart());
10207 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10208 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10209 if (Exp->getOpcode() == BO_Div ||
10210 Exp->getOpcode() == BO_Rem) {
10211 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10212 // we don't evaluate one.
10213 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10214 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10216 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10217 if (REval.isSigned() && REval.isAllOnesValue()) {
10218 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10219 if (LEval.isMinSignedValue())
10220 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10224 if (Exp->getOpcode() == BO_Comma) {
10225 if (Ctx.getLangOpts().C99) {
10226 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10227 // if it isn't evaluated.
10228 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10229 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10231 // In both C89 and C++, commas in ICEs are illegal.
10232 return ICEDiag(IK_NotICE, E->getLocStart());
10235 return Worst(LHSResult, RHSResult);
10239 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10240 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10241 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10242 // Rare case where the RHS has a comma "side-effect"; we need
10243 // to actually check the condition to see whether the side
10244 // with the comma is evaluated.
10245 if ((Exp->getOpcode() == BO_LAnd) !=
10246 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10251 return Worst(LHSResult, RHSResult);
10255 case Expr::ImplicitCastExprClass:
10256 case Expr::CStyleCastExprClass:
10257 case Expr::CXXFunctionalCastExprClass:
10258 case Expr::CXXStaticCastExprClass:
10259 case Expr::CXXReinterpretCastExprClass:
10260 case Expr::CXXConstCastExprClass:
10261 case Expr::ObjCBridgedCastExprClass: {
10262 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10263 if (isa<ExplicitCastExpr>(E)) {
10264 if (const FloatingLiteral *FL
10265 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10266 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10267 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10268 APSInt IgnoredVal(DestWidth, !DestSigned);
10270 // If the value does not fit in the destination type, the behavior is
10271 // undefined, so we are not required to treat it as a constant
10273 if (FL->getValue().convertToInteger(IgnoredVal,
10274 llvm::APFloat::rmTowardZero,
10275 &Ignored) & APFloat::opInvalidOp)
10276 return ICEDiag(IK_NotICE, E->getLocStart());
10280 switch (cast<CastExpr>(E)->getCastKind()) {
10281 case CK_LValueToRValue:
10282 case CK_AtomicToNonAtomic:
10283 case CK_NonAtomicToAtomic:
10285 case CK_IntegralToBoolean:
10286 case CK_IntegralCast:
10287 return CheckICE(SubExpr, Ctx);
10289 return ICEDiag(IK_NotICE, E->getLocStart());
10292 case Expr::BinaryConditionalOperatorClass: {
10293 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10294 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10295 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10296 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10297 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10298 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10299 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10300 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10301 return FalseResult;
10303 case Expr::ConditionalOperatorClass: {
10304 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10305 // If the condition (ignoring parens) is a __builtin_constant_p call,
10306 // then only the true side is actually considered in an integer constant
10307 // expression, and it is fully evaluated. This is an important GNU
10308 // extension. See GCC PR38377 for discussion.
10309 if (const CallExpr *CallCE
10310 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10311 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10312 return CheckEvalInICE(E, Ctx);
10313 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10314 if (CondResult.Kind == IK_NotICE)
10317 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10318 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10320 if (TrueResult.Kind == IK_NotICE)
10322 if (FalseResult.Kind == IK_NotICE)
10323 return FalseResult;
10324 if (CondResult.Kind == IK_ICEIfUnevaluated)
10326 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10328 // Rare case where the diagnostics depend on which side is evaluated
10329 // Note that if we get here, CondResult is 0, and at least one of
10330 // TrueResult and FalseResult is non-zero.
10331 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10332 return FalseResult;
10335 case Expr::CXXDefaultArgExprClass:
10336 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10337 case Expr::CXXDefaultInitExprClass:
10338 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10339 case Expr::ChooseExprClass: {
10340 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10344 llvm_unreachable("Invalid StmtClass!");
10347 /// Evaluate an expression as a C++11 integral constant expression.
10348 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10350 llvm::APSInt *Value,
10351 SourceLocation *Loc) {
10352 if (!E->getType()->isIntegralOrEnumerationType()) {
10353 if (Loc) *Loc = E->getExprLoc();
10358 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10361 if (!Result.isInt()) {
10362 if (Loc) *Loc = E->getExprLoc();
10366 if (Value) *Value = Result.getInt();
10370 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10371 SourceLocation *Loc) const {
10372 if (Ctx.getLangOpts().CPlusPlus11)
10373 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10375 ICEDiag D = CheckICE(this, Ctx);
10376 if (D.Kind != IK_ICE) {
10377 if (Loc) *Loc = D.Loc;
10383 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10384 SourceLocation *Loc, bool isEvaluated) const {
10385 if (Ctx.getLangOpts().CPlusPlus11)
10386 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10388 if (!isIntegerConstantExpr(Ctx, Loc))
10390 // The only possible side-effects here are due to UB discovered in the
10391 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10392 // required to treat the expression as an ICE, so we produce the folded
10394 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10395 llvm_unreachable("ICE cannot be evaluated!");
10399 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10400 return CheckICE(this, Ctx).Kind == IK_ICE;
10403 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10404 SourceLocation *Loc) const {
10405 // We support this checking in C++98 mode in order to diagnose compatibility
10407 assert(Ctx.getLangOpts().CPlusPlus);
10409 // Build evaluation settings.
10410 Expr::EvalStatus Status;
10411 SmallVector<PartialDiagnosticAt, 8> Diags;
10412 Status.Diag = &Diags;
10413 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10416 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10418 if (!Diags.empty()) {
10419 IsConstExpr = false;
10420 if (Loc) *Loc = Diags[0].first;
10421 } else if (!IsConstExpr) {
10422 // FIXME: This shouldn't happen.
10423 if (Loc) *Loc = getExprLoc();
10426 return IsConstExpr;
10429 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10430 const FunctionDecl *Callee,
10431 ArrayRef<const Expr*> Args,
10432 const Expr *This) const {
10433 Expr::EvalStatus Status;
10434 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10437 const LValue *ThisPtr = nullptr;
10440 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10441 assert(MD && "Don't provide `this` for non-methods.");
10442 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10444 if (EvaluateObjectArgument(Info, This, ThisVal))
10445 ThisPtr = &ThisVal;
10446 if (Info.EvalStatus.HasSideEffects)
10450 ArgVector ArgValues(Args.size());
10451 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10453 if ((*I)->isValueDependent() ||
10454 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10455 // If evaluation fails, throw away the argument entirely.
10456 ArgValues[I - Args.begin()] = APValue();
10457 if (Info.EvalStatus.HasSideEffects)
10461 // Build fake call to Callee.
10462 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10464 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10467 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10469 PartialDiagnosticAt> &Diags) {
10470 // FIXME: It would be useful to check constexpr function templates, but at the
10471 // moment the constant expression evaluator cannot cope with the non-rigorous
10472 // ASTs which we build for dependent expressions.
10473 if (FD->isDependentContext())
10476 Expr::EvalStatus Status;
10477 Status.Diag = &Diags;
10479 EvalInfo Info(FD->getASTContext(), Status,
10480 EvalInfo::EM_PotentialConstantExpression);
10482 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10483 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10485 // Fabricate an arbitrary expression on the stack and pretend that it
10486 // is a temporary being used as the 'this' pointer.
10488 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10489 This.set(&VIE, Info.CurrentCall->Index);
10491 ArrayRef<const Expr*> Args;
10494 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10495 // Evaluate the call as a constant initializer, to allow the construction
10496 // of objects of non-literal types.
10497 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10498 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10500 SourceLocation Loc = FD->getLocation();
10501 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10502 Args, FD->getBody(), Info, Scratch, nullptr);
10505 return Diags.empty();
10508 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10509 const FunctionDecl *FD,
10511 PartialDiagnosticAt> &Diags) {
10512 Expr::EvalStatus Status;
10513 Status.Diag = &Diags;
10515 EvalInfo Info(FD->getASTContext(), Status,
10516 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10518 // Fabricate a call stack frame to give the arguments a plausible cover story.
10519 ArrayRef<const Expr*> Args;
10520 ArgVector ArgValues(0);
10521 bool Success = EvaluateArgs(Args, ArgValues, Info);
10524 "Failed to set up arguments for potential constant evaluation");
10525 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10527 APValue ResultScratch;
10528 Evaluate(ResultScratch, Info, E);
10529 return Diags.empty();
10532 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10533 unsigned Type) const {
10534 if (!getType()->isPointerType())
10537 Expr::EvalStatus Status;
10538 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10539 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);