1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Expr constant evaluator.
12 // Constant expression evaluation produces four main results:
14 // * A success/failure flag indicating whether constant folding was successful.
15 // This is the 'bool' return value used by most of the code in this file. A
16 // 'false' return value indicates that constant folding has failed, and any
17 // appropriate diagnostic has already been produced.
19 // * An evaluated result, valid only if constant folding has not failed.
21 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 // where it is possible to determine the evaluated result regardless.
25 // * A set of notes indicating why the evaluation was not a constant expression
26 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 // too, why the expression could not be folded.
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
34 //===----------------------------------------------------------------------===//
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
51 using namespace clang;
55 static bool IsGlobalLValue(APValue::LValueBase B);
59 struct CallStackFrame;
62 static QualType getType(APValue::LValueBase B) {
63 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67 const Expr *Base = B.get<const Expr*>();
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it directly. Otherwise use the type after adjustment.
80 if (!Adjustments.empty())
81 return Inner->getType();
84 return Base->getType();
87 /// Get an LValue path entry, which is known to not be an array index, as a
88 /// field or base class.
90 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
98 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
106 /// Determine whether this LValue path entry for a base class names a virtual
108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109 return getAsBaseOrMember(E).getInt();
112 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114 const FunctionDecl *Callee = CE->getDirectCallee();
115 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
118 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119 /// This will look through a single cast.
121 /// Returns null if we couldn't unwrap a function with alloc_size.
122 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123 if (!E->getType()->isPointerType())
126 E = E->IgnoreParens();
127 // If we're doing a variable assignment from e.g. malloc(N), there will
128 // probably be a cast of some kind. Ignore it.
129 if (const auto *Cast = dyn_cast<CastExpr>(E))
130 E = Cast->getSubExpr()->IgnoreParens();
132 if (const auto *CE = dyn_cast<CallExpr>(E))
133 return getAllocSizeAttr(CE) ? CE : nullptr;
137 /// Determines whether or not the given Base contains a call to a function
138 /// with the alloc_size attribute.
139 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140 const auto *E = Base.dyn_cast<const Expr *>();
141 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
144 /// Determines if an LValue with the given LValueBase will have an unsized
145 /// array in its designator.
146 /// Find the path length and type of the most-derived subobject in the given
147 /// path, and find the size of the containing array, if any.
149 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150 ArrayRef<APValue::LValuePathEntry> Path,
151 uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152 // This only accepts LValueBases from APValues, and APValues don't support
153 // arrays that lack size info.
154 assert(!isBaseAnAllocSizeCall(Base) &&
155 "Unsized arrays shouldn't appear here");
156 unsigned MostDerivedLength = 0;
157 Type = getType(Base);
159 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160 if (Type->isArrayType()) {
161 const ConstantArrayType *CAT =
162 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163 Type = CAT->getElementType();
164 ArraySize = CAT->getSize().getZExtValue();
165 MostDerivedLength = I + 1;
167 } else if (Type->isAnyComplexType()) {
168 const ComplexType *CT = Type->castAs<ComplexType>();
169 Type = CT->getElementType();
171 MostDerivedLength = I + 1;
173 } else if (const FieldDecl *FD = getAsField(Path[I])) {
174 Type = FD->getType();
176 MostDerivedLength = I + 1;
179 // Path[I] describes a base class.
184 return MostDerivedLength;
187 // The order of this enum is important for diagnostics.
188 enum CheckSubobjectKind {
189 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190 CSK_This, CSK_Real, CSK_Imag
193 /// A path from a glvalue to a subobject of that glvalue.
194 struct SubobjectDesignator {
195 /// True if the subobject was named in a manner not supported by C++11. Such
196 /// lvalues can still be folded, but they are not core constant expressions
197 /// and we cannot perform lvalue-to-rvalue conversions on them.
198 unsigned Invalid : 1;
200 /// Is this a pointer one past the end of an object?
201 unsigned IsOnePastTheEnd : 1;
203 /// Indicator of whether the first entry is an unsized array.
204 unsigned FirstEntryIsAnUnsizedArray : 1;
206 /// Indicator of whether the most-derived object is an array element.
207 unsigned MostDerivedIsArrayElement : 1;
209 /// The length of the path to the most-derived object of which this is a
211 unsigned MostDerivedPathLength : 28;
213 /// The size of the array of which the most-derived object is an element.
214 /// This will always be 0 if the most-derived object is not an array
215 /// element. 0 is not an indicator of whether or not the most-derived object
216 /// is an array, however, because 0-length arrays are allowed.
218 /// If the current array is an unsized array, the value of this is
220 uint64_t MostDerivedArraySize;
222 /// The type of the most derived object referred to by this address.
223 QualType MostDerivedType;
225 typedef APValue::LValuePathEntry PathEntry;
227 /// The entries on the path from the glvalue to the designated subobject.
228 SmallVector<PathEntry, 8> Entries;
230 SubobjectDesignator() : Invalid(true) {}
232 explicit SubobjectDesignator(QualType T)
233 : Invalid(false), IsOnePastTheEnd(false),
234 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235 MostDerivedPathLength(0), MostDerivedArraySize(0),
236 MostDerivedType(T) {}
238 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241 MostDerivedPathLength(0), MostDerivedArraySize(0) {
242 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
244 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245 ArrayRef<PathEntry> VEntries = V.getLValuePath();
246 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247 if (V.getLValueBase()) {
248 bool IsArray = false;
249 MostDerivedPathLength = findMostDerivedSubobject(
250 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251 MostDerivedType, IsArray);
252 MostDerivedIsArrayElement = IsArray;
262 /// Determine whether the most derived subobject is an array without a
264 bool isMostDerivedAnUnsizedArray() const {
265 assert(!Invalid && "Calling this makes no sense on invalid designators");
266 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
269 /// Determine what the most derived array's size is. Results in an assertion
270 /// failure if the most derived array lacks a size.
271 uint64_t getMostDerivedArraySize() const {
272 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273 return MostDerivedArraySize;
276 /// Determine whether this is a one-past-the-end pointer.
277 bool isOnePastTheEnd() const {
281 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
287 /// Check that this refers to a valid subobject.
288 bool isValidSubobject() const {
291 return !isOnePastTheEnd();
293 /// Check that this refers to a valid subobject, and if not, produce a
294 /// relevant diagnostic and set the designator as invalid.
295 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
297 /// Update this designator to refer to the first element within this array.
298 void addArrayUnchecked(const ConstantArrayType *CAT) {
300 Entry.ArrayIndex = 0;
301 Entries.push_back(Entry);
303 // This is a most-derived object.
304 MostDerivedType = CAT->getElementType();
305 MostDerivedIsArrayElement = true;
306 MostDerivedArraySize = CAT->getSize().getZExtValue();
307 MostDerivedPathLength = Entries.size();
309 /// Update this designator to refer to the first element within the array of
310 /// elements of type T. This is an array of unknown size.
311 void addUnsizedArrayUnchecked(QualType ElemTy) {
313 Entry.ArrayIndex = 0;
314 Entries.push_back(Entry);
316 MostDerivedType = ElemTy;
317 MostDerivedIsArrayElement = true;
318 // The value in MostDerivedArraySize is undefined in this case. So, set it
319 // to an arbitrary value that's likely to loudly break things if it's
321 MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322 MostDerivedPathLength = Entries.size();
324 /// Update this designator to refer to the given base or member of this
326 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
328 APValue::BaseOrMemberType Value(D, Virtual);
329 Entry.BaseOrMember = Value.getOpaqueValue();
330 Entries.push_back(Entry);
332 // If this isn't a base class, it's a new most-derived object.
333 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334 MostDerivedType = FD->getType();
335 MostDerivedIsArrayElement = false;
336 MostDerivedArraySize = 0;
337 MostDerivedPathLength = Entries.size();
340 /// Update this designator to refer to the given complex component.
341 void addComplexUnchecked(QualType EltTy, bool Imag) {
343 Entry.ArrayIndex = Imag;
344 Entries.push_back(Entry);
346 // This is technically a most-derived object, though in practice this
347 // is unlikely to matter.
348 MostDerivedType = EltTy;
349 MostDerivedIsArrayElement = true;
350 MostDerivedArraySize = 2;
351 MostDerivedPathLength = Entries.size();
353 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
355 /// Add N to the address of this subobject.
356 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357 if (Invalid || !N) return;
358 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359 if (isMostDerivedAnUnsizedArray()) {
360 // Can't verify -- trust that the user is doing the right thing (or if
361 // not, trust that the caller will catch the bad behavior).
362 // FIXME: Should we reject if this overflows, at least?
363 Entries.back().ArrayIndex += TruncatedN;
367 // [expr.add]p4: For the purposes of these operators, a pointer to a
368 // nonarray object behaves the same as a pointer to the first element of
369 // an array of length one with the type of the object as its element type.
370 bool IsArray = MostDerivedPathLength == Entries.size() &&
371 MostDerivedIsArrayElement;
372 uint64_t ArrayIndex =
373 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
375 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
377 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378 // Calculate the actual index in a wide enough type, so we can include
380 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381 (llvm::APInt&)N += ArrayIndex;
382 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383 diagnosePointerArithmetic(Info, E, N);
388 ArrayIndex += TruncatedN;
389 assert(ArrayIndex <= ArraySize &&
390 "bounds check succeeded for out-of-bounds index");
393 Entries.back().ArrayIndex = ArrayIndex;
395 IsOnePastTheEnd = (ArrayIndex != 0);
399 /// A stack frame in the constexpr call stack.
400 struct CallStackFrame {
403 /// Parent - The caller of this stack frame.
404 CallStackFrame *Caller;
406 /// Callee - The function which was called.
407 const FunctionDecl *Callee;
409 /// This - The binding for the this pointer in this call, if any.
412 /// Arguments - Parameter bindings for this function call, indexed by
413 /// parameters' function scope indices.
416 // Note that we intentionally use std::map here so that references to
417 // values are stable.
418 typedef std::map<const void*, APValue> MapTy;
419 typedef MapTy::const_iterator temp_iterator;
420 /// Temporaries - Temporary lvalues materialized within this stack frame.
423 /// CallLoc - The location of the call expression for this call.
424 SourceLocation CallLoc;
426 /// Index - The call index of this call.
429 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430 // on the overall stack usage of deeply-recursing constexpr evaluataions.
431 // (We should cache this map rather than recomputing it repeatedly.)
432 // But let's try this and see how it goes; we can look into caching the map
433 // as a later change.
435 /// LambdaCaptureFields - Mapping from captured variables/this to
436 /// corresponding data members in the closure class.
437 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438 FieldDecl *LambdaThisCaptureField;
440 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441 const FunctionDecl *Callee, const LValue *This,
445 APValue *getTemporary(const void *Key) {
446 MapTy::iterator I = Temporaries.find(Key);
447 return I == Temporaries.end() ? nullptr : &I->second;
449 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
452 /// Temporarily override 'this'.
453 class ThisOverrideRAII {
455 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456 : Frame(Frame), OldThis(Frame.This) {
458 Frame.This = NewThis;
460 ~ThisOverrideRAII() {
461 Frame.This = OldThis;
464 CallStackFrame &Frame;
465 const LValue *OldThis;
468 /// A partial diagnostic which we might know in advance that we are not going
470 class OptionalDiagnostic {
471 PartialDiagnostic *Diag;
474 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
478 OptionalDiagnostic &operator<<(const T &v) {
484 OptionalDiagnostic &operator<<(const APSInt &I) {
486 SmallVector<char, 32> Buffer;
488 *Diag << StringRef(Buffer.data(), Buffer.size());
493 OptionalDiagnostic &operator<<(const APFloat &F) {
495 // FIXME: Force the precision of the source value down so we don't
496 // print digits which are usually useless (we don't really care here if
497 // we truncate a digit by accident in edge cases). Ideally,
498 // APFloat::toString would automatically print the shortest
499 // representation which rounds to the correct value, but it's a bit
500 // tricky to implement.
502 llvm::APFloat::semanticsPrecision(F.getSemantics());
503 precision = (precision * 59 + 195) / 196;
504 SmallVector<char, 32> Buffer;
505 F.toString(Buffer, precision);
506 *Diag << StringRef(Buffer.data(), Buffer.size());
512 /// A cleanup, and a flag indicating whether it is lifetime-extended.
514 llvm::PointerIntPair<APValue*, 1, bool> Value;
517 Cleanup(APValue *Val, bool IsLifetimeExtended)
518 : Value(Val, IsLifetimeExtended) {}
520 bool isLifetimeExtended() const { return Value.getInt(); }
522 *Value.getPointer() = APValue();
526 /// EvalInfo - This is a private struct used by the evaluator to capture
527 /// information about a subexpression as it is folded. It retains information
528 /// about the AST context, but also maintains information about the folded
531 /// If an expression could be evaluated, it is still possible it is not a C
532 /// "integer constant expression" or constant expression. If not, this struct
533 /// captures information about how and why not.
535 /// One bit of information passed *into* the request for constant folding
536 /// indicates whether the subexpression is "evaluated" or not according to C
537 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
538 /// evaluate the expression regardless of what the RHS is, but C only allows
539 /// certain things in certain situations.
540 struct LLVM_ALIGNAS(/*alignof(uint64_t)*/ 8) EvalInfo {
543 /// EvalStatus - Contains information about the evaluation.
544 Expr::EvalStatus &EvalStatus;
546 /// CurrentCall - The top of the constexpr call stack.
547 CallStackFrame *CurrentCall;
549 /// CallStackDepth - The number of calls in the call stack right now.
550 unsigned CallStackDepth;
552 /// NextCallIndex - The next call index to assign.
553 unsigned NextCallIndex;
555 /// StepsLeft - The remaining number of evaluation steps we're permitted
556 /// to perform. This is essentially a limit for the number of statements
557 /// we will evaluate.
560 /// BottomFrame - The frame in which evaluation started. This must be
561 /// initialized after CurrentCall and CallStackDepth.
562 CallStackFrame BottomFrame;
564 /// A stack of values whose lifetimes end at the end of some surrounding
565 /// evaluation frame.
566 llvm::SmallVector<Cleanup, 16> CleanupStack;
568 /// EvaluatingDecl - This is the declaration whose initializer is being
569 /// evaluated, if any.
570 APValue::LValueBase EvaluatingDecl;
572 /// EvaluatingDeclValue - This is the value being constructed for the
573 /// declaration whose initializer is being evaluated, if any.
574 APValue *EvaluatingDeclValue;
576 /// The current array initialization index, if we're performing array
578 uint64_t ArrayInitIndex = -1;
580 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
581 /// notes attached to it will also be stored, otherwise they will not be.
582 bool HasActiveDiagnostic;
584 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
585 /// fold (not just why it's not strictly a constant expression)?
586 bool HasFoldFailureDiagnostic;
588 /// \brief Whether or not we're currently speculatively evaluating.
589 bool IsSpeculativelyEvaluating;
591 enum EvaluationMode {
592 /// Evaluate as a constant expression. Stop if we find that the expression
593 /// is not a constant expression.
594 EM_ConstantExpression,
596 /// Evaluate as a potential constant expression. Keep going if we hit a
597 /// construct that we can't evaluate yet (because we don't yet know the
598 /// value of something) but stop if we hit something that could never be
599 /// a constant expression.
600 EM_PotentialConstantExpression,
602 /// Fold the expression to a constant. Stop if we hit a side-effect that
606 /// Evaluate the expression looking for integer overflow and similar
607 /// issues. Don't worry about side-effects, and try to visit all
609 EM_EvaluateForOverflow,
611 /// Evaluate in any way we know how. Don't worry about side-effects that
612 /// can't be modeled.
613 EM_IgnoreSideEffects,
615 /// Evaluate as a constant expression. Stop if we find that the expression
616 /// is not a constant expression. Some expressions can be retried in the
617 /// optimizer if we don't constant fold them here, but in an unevaluated
618 /// context we try to fold them immediately since the optimizer never
619 /// gets a chance to look at it.
620 EM_ConstantExpressionUnevaluated,
622 /// Evaluate as a potential constant expression. Keep going if we hit a
623 /// construct that we can't evaluate yet (because we don't yet know the
624 /// value of something) but stop if we hit something that could never be
625 /// a constant expression. Some expressions can be retried in the
626 /// optimizer if we don't constant fold them here, but in an unevaluated
627 /// context we try to fold them immediately since the optimizer never
628 /// gets a chance to look at it.
629 EM_PotentialConstantExpressionUnevaluated,
631 /// Evaluate as a constant expression. In certain scenarios, if:
632 /// - we find a MemberExpr with a base that can't be evaluated, or
633 /// - we find a variable initialized with a call to a function that has
634 /// the alloc_size attribute on it
635 /// then we may consider evaluation to have succeeded.
637 /// In either case, the LValue returned shall have an invalid base; in the
638 /// former, the base will be the invalid MemberExpr, in the latter, the
639 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
644 /// Are we checking whether the expression is a potential constant
646 bool checkingPotentialConstantExpression() const {
647 return EvalMode == EM_PotentialConstantExpression ||
648 EvalMode == EM_PotentialConstantExpressionUnevaluated;
651 /// Are we checking an expression for overflow?
652 // FIXME: We should check for any kind of undefined or suspicious behavior
653 // in such constructs, not just overflow.
654 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
656 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
657 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
658 CallStackDepth(0), NextCallIndex(1),
659 StepsLeft(getLangOpts().ConstexprStepLimit),
660 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
661 EvaluatingDecl((const ValueDecl *)nullptr),
662 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
663 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
666 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
667 EvaluatingDecl = Base;
668 EvaluatingDeclValue = &Value;
671 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
673 bool CheckCallLimit(SourceLocation Loc) {
674 // Don't perform any constexpr calls (other than the call we're checking)
675 // when checking a potential constant expression.
676 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
678 if (NextCallIndex == 0) {
679 // NextCallIndex has wrapped around.
680 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
683 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
685 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
686 << getLangOpts().ConstexprCallDepth;
690 CallStackFrame *getCallFrame(unsigned CallIndex) {
691 assert(CallIndex && "no call index in getCallFrame");
692 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
693 // be null in this loop.
694 CallStackFrame *Frame = CurrentCall;
695 while (Frame->Index > CallIndex)
696 Frame = Frame->Caller;
697 return (Frame->Index == CallIndex) ? Frame : nullptr;
700 bool nextStep(const Stmt *S) {
702 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
710 /// Add a diagnostic to the diagnostics list.
711 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
712 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
713 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
714 return EvalStatus.Diag->back().second;
717 /// Add notes containing a call stack to the current point of evaluation.
718 void addCallStack(unsigned Limit);
721 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
722 unsigned ExtraNotes, bool IsCCEDiag) {
724 if (EvalStatus.Diag) {
725 // If we have a prior diagnostic, it will be noting that the expression
726 // isn't a constant expression. This diagnostic is more important,
727 // unless we require this evaluation to produce a constant expression.
729 // FIXME: We might want to show both diagnostics to the user in
730 // EM_ConstantFold mode.
731 if (!EvalStatus.Diag->empty()) {
733 case EM_ConstantFold:
734 case EM_IgnoreSideEffects:
735 case EM_EvaluateForOverflow:
736 if (!HasFoldFailureDiagnostic)
738 // We've already failed to fold something. Keep that diagnostic.
740 case EM_ConstantExpression:
741 case EM_PotentialConstantExpression:
742 case EM_ConstantExpressionUnevaluated:
743 case EM_PotentialConstantExpressionUnevaluated:
745 HasActiveDiagnostic = false;
746 return OptionalDiagnostic();
750 unsigned CallStackNotes = CallStackDepth - 1;
751 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
753 CallStackNotes = std::min(CallStackNotes, Limit + 1);
754 if (checkingPotentialConstantExpression())
757 HasActiveDiagnostic = true;
758 HasFoldFailureDiagnostic = !IsCCEDiag;
759 EvalStatus.Diag->clear();
760 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
761 addDiag(Loc, DiagId);
762 if (!checkingPotentialConstantExpression())
764 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
766 HasActiveDiagnostic = false;
767 return OptionalDiagnostic();
770 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
772 FFDiag(SourceLocation Loc,
773 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
774 unsigned ExtraNotes = 0) {
775 return Diag(Loc, DiagId, ExtraNotes, false);
778 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
779 = diag::note_invalid_subexpr_in_const_expr,
780 unsigned ExtraNotes = 0) {
782 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
783 HasActiveDiagnostic = false;
784 return OptionalDiagnostic();
787 /// Diagnose that the evaluation does not produce a C++11 core constant
790 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
791 /// EM_PotentialConstantExpression mode and we produce one of these.
792 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
793 = diag::note_invalid_subexpr_in_const_expr,
794 unsigned ExtraNotes = 0) {
795 // Don't override a previous diagnostic. Don't bother collecting
796 // diagnostics if we're evaluating for overflow.
797 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
798 HasActiveDiagnostic = false;
799 return OptionalDiagnostic();
801 return Diag(Loc, DiagId, ExtraNotes, true);
803 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
804 = diag::note_invalid_subexpr_in_const_expr,
805 unsigned ExtraNotes = 0) {
806 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
808 /// Add a note to a prior diagnostic.
809 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
810 if (!HasActiveDiagnostic)
811 return OptionalDiagnostic();
812 return OptionalDiagnostic(&addDiag(Loc, DiagId));
815 /// Add a stack of notes to a prior diagnostic.
816 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
817 if (HasActiveDiagnostic) {
818 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
819 Diags.begin(), Diags.end());
823 /// Should we continue evaluation after encountering a side-effect that we
825 bool keepEvaluatingAfterSideEffect() {
827 case EM_PotentialConstantExpression:
828 case EM_PotentialConstantExpressionUnevaluated:
829 case EM_EvaluateForOverflow:
830 case EM_IgnoreSideEffects:
833 case EM_ConstantExpression:
834 case EM_ConstantExpressionUnevaluated:
835 case EM_ConstantFold:
839 llvm_unreachable("Missed EvalMode case");
842 /// Note that we have had a side-effect, and determine whether we should
844 bool noteSideEffect() {
845 EvalStatus.HasSideEffects = true;
846 return keepEvaluatingAfterSideEffect();
849 /// Should we continue evaluation after encountering undefined behavior?
850 bool keepEvaluatingAfterUndefinedBehavior() {
852 case EM_EvaluateForOverflow:
853 case EM_IgnoreSideEffects:
854 case EM_ConstantFold:
858 case EM_PotentialConstantExpression:
859 case EM_PotentialConstantExpressionUnevaluated:
860 case EM_ConstantExpression:
861 case EM_ConstantExpressionUnevaluated:
864 llvm_unreachable("Missed EvalMode case");
867 /// Note that we hit something that was technically undefined behavior, but
868 /// that we can evaluate past it (such as signed overflow or floating-point
869 /// division by zero.)
870 bool noteUndefinedBehavior() {
871 EvalStatus.HasUndefinedBehavior = true;
872 return keepEvaluatingAfterUndefinedBehavior();
875 /// Should we continue evaluation as much as possible after encountering a
876 /// construct which can't be reduced to a value?
877 bool keepEvaluatingAfterFailure() {
882 case EM_PotentialConstantExpression:
883 case EM_PotentialConstantExpressionUnevaluated:
884 case EM_EvaluateForOverflow:
887 case EM_ConstantExpression:
888 case EM_ConstantExpressionUnevaluated:
889 case EM_ConstantFold:
890 case EM_IgnoreSideEffects:
894 llvm_unreachable("Missed EvalMode case");
897 /// Notes that we failed to evaluate an expression that other expressions
898 /// directly depend on, and determine if we should keep evaluating. This
899 /// should only be called if we actually intend to keep evaluating.
901 /// Call noteSideEffect() instead if we may be able to ignore the value that
902 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
904 /// (Foo(), 1) // use noteSideEffect
905 /// (Foo() || true) // use noteSideEffect
906 /// Foo() + 1 // use noteFailure
907 LLVM_NODISCARD bool noteFailure() {
908 // Failure when evaluating some expression often means there is some
909 // subexpression whose evaluation was skipped. Therefore, (because we
910 // don't track whether we skipped an expression when unwinding after an
911 // evaluation failure) every evaluation failure that bubbles up from a
912 // subexpression implies that a side-effect has potentially happened. We
913 // skip setting the HasSideEffects flag to true until we decide to
914 // continue evaluating after that point, which happens here.
915 bool KeepGoing = keepEvaluatingAfterFailure();
916 EvalStatus.HasSideEffects |= KeepGoing;
920 class ArrayInitLoopIndex {
925 ArrayInitLoopIndex(EvalInfo &Info)
926 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
927 Info.ArrayInitIndex = 0;
929 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
931 operator uint64_t&() { return Info.ArrayInitIndex; }
935 /// Object used to treat all foldable expressions as constant expressions.
936 struct FoldConstant {
939 bool HadNoPriorDiags;
940 EvalInfo::EvaluationMode OldMode;
942 explicit FoldConstant(EvalInfo &Info, bool Enabled)
945 HadNoPriorDiags(Info.EvalStatus.Diag &&
946 Info.EvalStatus.Diag->empty() &&
947 !Info.EvalStatus.HasSideEffects),
948 OldMode(Info.EvalMode) {
950 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
951 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
952 Info.EvalMode = EvalInfo::EM_ConstantFold;
954 void keepDiagnostics() { Enabled = false; }
956 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
957 !Info.EvalStatus.HasSideEffects)
958 Info.EvalStatus.Diag->clear();
959 Info.EvalMode = OldMode;
963 /// RAII object used to treat the current evaluation as the correct pointer
964 /// offset fold for the current EvalMode
965 struct FoldOffsetRAII {
967 EvalInfo::EvaluationMode OldMode;
968 explicit FoldOffsetRAII(EvalInfo &Info)
969 : Info(Info), OldMode(Info.EvalMode) {
970 if (!Info.checkingPotentialConstantExpression())
971 Info.EvalMode = EvalInfo::EM_OffsetFold;
974 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
977 /// RAII object used to optionally suppress diagnostics and side-effects from
978 /// a speculative evaluation.
979 class SpeculativeEvaluationRAII {
980 /// Pair of EvalInfo, and a bit that stores whether or not we were
981 /// speculatively evaluating when we created this RAII.
982 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
983 Expr::EvalStatus Old;
985 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
986 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
988 Other.InfoAndOldSpecEval.setPointer(nullptr);
991 void maybeRestoreState() {
992 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
996 Info->EvalStatus = Old;
997 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
1001 SpeculativeEvaluationRAII() = default;
1003 SpeculativeEvaluationRAII(
1004 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1005 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
1006 Old(Info.EvalStatus) {
1007 Info.EvalStatus.Diag = NewDiag;
1008 Info.IsSpeculativelyEvaluating = true;
1011 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1012 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1013 moveFromAndCancel(std::move(Other));
1016 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1017 maybeRestoreState();
1018 moveFromAndCancel(std::move(Other));
1022 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1025 /// RAII object wrapping a full-expression or block scope, and handling
1026 /// the ending of the lifetime of temporaries created within it.
1027 template<bool IsFullExpression>
1030 unsigned OldStackSize;
1032 ScopeRAII(EvalInfo &Info)
1033 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1035 // Body moved to a static method to encourage the compiler to inline away
1036 // instances of this class.
1037 cleanup(Info, OldStackSize);
1040 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1041 unsigned NewEnd = OldStackSize;
1042 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1044 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1045 // Full-expression cleanup of a lifetime-extended temporary: nothing
1046 // to do, just move this cleanup to the right place in the stack.
1047 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1050 // End the lifetime of the object.
1051 Info.CleanupStack[I].endLifetime();
1054 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1055 Info.CleanupStack.end());
1058 typedef ScopeRAII<false> BlockScopeRAII;
1059 typedef ScopeRAII<true> FullExpressionRAII;
1062 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1063 CheckSubobjectKind CSK) {
1066 if (isOnePastTheEnd()) {
1067 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1075 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1078 // If we're complaining, we must be able to statically determine the size of
1079 // the most derived array.
1080 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1081 Info.CCEDiag(E, diag::note_constexpr_array_index)
1083 << static_cast<unsigned>(getMostDerivedArraySize());
1085 Info.CCEDiag(E, diag::note_constexpr_array_index)
1086 << N << /*non-array*/ 1;
1090 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1091 const FunctionDecl *Callee, const LValue *This,
1093 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1094 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1095 Info.CurrentCall = this;
1096 ++Info.CallStackDepth;
1099 CallStackFrame::~CallStackFrame() {
1100 assert(Info.CurrentCall == this && "calls retired out of order");
1101 --Info.CallStackDepth;
1102 Info.CurrentCall = Caller;
1105 APValue &CallStackFrame::createTemporary(const void *Key,
1106 bool IsLifetimeExtended) {
1107 APValue &Result = Temporaries[Key];
1108 assert(Result.isUninit() && "temporary created multiple times");
1109 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1113 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1115 void EvalInfo::addCallStack(unsigned Limit) {
1116 // Determine which calls to skip, if any.
1117 unsigned ActiveCalls = CallStackDepth - 1;
1118 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1119 if (Limit && Limit < ActiveCalls) {
1120 SkipStart = Limit / 2 + Limit % 2;
1121 SkipEnd = ActiveCalls - Limit / 2;
1124 // Walk the call stack and add the diagnostics.
1125 unsigned CallIdx = 0;
1126 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1127 Frame = Frame->Caller, ++CallIdx) {
1129 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1130 if (CallIdx == SkipStart) {
1131 // Note that we're skipping calls.
1132 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1133 << unsigned(ActiveCalls - Limit);
1138 // Use a different note for an inheriting constructor, because from the
1139 // user's perspective it's not really a function at all.
1140 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1141 if (CD->isInheritingConstructor()) {
1142 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1148 SmallVector<char, 128> Buffer;
1149 llvm::raw_svector_ostream Out(Buffer);
1150 describeCall(Frame, Out);
1151 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1156 struct ComplexValue {
1161 APSInt IntReal, IntImag;
1162 APFloat FloatReal, FloatImag;
1164 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1166 void makeComplexFloat() { IsInt = false; }
1167 bool isComplexFloat() const { return !IsInt; }
1168 APFloat &getComplexFloatReal() { return FloatReal; }
1169 APFloat &getComplexFloatImag() { return FloatImag; }
1171 void makeComplexInt() { IsInt = true; }
1172 bool isComplexInt() const { return IsInt; }
1173 APSInt &getComplexIntReal() { return IntReal; }
1174 APSInt &getComplexIntImag() { return IntImag; }
1176 void moveInto(APValue &v) const {
1177 if (isComplexFloat())
1178 v = APValue(FloatReal, FloatImag);
1180 v = APValue(IntReal, IntImag);
1182 void setFrom(const APValue &v) {
1183 assert(v.isComplexFloat() || v.isComplexInt());
1184 if (v.isComplexFloat()) {
1186 FloatReal = v.getComplexFloatReal();
1187 FloatImag = v.getComplexFloatImag();
1190 IntReal = v.getComplexIntReal();
1191 IntImag = v.getComplexIntImag();
1197 APValue::LValueBase Base;
1199 unsigned InvalidBase : 1;
1200 unsigned CallIndex : 31;
1201 SubobjectDesignator Designator;
1204 const APValue::LValueBase getLValueBase() const { return Base; }
1205 CharUnits &getLValueOffset() { return Offset; }
1206 const CharUnits &getLValueOffset() const { return Offset; }
1207 unsigned getLValueCallIndex() const { return CallIndex; }
1208 SubobjectDesignator &getLValueDesignator() { return Designator; }
1209 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1210 bool isNullPointer() const { return IsNullPtr;}
1212 void moveInto(APValue &V) const {
1213 if (Designator.Invalid)
1214 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1217 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1218 assert(!Designator.FirstEntryIsAnUnsizedArray &&
1219 "Unsized array with a valid base?");
1220 V = APValue(Base, Offset, Designator.Entries,
1221 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1224 void setFrom(ASTContext &Ctx, const APValue &V) {
1225 assert(V.isLValue() && "Setting LValue from a non-LValue?");
1226 Base = V.getLValueBase();
1227 Offset = V.getLValueOffset();
1228 InvalidBase = false;
1229 CallIndex = V.getLValueCallIndex();
1230 Designator = SubobjectDesignator(Ctx, V);
1231 IsNullPtr = V.isNullPointer();
1234 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1236 // We only allow a few types of invalid bases. Enforce that here.
1238 const auto *E = B.get<const Expr *>();
1239 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1240 "Unexpected type of invalid base");
1245 Offset = CharUnits::fromQuantity(0);
1246 InvalidBase = BInvalid;
1248 Designator = SubobjectDesignator(getType(B));
1252 void setNull(QualType PointerTy, uint64_t TargetVal) {
1253 Base = (Expr *)nullptr;
1254 Offset = CharUnits::fromQuantity(TargetVal);
1255 InvalidBase = false;
1257 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1261 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1265 // Check that this LValue is not based on a null pointer. If it is, produce
1266 // a diagnostic and mark the designator as invalid.
1267 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1268 CheckSubobjectKind CSK) {
1269 if (Designator.Invalid)
1272 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1274 Designator.setInvalid();
1280 // Check this LValue refers to an object. If not, set the designator to be
1281 // invalid and emit a diagnostic.
1282 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1283 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1284 Designator.checkSubobject(Info, E, CSK);
1287 void addDecl(EvalInfo &Info, const Expr *E,
1288 const Decl *D, bool Virtual = false) {
1289 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1290 Designator.addDeclUnchecked(D, Virtual);
1292 void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1293 assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1294 assert(isBaseAnAllocSizeCall(Base) &&
1295 "Only alloc_size bases can have unsized arrays");
1296 Designator.FirstEntryIsAnUnsizedArray = true;
1297 Designator.addUnsizedArrayUnchecked(ElemTy);
1299 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1300 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1301 Designator.addArrayUnchecked(CAT);
1303 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1304 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1305 Designator.addComplexUnchecked(EltTy, Imag);
1307 void clearIsNullPointer() {
1310 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1311 const APSInt &Index, CharUnits ElementSize) {
1312 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1313 // but we're not required to diagnose it and it's valid in C++.)
1317 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1318 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1320 uint64_t Offset64 = Offset.getQuantity();
1321 uint64_t ElemSize64 = ElementSize.getQuantity();
1322 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1323 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1325 if (checkNullPointer(Info, E, CSK_ArrayIndex))
1326 Designator.adjustIndex(Info, E, Index);
1327 clearIsNullPointer();
1329 void adjustOffset(CharUnits N) {
1331 if (N.getQuantity())
1332 clearIsNullPointer();
1338 explicit MemberPtr(const ValueDecl *Decl) :
1339 DeclAndIsDerivedMember(Decl, false), Path() {}
1341 /// The member or (direct or indirect) field referred to by this member
1342 /// pointer, or 0 if this is a null member pointer.
1343 const ValueDecl *getDecl() const {
1344 return DeclAndIsDerivedMember.getPointer();
1346 /// Is this actually a member of some type derived from the relevant class?
1347 bool isDerivedMember() const {
1348 return DeclAndIsDerivedMember.getInt();
1350 /// Get the class which the declaration actually lives in.
1351 const CXXRecordDecl *getContainingRecord() const {
1352 return cast<CXXRecordDecl>(
1353 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1356 void moveInto(APValue &V) const {
1357 V = APValue(getDecl(), isDerivedMember(), Path);
1359 void setFrom(const APValue &V) {
1360 assert(V.isMemberPointer());
1361 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1362 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1364 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1365 Path.insert(Path.end(), P.begin(), P.end());
1368 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1369 /// whether the member is a member of some class derived from the class type
1370 /// of the member pointer.
1371 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1372 /// Path - The path of base/derived classes from the member declaration's
1373 /// class (exclusive) to the class type of the member pointer (inclusive).
1374 SmallVector<const CXXRecordDecl*, 4> Path;
1376 /// Perform a cast towards the class of the Decl (either up or down the
1378 bool castBack(const CXXRecordDecl *Class) {
1379 assert(!Path.empty());
1380 const CXXRecordDecl *Expected;
1381 if (Path.size() >= 2)
1382 Expected = Path[Path.size() - 2];
1384 Expected = getContainingRecord();
1385 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1386 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1387 // if B does not contain the original member and is not a base or
1388 // derived class of the class containing the original member, the result
1389 // of the cast is undefined.
1390 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1391 // (D::*). We consider that to be a language defect.
1397 /// Perform a base-to-derived member pointer cast.
1398 bool castToDerived(const CXXRecordDecl *Derived) {
1401 if (!isDerivedMember()) {
1402 Path.push_back(Derived);
1405 if (!castBack(Derived))
1408 DeclAndIsDerivedMember.setInt(false);
1411 /// Perform a derived-to-base member pointer cast.
1412 bool castToBase(const CXXRecordDecl *Base) {
1416 DeclAndIsDerivedMember.setInt(true);
1417 if (isDerivedMember()) {
1418 Path.push_back(Base);
1421 return castBack(Base);
1425 /// Compare two member pointers, which are assumed to be of the same type.
1426 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1427 if (!LHS.getDecl() || !RHS.getDecl())
1428 return !LHS.getDecl() && !RHS.getDecl();
1429 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1431 return LHS.Path == RHS.Path;
1435 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1436 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1437 const LValue &This, const Expr *E,
1438 bool AllowNonLiteralTypes = false);
1439 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1440 bool InvalidBaseOK = false);
1441 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1442 bool InvalidBaseOK = false);
1443 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1445 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1446 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1447 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1449 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1450 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1451 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1453 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1455 //===----------------------------------------------------------------------===//
1457 //===----------------------------------------------------------------------===//
1459 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1460 /// preserving its value (by extending by up to one bit as needed).
1461 static void negateAsSigned(APSInt &Int) {
1462 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1463 Int = Int.extend(Int.getBitWidth() + 1);
1464 Int.setIsSigned(true);
1469 /// Produce a string describing the given constexpr call.
1470 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1471 unsigned ArgIndex = 0;
1472 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1473 !isa<CXXConstructorDecl>(Frame->Callee) &&
1474 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1477 Out << *Frame->Callee << '(';
1479 if (Frame->This && IsMemberCall) {
1481 Frame->This->moveInto(Val);
1482 Val.printPretty(Out, Frame->Info.Ctx,
1483 Frame->This->Designator.MostDerivedType);
1484 // FIXME: Add parens around Val if needed.
1485 Out << "->" << *Frame->Callee << '(';
1486 IsMemberCall = false;
1489 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1490 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1491 if (ArgIndex > (unsigned)IsMemberCall)
1494 const ParmVarDecl *Param = *I;
1495 const APValue &Arg = Frame->Arguments[ArgIndex];
1496 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1498 if (ArgIndex == 0 && IsMemberCall)
1499 Out << "->" << *Frame->Callee << '(';
1505 /// Evaluate an expression to see if it had side-effects, and discard its
1507 /// \return \c true if the caller should keep evaluating.
1508 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1510 if (!Evaluate(Scratch, Info, E))
1511 // We don't need the value, but we might have skipped a side effect here.
1512 return Info.noteSideEffect();
1516 /// Should this call expression be treated as a string literal?
1517 static bool IsStringLiteralCall(const CallExpr *E) {
1518 unsigned Builtin = E->getBuiltinCallee();
1519 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1520 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1523 static bool IsGlobalLValue(APValue::LValueBase B) {
1524 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1525 // constant expression of pointer type that evaluates to...
1527 // ... a null pointer value, or a prvalue core constant expression of type
1529 if (!B) return true;
1531 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1532 // ... the address of an object with static storage duration,
1533 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1534 return VD->hasGlobalStorage();
1535 // ... the address of a function,
1536 return isa<FunctionDecl>(D);
1539 const Expr *E = B.get<const Expr*>();
1540 switch (E->getStmtClass()) {
1543 case Expr::CompoundLiteralExprClass: {
1544 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1545 return CLE->isFileScope() && CLE->isLValue();
1547 case Expr::MaterializeTemporaryExprClass:
1548 // A materialized temporary might have been lifetime-extended to static
1549 // storage duration.
1550 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1551 // A string literal has static storage duration.
1552 case Expr::StringLiteralClass:
1553 case Expr::PredefinedExprClass:
1554 case Expr::ObjCStringLiteralClass:
1555 case Expr::ObjCEncodeExprClass:
1556 case Expr::CXXTypeidExprClass:
1557 case Expr::CXXUuidofExprClass:
1559 case Expr::CallExprClass:
1560 return IsStringLiteralCall(cast<CallExpr>(E));
1561 // For GCC compatibility, &&label has static storage duration.
1562 case Expr::AddrLabelExprClass:
1564 // A Block literal expression may be used as the initialization value for
1565 // Block variables at global or local static scope.
1566 case Expr::BlockExprClass:
1567 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1568 case Expr::ImplicitValueInitExprClass:
1570 // We can never form an lvalue with an implicit value initialization as its
1571 // base through expression evaluation, so these only appear in one case: the
1572 // implicit variable declaration we invent when checking whether a constexpr
1573 // constructor can produce a constant expression. We must assume that such
1574 // an expression might be a global lvalue.
1579 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1580 assert(Base && "no location for a null lvalue");
1581 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1583 Info.Note(VD->getLocation(), diag::note_declared_at);
1585 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1586 diag::note_constexpr_temporary_here);
1589 /// Check that this reference or pointer core constant expression is a valid
1590 /// value for an address or reference constant expression. Return true if we
1591 /// can fold this expression, whether or not it's a constant expression.
1592 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1593 QualType Type, const LValue &LVal) {
1594 bool IsReferenceType = Type->isReferenceType();
1596 APValue::LValueBase Base = LVal.getLValueBase();
1597 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1599 // Check that the object is a global. Note that the fake 'this' object we
1600 // manufacture when checking potential constant expressions is conservatively
1601 // assumed to be global here.
1602 if (!IsGlobalLValue(Base)) {
1603 if (Info.getLangOpts().CPlusPlus11) {
1604 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1605 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1606 << IsReferenceType << !Designator.Entries.empty()
1608 NoteLValueLocation(Info, Base);
1612 // Don't allow references to temporaries to escape.
1615 assert((Info.checkingPotentialConstantExpression() ||
1616 LVal.getLValueCallIndex() == 0) &&
1617 "have call index for global lvalue");
1619 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1620 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1621 // Check if this is a thread-local variable.
1622 if (Var->getTLSKind())
1625 // A dllimport variable never acts like a constant.
1626 if (Var->hasAttr<DLLImportAttr>())
1629 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1630 // __declspec(dllimport) must be handled very carefully:
1631 // We must never initialize an expression with the thunk in C++.
1632 // Doing otherwise would allow the same id-expression to yield
1633 // different addresses for the same function in different translation
1634 // units. However, this means that we must dynamically initialize the
1635 // expression with the contents of the import address table at runtime.
1637 // The C language has no notion of ODR; furthermore, it has no notion of
1638 // dynamic initialization. This means that we are permitted to
1639 // perform initialization with the address of the thunk.
1640 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1645 // Allow address constant expressions to be past-the-end pointers. This is
1646 // an extension: the standard requires them to point to an object.
1647 if (!IsReferenceType)
1650 // A reference constant expression must refer to an object.
1652 // FIXME: diagnostic
1657 // Does this refer one past the end of some object?
1658 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1659 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1660 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1661 << !Designator.Entries.empty() << !!VD << VD;
1662 NoteLValueLocation(Info, Base);
1668 /// Member pointers are constant expressions unless they point to a
1669 /// non-virtual dllimport member function.
1670 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1673 const APValue &Value) {
1674 const ValueDecl *Member = Value.getMemberPointerDecl();
1675 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1678 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1681 /// Check that this core constant expression is of literal type, and if not,
1682 /// produce an appropriate diagnostic.
1683 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1684 const LValue *This = nullptr) {
1685 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1688 // C++1y: A constant initializer for an object o [...] may also invoke
1689 // constexpr constructors for o and its subobjects even if those objects
1690 // are of non-literal class types.
1692 // C++11 missed this detail for aggregates, so classes like this:
1693 // struct foo_t { union { int i; volatile int j; } u; };
1694 // are not (obviously) initializable like so:
1695 // __attribute__((__require_constant_initialization__))
1696 // static const foo_t x = {{0}};
1697 // because "i" is a subobject with non-literal initialization (due to the
1698 // volatile member of the union). See:
1699 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1700 // Therefore, we use the C++1y behavior.
1701 if (This && Info.EvaluatingDecl == This->getLValueBase())
1704 // Prvalue constant expressions must be of literal types.
1705 if (Info.getLangOpts().CPlusPlus11)
1706 Info.FFDiag(E, diag::note_constexpr_nonliteral)
1709 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1713 /// Check that this core constant expression value is a valid value for a
1714 /// constant expression. If not, report an appropriate diagnostic. Does not
1715 /// check that the expression is of literal type.
1716 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1717 QualType Type, const APValue &Value) {
1718 if (Value.isUninit()) {
1719 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1724 // We allow _Atomic(T) to be initialized from anything that T can be
1725 // initialized from.
1726 if (const AtomicType *AT = Type->getAs<AtomicType>())
1727 Type = AT->getValueType();
1729 // Core issue 1454: For a literal constant expression of array or class type,
1730 // each subobject of its value shall have been initialized by a constant
1732 if (Value.isArray()) {
1733 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1734 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1735 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1736 Value.getArrayInitializedElt(I)))
1739 if (!Value.hasArrayFiller())
1741 return CheckConstantExpression(Info, DiagLoc, EltTy,
1742 Value.getArrayFiller());
1744 if (Value.isUnion() && Value.getUnionField()) {
1745 return CheckConstantExpression(Info, DiagLoc,
1746 Value.getUnionField()->getType(),
1747 Value.getUnionValue());
1749 if (Value.isStruct()) {
1750 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1751 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1752 unsigned BaseIndex = 0;
1753 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1754 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1755 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1756 Value.getStructBase(BaseIndex)))
1760 for (const auto *I : RD->fields()) {
1761 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1762 Value.getStructField(I->getFieldIndex())))
1767 if (Value.isLValue()) {
1769 LVal.setFrom(Info.Ctx, Value);
1770 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1773 if (Value.isMemberPointer())
1774 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1776 // Everything else is fine.
1780 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1781 return LVal.Base.dyn_cast<const ValueDecl*>();
1784 static bool IsLiteralLValue(const LValue &Value) {
1785 if (Value.CallIndex)
1787 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1788 return E && !isa<MaterializeTemporaryExpr>(E);
1791 static bool IsWeakLValue(const LValue &Value) {
1792 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1793 return Decl && Decl->isWeak();
1796 static bool isZeroSized(const LValue &Value) {
1797 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1798 if (Decl && isa<VarDecl>(Decl)) {
1799 QualType Ty = Decl->getType();
1800 if (Ty->isArrayType())
1801 return Ty->isIncompleteType() ||
1802 Decl->getASTContext().getTypeSize(Ty) == 0;
1807 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1808 // A null base expression indicates a null pointer. These are always
1809 // evaluatable, and they are false unless the offset is zero.
1810 if (!Value.getLValueBase()) {
1811 Result = !Value.getLValueOffset().isZero();
1815 // We have a non-null base. These are generally known to be true, but if it's
1816 // a weak declaration it can be null at runtime.
1818 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1819 return !Decl || !Decl->isWeak();
1822 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1823 switch (Val.getKind()) {
1824 case APValue::Uninitialized:
1827 Result = Val.getInt().getBoolValue();
1829 case APValue::Float:
1830 Result = !Val.getFloat().isZero();
1832 case APValue::ComplexInt:
1833 Result = Val.getComplexIntReal().getBoolValue() ||
1834 Val.getComplexIntImag().getBoolValue();
1836 case APValue::ComplexFloat:
1837 Result = !Val.getComplexFloatReal().isZero() ||
1838 !Val.getComplexFloatImag().isZero();
1840 case APValue::LValue:
1841 return EvalPointerValueAsBool(Val, Result);
1842 case APValue::MemberPointer:
1843 Result = Val.getMemberPointerDecl();
1845 case APValue::Vector:
1846 case APValue::Array:
1847 case APValue::Struct:
1848 case APValue::Union:
1849 case APValue::AddrLabelDiff:
1853 llvm_unreachable("unknown APValue kind");
1856 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1858 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1860 if (!Evaluate(Val, Info, E))
1862 return HandleConversionToBool(Val, Result);
1865 template<typename T>
1866 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1867 const T &SrcValue, QualType DestType) {
1868 Info.CCEDiag(E, diag::note_constexpr_overflow)
1869 << SrcValue << DestType;
1870 return Info.noteUndefinedBehavior();
1873 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1874 QualType SrcType, const APFloat &Value,
1875 QualType DestType, APSInt &Result) {
1876 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1877 // Determine whether we are converting to unsigned or signed.
1878 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1880 Result = APSInt(DestWidth, !DestSigned);
1882 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1883 & APFloat::opInvalidOp)
1884 return HandleOverflow(Info, E, Value, DestType);
1888 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1889 QualType SrcType, QualType DestType,
1891 APFloat Value = Result;
1893 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1894 APFloat::rmNearestTiesToEven, &ignored)
1895 & APFloat::opOverflow)
1896 return HandleOverflow(Info, E, Value, DestType);
1900 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1901 QualType DestType, QualType SrcType,
1902 const APSInt &Value) {
1903 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1904 APSInt Result = Value;
1905 // Figure out if this is a truncate, extend or noop cast.
1906 // If the input is signed, do a sign extend, noop, or truncate.
1907 Result = Result.extOrTrunc(DestWidth);
1908 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1912 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1913 QualType SrcType, const APSInt &Value,
1914 QualType DestType, APFloat &Result) {
1915 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1916 if (Result.convertFromAPInt(Value, Value.isSigned(),
1917 APFloat::rmNearestTiesToEven)
1918 & APFloat::opOverflow)
1919 return HandleOverflow(Info, E, Value, DestType);
1923 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1924 APValue &Value, const FieldDecl *FD) {
1925 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1927 if (!Value.isInt()) {
1928 // Trying to store a pointer-cast-to-integer into a bitfield.
1929 // FIXME: In this case, we should provide the diagnostic for casting
1930 // a pointer to an integer.
1931 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1936 APSInt &Int = Value.getInt();
1937 unsigned OldBitWidth = Int.getBitWidth();
1938 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1939 if (NewBitWidth < OldBitWidth)
1940 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1944 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1947 if (!Evaluate(SVal, Info, E))
1950 Res = SVal.getInt();
1953 if (SVal.isFloat()) {
1954 Res = SVal.getFloat().bitcastToAPInt();
1957 if (SVal.isVector()) {
1958 QualType VecTy = E->getType();
1959 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1960 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1961 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1962 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1963 Res = llvm::APInt::getNullValue(VecSize);
1964 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1965 APValue &Elt = SVal.getVectorElt(i);
1966 llvm::APInt EltAsInt;
1968 EltAsInt = Elt.getInt();
1969 } else if (Elt.isFloat()) {
1970 EltAsInt = Elt.getFloat().bitcastToAPInt();
1972 // Don't try to handle vectors of anything other than int or float
1973 // (not sure if it's possible to hit this case).
1974 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1977 unsigned BaseEltSize = EltAsInt.getBitWidth();
1979 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1981 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1985 // Give up if the input isn't an int, float, or vector. For example, we
1986 // reject "(v4i16)(intptr_t)&a".
1987 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1991 /// Perform the given integer operation, which is known to need at most BitWidth
1992 /// bits, and check for overflow in the original type (if that type was not an
1994 template<typename Operation>
1995 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1996 const APSInt &LHS, const APSInt &RHS,
1997 unsigned BitWidth, Operation Op,
1999 if (LHS.isUnsigned()) {
2000 Result = Op(LHS, RHS);
2004 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2005 Result = Value.trunc(LHS.getBitWidth());
2006 if (Result.extend(BitWidth) != Value) {
2007 if (Info.checkingForOverflow())
2008 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2009 diag::warn_integer_constant_overflow)
2010 << Result.toString(10) << E->getType();
2012 return HandleOverflow(Info, E, Value, E->getType());
2017 /// Perform the given binary integer operation.
2018 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2019 BinaryOperatorKind Opcode, APSInt RHS,
2026 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2027 std::multiplies<APSInt>(), Result);
2029 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2030 std::plus<APSInt>(), Result);
2032 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2033 std::minus<APSInt>(), Result);
2034 case BO_And: Result = LHS & RHS; return true;
2035 case BO_Xor: Result = LHS ^ RHS; return true;
2036 case BO_Or: Result = LHS | RHS; return true;
2040 Info.FFDiag(E, diag::note_expr_divide_by_zero);
2043 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2044 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2045 // this operation and gives the two's complement result.
2046 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2047 LHS.isSigned() && LHS.isMinSignedValue())
2048 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2052 if (Info.getLangOpts().OpenCL)
2053 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2054 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2055 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2057 else if (RHS.isSigned() && RHS.isNegative()) {
2058 // During constant-folding, a negative shift is an opposite shift. Such
2059 // a shift is not a constant expression.
2060 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2065 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2066 // the shifted type.
2067 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2069 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2070 << RHS << E->getType() << LHS.getBitWidth();
2071 } else if (LHS.isSigned()) {
2072 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2073 // operand, and must not overflow the corresponding unsigned type.
2074 if (LHS.isNegative())
2075 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2076 else if (LHS.countLeadingZeros() < SA)
2077 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2083 if (Info.getLangOpts().OpenCL)
2084 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2085 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2086 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2088 else if (RHS.isSigned() && RHS.isNegative()) {
2089 // During constant-folding, a negative shift is an opposite shift. Such a
2090 // shift is not a constant expression.
2091 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2096 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2098 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2100 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2101 << RHS << E->getType() << LHS.getBitWidth();
2106 case BO_LT: Result = LHS < RHS; return true;
2107 case BO_GT: Result = LHS > RHS; return true;
2108 case BO_LE: Result = LHS <= RHS; return true;
2109 case BO_GE: Result = LHS >= RHS; return true;
2110 case BO_EQ: Result = LHS == RHS; return true;
2111 case BO_NE: Result = LHS != RHS; return true;
2115 /// Perform the given binary floating-point operation, in-place, on LHS.
2116 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2117 APFloat &LHS, BinaryOperatorKind Opcode,
2118 const APFloat &RHS) {
2124 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2127 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2130 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2133 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2137 if (LHS.isInfinity() || LHS.isNaN()) {
2138 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2139 return Info.noteUndefinedBehavior();
2144 /// Cast an lvalue referring to a base subobject to a derived class, by
2145 /// truncating the lvalue's path to the given length.
2146 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2147 const RecordDecl *TruncatedType,
2148 unsigned TruncatedElements) {
2149 SubobjectDesignator &D = Result.Designator;
2151 // Check we actually point to a derived class object.
2152 if (TruncatedElements == D.Entries.size())
2154 assert(TruncatedElements >= D.MostDerivedPathLength &&
2155 "not casting to a derived class");
2156 if (!Result.checkSubobject(Info, E, CSK_Derived))
2159 // Truncate the path to the subobject, and remove any derived-to-base offsets.
2160 const RecordDecl *RD = TruncatedType;
2161 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2162 if (RD->isInvalidDecl()) return false;
2163 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2164 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2165 if (isVirtualBaseClass(D.Entries[I]))
2166 Result.Offset -= Layout.getVBaseClassOffset(Base);
2168 Result.Offset -= Layout.getBaseClassOffset(Base);
2171 D.Entries.resize(TruncatedElements);
2175 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2176 const CXXRecordDecl *Derived,
2177 const CXXRecordDecl *Base,
2178 const ASTRecordLayout *RL = nullptr) {
2180 if (Derived->isInvalidDecl()) return false;
2181 RL = &Info.Ctx.getASTRecordLayout(Derived);
2184 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2185 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2189 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2190 const CXXRecordDecl *DerivedDecl,
2191 const CXXBaseSpecifier *Base) {
2192 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2194 if (!Base->isVirtual())
2195 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2197 SubobjectDesignator &D = Obj.Designator;
2201 // Extract most-derived object and corresponding type.
2202 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2203 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2206 // Find the virtual base class.
2207 if (DerivedDecl->isInvalidDecl()) return false;
2208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2209 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2210 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2214 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2215 QualType Type, LValue &Result) {
2216 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2217 PathE = E->path_end();
2218 PathI != PathE; ++PathI) {
2219 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2222 Type = (*PathI)->getType();
2227 /// Update LVal to refer to the given field, which must be a member of the type
2228 /// currently described by LVal.
2229 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2230 const FieldDecl *FD,
2231 const ASTRecordLayout *RL = nullptr) {
2233 if (FD->getParent()->isInvalidDecl()) return false;
2234 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2237 unsigned I = FD->getFieldIndex();
2238 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2239 LVal.addDecl(Info, E, FD);
2243 /// Update LVal to refer to the given indirect field.
2244 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2246 const IndirectFieldDecl *IFD) {
2247 for (const auto *C : IFD->chain())
2248 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2253 /// Get the size of the given type in char units.
2254 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2255 QualType Type, CharUnits &Size) {
2256 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2258 if (Type->isVoidType() || Type->isFunctionType()) {
2259 Size = CharUnits::One();
2263 if (Type->isDependentType()) {
2268 if (!Type->isConstantSizeType()) {
2269 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2270 // FIXME: Better diagnostic.
2275 Size = Info.Ctx.getTypeSizeInChars(Type);
2279 /// Update a pointer value to model pointer arithmetic.
2280 /// \param Info - Information about the ongoing evaluation.
2281 /// \param E - The expression being evaluated, for diagnostic purposes.
2282 /// \param LVal - The pointer value to be updated.
2283 /// \param EltTy - The pointee type represented by LVal.
2284 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2285 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2286 LValue &LVal, QualType EltTy,
2287 APSInt Adjustment) {
2288 CharUnits SizeOfPointee;
2289 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2292 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2296 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2297 LValue &LVal, QualType EltTy,
2298 int64_t Adjustment) {
2299 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2300 APSInt::get(Adjustment));
2303 /// Update an lvalue to refer to a component of a complex number.
2304 /// \param Info - Information about the ongoing evaluation.
2305 /// \param LVal - The lvalue to be updated.
2306 /// \param EltTy - The complex number's component type.
2307 /// \param Imag - False for the real component, true for the imaginary.
2308 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2309 LValue &LVal, QualType EltTy,
2312 CharUnits SizeOfComponent;
2313 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2315 LVal.Offset += SizeOfComponent;
2317 LVal.addComplex(Info, E, EltTy, Imag);
2321 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2322 QualType Type, const LValue &LVal,
2325 /// Try to evaluate the initializer for a variable declaration.
2327 /// \param Info Information about the ongoing evaluation.
2328 /// \param E An expression to be used when printing diagnostics.
2329 /// \param VD The variable whose initializer should be obtained.
2330 /// \param Frame The frame in which the variable was created. Must be null
2331 /// if this variable is not local to the evaluation.
2332 /// \param Result Filled in with a pointer to the value of the variable.
2333 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2334 const VarDecl *VD, CallStackFrame *Frame,
2337 // If this is a parameter to an active constexpr function call, perform
2338 // argument substitution.
2339 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2340 // Assume arguments of a potential constant expression are unknown
2341 // constant expressions.
2342 if (Info.checkingPotentialConstantExpression())
2344 if (!Frame || !Frame->Arguments) {
2345 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2348 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2352 // If this is a local variable, dig out its value.
2354 Result = Frame->getTemporary(VD);
2356 // Assume variables referenced within a lambda's call operator that were
2357 // not declared within the call operator are captures and during checking
2358 // of a potential constant expression, assume they are unknown constant
2360 assert(isLambdaCallOperator(Frame->Callee) &&
2361 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2362 "missing value for local variable");
2363 if (Info.checkingPotentialConstantExpression())
2365 // FIXME: implement capture evaluation during constant expr evaluation.
2366 Info.FFDiag(E->getLocStart(),
2367 diag::note_unimplemented_constexpr_lambda_feature_ast)
2368 << "captures not currently allowed";
2374 // Dig out the initializer, and use the declaration which it's attached to.
2375 const Expr *Init = VD->getAnyInitializer(VD);
2376 if (!Init || Init->isValueDependent()) {
2377 // If we're checking a potential constant expression, the variable could be
2378 // initialized later.
2379 if (!Info.checkingPotentialConstantExpression())
2380 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2384 // If we're currently evaluating the initializer of this declaration, use that
2386 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2387 Result = Info.EvaluatingDeclValue;
2391 // Never evaluate the initializer of a weak variable. We can't be sure that
2392 // this is the definition which will be used.
2394 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2398 // Check that we can fold the initializer. In C++, we will have already done
2399 // this in the cases where it matters for conformance.
2400 SmallVector<PartialDiagnosticAt, 8> Notes;
2401 if (!VD->evaluateValue(Notes)) {
2402 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2403 Notes.size() + 1) << VD;
2404 Info.Note(VD->getLocation(), diag::note_declared_at);
2405 Info.addNotes(Notes);
2407 } else if (!VD->checkInitIsICE()) {
2408 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2409 Notes.size() + 1) << VD;
2410 Info.Note(VD->getLocation(), diag::note_declared_at);
2411 Info.addNotes(Notes);
2414 Result = VD->getEvaluatedValue();
2418 static bool IsConstNonVolatile(QualType T) {
2419 Qualifiers Quals = T.getQualifiers();
2420 return Quals.hasConst() && !Quals.hasVolatile();
2423 /// Get the base index of the given base class within an APValue representing
2424 /// the given derived class.
2425 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2426 const CXXRecordDecl *Base) {
2427 Base = Base->getCanonicalDecl();
2429 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2430 E = Derived->bases_end(); I != E; ++I, ++Index) {
2431 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2435 llvm_unreachable("base class missing from derived class's bases list");
2438 /// Extract the value of a character from a string literal.
2439 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2441 // FIXME: Support MakeStringConstant
2442 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2444 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2445 assert(Index <= Str.size() && "Index too large");
2446 return APSInt::getUnsigned(Str.c_str()[Index]);
2449 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2450 Lit = PE->getFunctionName();
2451 const StringLiteral *S = cast<StringLiteral>(Lit);
2452 const ConstantArrayType *CAT =
2453 Info.Ctx.getAsConstantArrayType(S->getType());
2454 assert(CAT && "string literal isn't an array");
2455 QualType CharType = CAT->getElementType();
2456 assert(CharType->isIntegerType() && "unexpected character type");
2458 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2459 CharType->isUnsignedIntegerType());
2460 if (Index < S->getLength())
2461 Value = S->getCodeUnit(Index);
2465 // Expand a string literal into an array of characters.
2466 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2468 const StringLiteral *S = cast<StringLiteral>(Lit);
2469 const ConstantArrayType *CAT =
2470 Info.Ctx.getAsConstantArrayType(S->getType());
2471 assert(CAT && "string literal isn't an array");
2472 QualType CharType = CAT->getElementType();
2473 assert(CharType->isIntegerType() && "unexpected character type");
2475 unsigned Elts = CAT->getSize().getZExtValue();
2476 Result = APValue(APValue::UninitArray(),
2477 std::min(S->getLength(), Elts), Elts);
2478 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2479 CharType->isUnsignedIntegerType());
2480 if (Result.hasArrayFiller())
2481 Result.getArrayFiller() = APValue(Value);
2482 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2483 Value = S->getCodeUnit(I);
2484 Result.getArrayInitializedElt(I) = APValue(Value);
2488 // Expand an array so that it has more than Index filled elements.
2489 static void expandArray(APValue &Array, unsigned Index) {
2490 unsigned Size = Array.getArraySize();
2491 assert(Index < Size);
2493 // Always at least double the number of elements for which we store a value.
2494 unsigned OldElts = Array.getArrayInitializedElts();
2495 unsigned NewElts = std::max(Index+1, OldElts * 2);
2496 NewElts = std::min(Size, std::max(NewElts, 8u));
2498 // Copy the data across.
2499 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2500 for (unsigned I = 0; I != OldElts; ++I)
2501 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2502 for (unsigned I = OldElts; I != NewElts; ++I)
2503 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2504 if (NewValue.hasArrayFiller())
2505 NewValue.getArrayFiller() = Array.getArrayFiller();
2506 Array.swap(NewValue);
2509 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2510 /// conversion. If it's of class type, we may assume that the copy operation
2511 /// is trivial. Note that this is never true for a union type with fields
2512 /// (because the copy always "reads" the active member) and always true for
2513 /// a non-class type.
2514 static bool isReadByLvalueToRvalueConversion(QualType T) {
2515 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2516 if (!RD || (RD->isUnion() && !RD->field_empty()))
2521 for (auto *Field : RD->fields())
2522 if (isReadByLvalueToRvalueConversion(Field->getType()))
2525 for (auto &BaseSpec : RD->bases())
2526 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2532 /// Diagnose an attempt to read from any unreadable field within the specified
2533 /// type, which might be a class type.
2534 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2536 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2540 if (!RD->hasMutableFields())
2543 for (auto *Field : RD->fields()) {
2544 // If we're actually going to read this field in some way, then it can't
2545 // be mutable. If we're in a union, then assigning to a mutable field
2546 // (even an empty one) can change the active member, so that's not OK.
2547 // FIXME: Add core issue number for the union case.
2548 if (Field->isMutable() &&
2549 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2550 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2551 Info.Note(Field->getLocation(), diag::note_declared_at);
2555 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2559 for (auto &BaseSpec : RD->bases())
2560 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2563 // All mutable fields were empty, and thus not actually read.
2567 /// Kinds of access we can perform on an object, for diagnostics.
2576 /// A handle to a complete object (an object that is not a subobject of
2577 /// another object).
2578 struct CompleteObject {
2579 /// The value of the complete object.
2581 /// The type of the complete object.
2584 CompleteObject() : Value(nullptr) {}
2585 CompleteObject(APValue *Value, QualType Type)
2586 : Value(Value), Type(Type) {
2587 assert(Value && "missing value for complete object");
2590 explicit operator bool() const { return Value; }
2592 } // end anonymous namespace
2594 /// Find the designated sub-object of an rvalue.
2595 template<typename SubobjectHandler>
2596 typename SubobjectHandler::result_type
2597 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2598 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2600 // A diagnostic will have already been produced.
2601 return handler.failed();
2602 if (Sub.isOnePastTheEnd()) {
2603 if (Info.getLangOpts().CPlusPlus11)
2604 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2605 << handler.AccessKind;
2608 return handler.failed();
2611 APValue *O = Obj.Value;
2612 QualType ObjType = Obj.Type;
2613 const FieldDecl *LastField = nullptr;
2615 // Walk the designator's path to find the subobject.
2616 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2617 if (O->isUninit()) {
2618 if (!Info.checkingPotentialConstantExpression())
2619 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2620 return handler.failed();
2624 // If we are reading an object of class type, there may still be more
2625 // things we need to check: if there are any mutable subobjects, we
2626 // cannot perform this read. (This only happens when performing a trivial
2627 // copy or assignment.)
2628 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2629 diagnoseUnreadableFields(Info, E, ObjType))
2630 return handler.failed();
2632 if (!handler.found(*O, ObjType))
2635 // If we modified a bit-field, truncate it to the right width.
2636 if (handler.AccessKind != AK_Read &&
2637 LastField && LastField->isBitField() &&
2638 !truncateBitfieldValue(Info, E, *O, LastField))
2644 LastField = nullptr;
2645 if (ObjType->isArrayType()) {
2646 // Next subobject is an array element.
2647 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2648 assert(CAT && "vla in literal type?");
2649 uint64_t Index = Sub.Entries[I].ArrayIndex;
2650 if (CAT->getSize().ule(Index)) {
2651 // Note, it should not be possible to form a pointer with a valid
2652 // designator which points more than one past the end of the array.
2653 if (Info.getLangOpts().CPlusPlus11)
2654 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2655 << handler.AccessKind;
2658 return handler.failed();
2661 ObjType = CAT->getElementType();
2663 // An array object is represented as either an Array APValue or as an
2664 // LValue which refers to a string literal.
2665 if (O->isLValue()) {
2666 assert(I == N - 1 && "extracting subobject of character?");
2667 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2668 if (handler.AccessKind != AK_Read)
2669 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2672 return handler.foundString(*O, ObjType, Index);
2675 if (O->getArrayInitializedElts() > Index)
2676 O = &O->getArrayInitializedElt(Index);
2677 else if (handler.AccessKind != AK_Read) {
2678 expandArray(*O, Index);
2679 O = &O->getArrayInitializedElt(Index);
2681 O = &O->getArrayFiller();
2682 } else if (ObjType->isAnyComplexType()) {
2683 // Next subobject is a complex number.
2684 uint64_t Index = Sub.Entries[I].ArrayIndex;
2686 if (Info.getLangOpts().CPlusPlus11)
2687 Info.FFDiag(E, diag::note_constexpr_access_past_end)
2688 << handler.AccessKind;
2691 return handler.failed();
2694 bool WasConstQualified = ObjType.isConstQualified();
2695 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2696 if (WasConstQualified)
2699 assert(I == N - 1 && "extracting subobject of scalar?");
2700 if (O->isComplexInt()) {
2701 return handler.found(Index ? O->getComplexIntImag()
2702 : O->getComplexIntReal(), ObjType);
2704 assert(O->isComplexFloat());
2705 return handler.found(Index ? O->getComplexFloatImag()
2706 : O->getComplexFloatReal(), ObjType);
2708 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2709 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2710 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2712 Info.Note(Field->getLocation(), diag::note_declared_at);
2713 return handler.failed();
2716 // Next subobject is a class, struct or union field.
2717 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2718 if (RD->isUnion()) {
2719 const FieldDecl *UnionField = O->getUnionField();
2721 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2722 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2723 << handler.AccessKind << Field << !UnionField << UnionField;
2724 return handler.failed();
2726 O = &O->getUnionValue();
2728 O = &O->getStructField(Field->getFieldIndex());
2730 bool WasConstQualified = ObjType.isConstQualified();
2731 ObjType = Field->getType();
2732 if (WasConstQualified && !Field->isMutable())
2735 if (ObjType.isVolatileQualified()) {
2736 if (Info.getLangOpts().CPlusPlus) {
2737 // FIXME: Include a description of the path to the volatile subobject.
2738 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2739 << handler.AccessKind << 2 << Field;
2740 Info.Note(Field->getLocation(), diag::note_declared_at);
2742 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2744 return handler.failed();
2749 // Next subobject is a base class.
2750 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2751 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2752 O = &O->getStructBase(getBaseIndex(Derived, Base));
2754 bool WasConstQualified = ObjType.isConstQualified();
2755 ObjType = Info.Ctx.getRecordType(Base);
2756 if (WasConstQualified)
2763 struct ExtractSubobjectHandler {
2767 static const AccessKinds AccessKind = AK_Read;
2769 typedef bool result_type;
2770 bool failed() { return false; }
2771 bool found(APValue &Subobj, QualType SubobjType) {
2775 bool found(APSInt &Value, QualType SubobjType) {
2776 Result = APValue(Value);
2779 bool found(APFloat &Value, QualType SubobjType) {
2780 Result = APValue(Value);
2783 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2784 Result = APValue(extractStringLiteralCharacter(
2785 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2789 } // end anonymous namespace
2791 const AccessKinds ExtractSubobjectHandler::AccessKind;
2793 /// Extract the designated sub-object of an rvalue.
2794 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2795 const CompleteObject &Obj,
2796 const SubobjectDesignator &Sub,
2798 ExtractSubobjectHandler Handler = { Info, Result };
2799 return findSubobject(Info, E, Obj, Sub, Handler);
2803 struct ModifySubobjectHandler {
2808 typedef bool result_type;
2809 static const AccessKinds AccessKind = AK_Assign;
2811 bool checkConst(QualType QT) {
2812 // Assigning to a const object has undefined behavior.
2813 if (QT.isConstQualified()) {
2814 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2820 bool failed() { return false; }
2821 bool found(APValue &Subobj, QualType SubobjType) {
2822 if (!checkConst(SubobjType))
2824 // We've been given ownership of NewVal, so just swap it in.
2825 Subobj.swap(NewVal);
2828 bool found(APSInt &Value, QualType SubobjType) {
2829 if (!checkConst(SubobjType))
2831 if (!NewVal.isInt()) {
2832 // Maybe trying to write a cast pointer value into a complex?
2836 Value = NewVal.getInt();
2839 bool found(APFloat &Value, QualType SubobjType) {
2840 if (!checkConst(SubobjType))
2842 Value = NewVal.getFloat();
2845 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2846 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2849 } // end anonymous namespace
2851 const AccessKinds ModifySubobjectHandler::AccessKind;
2853 /// Update the designated sub-object of an rvalue to the given value.
2854 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2855 const CompleteObject &Obj,
2856 const SubobjectDesignator &Sub,
2858 ModifySubobjectHandler Handler = { Info, NewVal, E };
2859 return findSubobject(Info, E, Obj, Sub, Handler);
2862 /// Find the position where two subobject designators diverge, or equivalently
2863 /// the length of the common initial subsequence.
2864 static unsigned FindDesignatorMismatch(QualType ObjType,
2865 const SubobjectDesignator &A,
2866 const SubobjectDesignator &B,
2867 bool &WasArrayIndex) {
2868 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2869 for (/**/; I != N; ++I) {
2870 if (!ObjType.isNull() &&
2871 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2872 // Next subobject is an array element.
2873 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2874 WasArrayIndex = true;
2877 if (ObjType->isAnyComplexType())
2878 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2880 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2882 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2883 WasArrayIndex = false;
2886 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2887 // Next subobject is a field.
2888 ObjType = FD->getType();
2890 // Next subobject is a base class.
2891 ObjType = QualType();
2894 WasArrayIndex = false;
2898 /// Determine whether the given subobject designators refer to elements of the
2899 /// same array object.
2900 static bool AreElementsOfSameArray(QualType ObjType,
2901 const SubobjectDesignator &A,
2902 const SubobjectDesignator &B) {
2903 if (A.Entries.size() != B.Entries.size())
2906 bool IsArray = A.MostDerivedIsArrayElement;
2907 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2908 // A is a subobject of the array element.
2911 // If A (and B) designates an array element, the last entry will be the array
2912 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2913 // of length 1' case, and the entire path must match.
2915 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2916 return CommonLength >= A.Entries.size() - IsArray;
2919 /// Find the complete object to which an LValue refers.
2920 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2921 AccessKinds AK, const LValue &LVal,
2922 QualType LValType) {
2924 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2925 return CompleteObject();
2928 CallStackFrame *Frame = nullptr;
2929 if (LVal.CallIndex) {
2930 Frame = Info.getCallFrame(LVal.CallIndex);
2932 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2933 << AK << LVal.Base.is<const ValueDecl*>();
2934 NoteLValueLocation(Info, LVal.Base);
2935 return CompleteObject();
2939 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2940 // is not a constant expression (even if the object is non-volatile). We also
2941 // apply this rule to C++98, in order to conform to the expected 'volatile'
2943 if (LValType.isVolatileQualified()) {
2944 if (Info.getLangOpts().CPlusPlus)
2945 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2949 return CompleteObject();
2952 // Compute value storage location and type of base object.
2953 APValue *BaseVal = nullptr;
2954 QualType BaseType = getType(LVal.Base);
2956 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2957 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2958 // In C++11, constexpr, non-volatile variables initialized with constant
2959 // expressions are constant expressions too. Inside constexpr functions,
2960 // parameters are constant expressions even if they're non-const.
2961 // In C++1y, objects local to a constant expression (those with a Frame) are
2962 // both readable and writable inside constant expressions.
2963 // In C, such things can also be folded, although they are not ICEs.
2964 const VarDecl *VD = dyn_cast<VarDecl>(D);
2966 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2969 if (!VD || VD->isInvalidDecl()) {
2971 return CompleteObject();
2974 // Accesses of volatile-qualified objects are not allowed.
2975 if (BaseType.isVolatileQualified()) {
2976 if (Info.getLangOpts().CPlusPlus) {
2977 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2979 Info.Note(VD->getLocation(), diag::note_declared_at);
2983 return CompleteObject();
2986 // Unless we're looking at a local variable or argument in a constexpr call,
2987 // the variable we're reading must be const.
2989 if (Info.getLangOpts().CPlusPlus14 &&
2990 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2991 // OK, we can read and modify an object if we're in the process of
2992 // evaluating its initializer, because its lifetime began in this
2994 } else if (AK != AK_Read) {
2995 // All the remaining cases only permit reading.
2996 Info.FFDiag(E, diag::note_constexpr_modify_global);
2997 return CompleteObject();
2998 } else if (VD->isConstexpr()) {
2999 // OK, we can read this variable.
3000 } else if (BaseType->isIntegralOrEnumerationType()) {
3001 // In OpenCL if a variable is in constant address space it is a const value.
3002 if (!(BaseType.isConstQualified() ||
3003 (Info.getLangOpts().OpenCL &&
3004 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3005 if (Info.getLangOpts().CPlusPlus) {
3006 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3007 Info.Note(VD->getLocation(), diag::note_declared_at);
3011 return CompleteObject();
3013 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3014 // We support folding of const floating-point types, in order to make
3015 // static const data members of such types (supported as an extension)
3017 if (Info.getLangOpts().CPlusPlus11) {
3018 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3019 Info.Note(VD->getLocation(), diag::note_declared_at);
3023 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3024 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3025 // Keep evaluating to see what we can do.
3027 // FIXME: Allow folding of values of any literal type in all languages.
3028 if (Info.checkingPotentialConstantExpression() &&
3029 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3030 // The definition of this variable could be constexpr. We can't
3031 // access it right now, but may be able to in future.
3032 } else if (Info.getLangOpts().CPlusPlus11) {
3033 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3034 Info.Note(VD->getLocation(), diag::note_declared_at);
3038 return CompleteObject();
3042 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3043 return CompleteObject();
3045 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3048 if (const MaterializeTemporaryExpr *MTE =
3049 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3050 assert(MTE->getStorageDuration() == SD_Static &&
3051 "should have a frame for a non-global materialized temporary");
3053 // Per C++1y [expr.const]p2:
3054 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3055 // - a [...] glvalue of integral or enumeration type that refers to
3056 // a non-volatile const object [...]
3058 // - a [...] glvalue of literal type that refers to a non-volatile
3059 // object whose lifetime began within the evaluation of e.
3061 // C++11 misses the 'began within the evaluation of e' check and
3062 // instead allows all temporaries, including things like:
3065 // constexpr int k = r;
3066 // Therefore we use the C++1y rules in C++11 too.
3067 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3068 const ValueDecl *ED = MTE->getExtendingDecl();
3069 if (!(BaseType.isConstQualified() &&
3070 BaseType->isIntegralOrEnumerationType()) &&
3071 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3072 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3073 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3074 return CompleteObject();
3077 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3078 assert(BaseVal && "got reference to unevaluated temporary");
3081 return CompleteObject();
3084 BaseVal = Frame->getTemporary(Base);
3085 assert(BaseVal && "missing value for temporary");
3088 // Volatile temporary objects cannot be accessed in constant expressions.
3089 if (BaseType.isVolatileQualified()) {
3090 if (Info.getLangOpts().CPlusPlus) {
3091 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3093 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3097 return CompleteObject();
3101 // During the construction of an object, it is not yet 'const'.
3102 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3103 // and this doesn't do quite the right thing for const subobjects of the
3104 // object under construction.
3105 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3106 BaseType = Info.Ctx.getCanonicalType(BaseType);
3107 BaseType.removeLocalConst();
3110 // In C++1y, we can't safely access any mutable state when we might be
3111 // evaluating after an unmodeled side effect.
3113 // FIXME: Not all local state is mutable. Allow local constant subobjects
3114 // to be read here (but take care with 'mutable' fields).
3115 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3116 Info.EvalStatus.HasSideEffects) ||
3117 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3118 return CompleteObject();
3120 return CompleteObject(BaseVal, BaseType);
3123 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3124 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3125 /// glvalue referred to by an entity of reference type.
3127 /// \param Info - Information about the ongoing evaluation.
3128 /// \param Conv - The expression for which we are performing the conversion.
3129 /// Used for diagnostics.
3130 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3131 /// case of a non-class type).
3132 /// \param LVal - The glvalue on which we are attempting to perform this action.
3133 /// \param RVal - The produced value will be placed here.
3134 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3136 const LValue &LVal, APValue &RVal) {
3137 if (LVal.Designator.Invalid)
3140 // Check for special cases where there is no existing APValue to look at.
3141 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3142 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3143 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3144 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3145 // initializer until now for such expressions. Such an expression can't be
3146 // an ICE in C, so this only matters for fold.
3147 if (Type.isVolatileQualified()) {
3152 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3154 CompleteObject LitObj(&Lit, Base->getType());
3155 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3156 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3157 // We represent a string literal array as an lvalue pointing at the
3158 // corresponding expression, rather than building an array of chars.
3159 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3160 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3161 CompleteObject StrObj(&Str, Base->getType());
3162 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3166 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3167 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3170 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3171 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3172 QualType LValType, APValue &Val) {
3173 if (LVal.Designator.Invalid)
3176 if (!Info.getLangOpts().CPlusPlus14) {
3181 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3182 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3185 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3186 return T->isSignedIntegerType() &&
3187 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3191 struct CompoundAssignSubobjectHandler {
3194 QualType PromotedLHSType;
3195 BinaryOperatorKind Opcode;
3198 static const AccessKinds AccessKind = AK_Assign;
3200 typedef bool result_type;
3202 bool checkConst(QualType QT) {
3203 // Assigning to a const object has undefined behavior.
3204 if (QT.isConstQualified()) {
3205 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3211 bool failed() { return false; }
3212 bool found(APValue &Subobj, QualType SubobjType) {
3213 switch (Subobj.getKind()) {
3215 return found(Subobj.getInt(), SubobjType);
3216 case APValue::Float:
3217 return found(Subobj.getFloat(), SubobjType);
3218 case APValue::ComplexInt:
3219 case APValue::ComplexFloat:
3220 // FIXME: Implement complex compound assignment.
3223 case APValue::LValue:
3224 return foundPointer(Subobj, SubobjType);
3226 // FIXME: can this happen?
3231 bool found(APSInt &Value, QualType SubobjType) {
3232 if (!checkConst(SubobjType))
3235 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3236 // We don't support compound assignment on integer-cast-to-pointer
3242 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3244 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3246 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3249 bool found(APFloat &Value, QualType SubobjType) {
3250 return checkConst(SubobjType) &&
3251 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3253 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3254 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3256 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3257 if (!checkConst(SubobjType))
3260 QualType PointeeType;
3261 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3262 PointeeType = PT->getPointeeType();
3264 if (PointeeType.isNull() || !RHS.isInt() ||
3265 (Opcode != BO_Add && Opcode != BO_Sub)) {
3270 APSInt Offset = RHS.getInt();
3271 if (Opcode == BO_Sub)
3272 negateAsSigned(Offset);
3275 LVal.setFrom(Info.Ctx, Subobj);
3276 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3278 LVal.moveInto(Subobj);
3281 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3282 llvm_unreachable("shouldn't encounter string elements here");
3285 } // end anonymous namespace
3287 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3289 /// Perform a compound assignment of LVal <op>= RVal.
3290 static bool handleCompoundAssignment(
3291 EvalInfo &Info, const Expr *E,
3292 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3293 BinaryOperatorKind Opcode, const APValue &RVal) {
3294 if (LVal.Designator.Invalid)
3297 if (!Info.getLangOpts().CPlusPlus14) {
3302 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3303 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3305 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3309 struct IncDecSubobjectHandler {
3312 AccessKinds AccessKind;
3315 typedef bool result_type;
3317 bool checkConst(QualType QT) {
3318 // Assigning to a const object has undefined behavior.
3319 if (QT.isConstQualified()) {
3320 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3326 bool failed() { return false; }
3327 bool found(APValue &Subobj, QualType SubobjType) {
3328 // Stash the old value. Also clear Old, so we don't clobber it later
3329 // if we're post-incrementing a complex.
3335 switch (Subobj.getKind()) {
3337 return found(Subobj.getInt(), SubobjType);
3338 case APValue::Float:
3339 return found(Subobj.getFloat(), SubobjType);
3340 case APValue::ComplexInt:
3341 return found(Subobj.getComplexIntReal(),
3342 SubobjType->castAs<ComplexType>()->getElementType()
3343 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3344 case APValue::ComplexFloat:
3345 return found(Subobj.getComplexFloatReal(),
3346 SubobjType->castAs<ComplexType>()->getElementType()
3347 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3348 case APValue::LValue:
3349 return foundPointer(Subobj, SubobjType);
3351 // FIXME: can this happen?
3356 bool found(APSInt &Value, QualType SubobjType) {
3357 if (!checkConst(SubobjType))
3360 if (!SubobjType->isIntegerType()) {
3361 // We don't support increment / decrement on integer-cast-to-pointer
3367 if (Old) *Old = APValue(Value);
3369 // bool arithmetic promotes to int, and the conversion back to bool
3370 // doesn't reduce mod 2^n, so special-case it.
3371 if (SubobjType->isBooleanType()) {
3372 if (AccessKind == AK_Increment)
3379 bool WasNegative = Value.isNegative();
3380 if (AccessKind == AK_Increment) {
3383 if (!WasNegative && Value.isNegative() &&
3384 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3385 APSInt ActualValue(Value, /*IsUnsigned*/true);
3386 return HandleOverflow(Info, E, ActualValue, SubobjType);
3391 if (WasNegative && !Value.isNegative() &&
3392 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3393 unsigned BitWidth = Value.getBitWidth();
3394 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3395 ActualValue.setBit(BitWidth);
3396 return HandleOverflow(Info, E, ActualValue, SubobjType);
3401 bool found(APFloat &Value, QualType SubobjType) {
3402 if (!checkConst(SubobjType))
3405 if (Old) *Old = APValue(Value);
3407 APFloat One(Value.getSemantics(), 1);
3408 if (AccessKind == AK_Increment)
3409 Value.add(One, APFloat::rmNearestTiesToEven);
3411 Value.subtract(One, APFloat::rmNearestTiesToEven);
3414 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3415 if (!checkConst(SubobjType))
3418 QualType PointeeType;
3419 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3420 PointeeType = PT->getPointeeType();
3427 LVal.setFrom(Info.Ctx, Subobj);
3428 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3429 AccessKind == AK_Increment ? 1 : -1))
3431 LVal.moveInto(Subobj);
3434 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3435 llvm_unreachable("shouldn't encounter string elements here");
3438 } // end anonymous namespace
3440 /// Perform an increment or decrement on LVal.
3441 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3442 QualType LValType, bool IsIncrement, APValue *Old) {
3443 if (LVal.Designator.Invalid)
3446 if (!Info.getLangOpts().CPlusPlus14) {
3451 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3452 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3453 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3454 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3457 /// Build an lvalue for the object argument of a member function call.
3458 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3460 if (Object->getType()->isPointerType())
3461 return EvaluatePointer(Object, This, Info);
3463 if (Object->isGLValue())
3464 return EvaluateLValue(Object, This, Info);
3466 if (Object->getType()->isLiteralType(Info.Ctx))
3467 return EvaluateTemporary(Object, This, Info);
3469 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3473 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3474 /// lvalue referring to the result.
3476 /// \param Info - Information about the ongoing evaluation.
3477 /// \param LV - An lvalue referring to the base of the member pointer.
3478 /// \param RHS - The member pointer expression.
3479 /// \param IncludeMember - Specifies whether the member itself is included in
3480 /// the resulting LValue subobject designator. This is not possible when
3481 /// creating a bound member function.
3482 /// \return The field or method declaration to which the member pointer refers,
3483 /// or 0 if evaluation fails.
3484 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3488 bool IncludeMember = true) {
3490 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3493 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3494 // member value, the behavior is undefined.
3495 if (!MemPtr.getDecl()) {
3496 // FIXME: Specific diagnostic.
3501 if (MemPtr.isDerivedMember()) {
3502 // This is a member of some derived class. Truncate LV appropriately.
3503 // The end of the derived-to-base path for the base object must match the
3504 // derived-to-base path for the member pointer.
3505 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3506 LV.Designator.Entries.size()) {
3510 unsigned PathLengthToMember =
3511 LV.Designator.Entries.size() - MemPtr.Path.size();
3512 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3513 const CXXRecordDecl *LVDecl = getAsBaseClass(
3514 LV.Designator.Entries[PathLengthToMember + I]);
3515 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3516 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3522 // Truncate the lvalue to the appropriate derived class.
3523 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3524 PathLengthToMember))
3526 } else if (!MemPtr.Path.empty()) {
3527 // Extend the LValue path with the member pointer's path.
3528 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3529 MemPtr.Path.size() + IncludeMember);
3531 // Walk down to the appropriate base class.
3532 if (const PointerType *PT = LVType->getAs<PointerType>())
3533 LVType = PT->getPointeeType();
3534 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3535 assert(RD && "member pointer access on non-class-type expression");
3536 // The first class in the path is that of the lvalue.
3537 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3538 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3539 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3543 // Finally cast to the class containing the member.
3544 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3545 MemPtr.getContainingRecord()))
3549 // Add the member. Note that we cannot build bound member functions here.
3550 if (IncludeMember) {
3551 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3552 if (!HandleLValueMember(Info, RHS, LV, FD))
3554 } else if (const IndirectFieldDecl *IFD =
3555 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3556 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3559 llvm_unreachable("can't construct reference to bound member function");
3563 return MemPtr.getDecl();
3566 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3567 const BinaryOperator *BO,
3569 bool IncludeMember = true) {
3570 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3572 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3573 if (Info.noteFailure()) {
3575 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3580 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3581 BO->getRHS(), IncludeMember);
3584 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3585 /// the provided lvalue, which currently refers to the base object.
3586 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3588 SubobjectDesignator &D = Result.Designator;
3589 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3592 QualType TargetQT = E->getType();
3593 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3594 TargetQT = PT->getPointeeType();
3596 // Check this cast lands within the final derived-to-base subobject path.
3597 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3598 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3599 << D.MostDerivedType << TargetQT;
3603 // Check the type of the final cast. We don't need to check the path,
3604 // since a cast can only be formed if the path is unique.
3605 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3606 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3607 const CXXRecordDecl *FinalType;
3608 if (NewEntriesSize == D.MostDerivedPathLength)
3609 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3611 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3612 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3613 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3614 << D.MostDerivedType << TargetQT;
3618 // Truncate the lvalue to the appropriate derived class.
3619 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3623 enum EvalStmtResult {
3624 /// Evaluation failed.
3626 /// Hit a 'return' statement.
3628 /// Evaluation succeeded.
3630 /// Hit a 'continue' statement.
3632 /// Hit a 'break' statement.
3634 /// Still scanning for 'case' or 'default' statement.
3639 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3640 // We don't need to evaluate the initializer for a static local.
3641 if (!VD->hasLocalStorage())
3645 Result.set(VD, Info.CurrentCall->Index);
3646 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3648 const Expr *InitE = VD->getInit();
3650 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3651 << false << VD->getType();
3656 if (InitE->isValueDependent())
3659 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3660 // Wipe out any partially-computed value, to allow tracking that this
3661 // evaluation failed.
3669 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3672 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3673 OK &= EvaluateVarDecl(Info, VD);
3675 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3676 for (auto *BD : DD->bindings())
3677 if (auto *VD = BD->getHoldingVar())
3678 OK &= EvaluateDecl(Info, VD);
3684 /// Evaluate a condition (either a variable declaration or an expression).
3685 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3686 const Expr *Cond, bool &Result) {
3687 FullExpressionRAII Scope(Info);
3688 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3690 return EvaluateAsBooleanCondition(Cond, Result, Info);
3694 /// \brief A location where the result (returned value) of evaluating a
3695 /// statement should be stored.
3697 /// The APValue that should be filled in with the returned value.
3699 /// The location containing the result, if any (used to support RVO).
3704 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3706 const SwitchCase *SC = nullptr);
3708 /// Evaluate the body of a loop, and translate the result as appropriate.
3709 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3711 const SwitchCase *Case = nullptr) {
3712 BlockScopeRAII Scope(Info);
3713 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3715 return ESR_Succeeded;
3718 return ESR_Continue;
3721 case ESR_CaseNotFound:
3724 llvm_unreachable("Invalid EvalStmtResult!");
3727 /// Evaluate a switch statement.
3728 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3729 const SwitchStmt *SS) {
3730 BlockScopeRAII Scope(Info);
3732 // Evaluate the switch condition.
3735 FullExpressionRAII Scope(Info);
3736 if (const Stmt *Init = SS->getInit()) {
3737 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3738 if (ESR != ESR_Succeeded)
3741 if (SS->getConditionVariable() &&
3742 !EvaluateDecl(Info, SS->getConditionVariable()))
3744 if (!EvaluateInteger(SS->getCond(), Value, Info))
3748 // Find the switch case corresponding to the value of the condition.
3749 // FIXME: Cache this lookup.
3750 const SwitchCase *Found = nullptr;
3751 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3752 SC = SC->getNextSwitchCase()) {
3753 if (isa<DefaultStmt>(SC)) {
3758 const CaseStmt *CS = cast<CaseStmt>(SC);
3759 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3760 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3762 if (LHS <= Value && Value <= RHS) {
3769 return ESR_Succeeded;
3771 // Search the switch body for the switch case and evaluate it from there.
3772 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3774 return ESR_Succeeded;
3780 case ESR_CaseNotFound:
3781 // This can only happen if the switch case is nested within a statement
3782 // expression. We have no intention of supporting that.
3783 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3786 llvm_unreachable("Invalid EvalStmtResult!");
3789 // Evaluate a statement.
3790 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3791 const Stmt *S, const SwitchCase *Case) {
3792 if (!Info.nextStep(S))
3795 // If we're hunting down a 'case' or 'default' label, recurse through
3796 // substatements until we hit the label.
3798 // FIXME: We don't start the lifetime of objects whose initialization we
3799 // jump over. However, such objects must be of class type with a trivial
3800 // default constructor that initialize all subobjects, so must be empty,
3801 // so this almost never matters.
3802 switch (S->getStmtClass()) {
3803 case Stmt::CompoundStmtClass:
3804 // FIXME: Precompute which substatement of a compound statement we
3805 // would jump to, and go straight there rather than performing a
3806 // linear scan each time.
3807 case Stmt::LabelStmtClass:
3808 case Stmt::AttributedStmtClass:
3809 case Stmt::DoStmtClass:
3812 case Stmt::CaseStmtClass:
3813 case Stmt::DefaultStmtClass:
3818 case Stmt::IfStmtClass: {
3819 // FIXME: Precompute which side of an 'if' we would jump to, and go
3820 // straight there rather than scanning both sides.
3821 const IfStmt *IS = cast<IfStmt>(S);
3823 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3824 // preceded by our switch label.
3825 BlockScopeRAII Scope(Info);
3827 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3828 if (ESR != ESR_CaseNotFound || !IS->getElse())
3830 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3833 case Stmt::WhileStmtClass: {
3834 EvalStmtResult ESR =
3835 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3836 if (ESR != ESR_Continue)
3841 case Stmt::ForStmtClass: {
3842 const ForStmt *FS = cast<ForStmt>(S);
3843 EvalStmtResult ESR =
3844 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3845 if (ESR != ESR_Continue)
3848 FullExpressionRAII IncScope(Info);
3849 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3855 case Stmt::DeclStmtClass:
3856 // FIXME: If the variable has initialization that can't be jumped over,
3857 // bail out of any immediately-surrounding compound-statement too.
3859 return ESR_CaseNotFound;
3863 switch (S->getStmtClass()) {
3865 if (const Expr *E = dyn_cast<Expr>(S)) {
3866 // Don't bother evaluating beyond an expression-statement which couldn't
3868 FullExpressionRAII Scope(Info);
3869 if (!EvaluateIgnoredValue(Info, E))
3871 return ESR_Succeeded;
3874 Info.FFDiag(S->getLocStart());
3877 case Stmt::NullStmtClass:
3878 return ESR_Succeeded;
3880 case Stmt::DeclStmtClass: {
3881 const DeclStmt *DS = cast<DeclStmt>(S);
3882 for (const auto *DclIt : DS->decls()) {
3883 // Each declaration initialization is its own full-expression.
3884 // FIXME: This isn't quite right; if we're performing aggregate
3885 // initialization, each braced subexpression is its own full-expression.
3886 FullExpressionRAII Scope(Info);
3887 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3890 return ESR_Succeeded;
3893 case Stmt::ReturnStmtClass: {
3894 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3895 FullExpressionRAII Scope(Info);
3898 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3899 : Evaluate(Result.Value, Info, RetExpr)))
3901 return ESR_Returned;
3904 case Stmt::CompoundStmtClass: {
3905 BlockScopeRAII Scope(Info);
3907 const CompoundStmt *CS = cast<CompoundStmt>(S);
3908 for (const auto *BI : CS->body()) {
3909 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3910 if (ESR == ESR_Succeeded)
3912 else if (ESR != ESR_CaseNotFound)
3915 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3918 case Stmt::IfStmtClass: {
3919 const IfStmt *IS = cast<IfStmt>(S);
3921 // Evaluate the condition, as either a var decl or as an expression.
3922 BlockScopeRAII Scope(Info);
3923 if (const Stmt *Init = IS->getInit()) {
3924 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3925 if (ESR != ESR_Succeeded)
3929 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3932 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3933 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3934 if (ESR != ESR_Succeeded)
3937 return ESR_Succeeded;
3940 case Stmt::WhileStmtClass: {
3941 const WhileStmt *WS = cast<WhileStmt>(S);
3943 BlockScopeRAII Scope(Info);
3945 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3951 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3952 if (ESR != ESR_Continue)
3955 return ESR_Succeeded;
3958 case Stmt::DoStmtClass: {
3959 const DoStmt *DS = cast<DoStmt>(S);
3962 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3963 if (ESR != ESR_Continue)
3967 FullExpressionRAII CondScope(Info);
3968 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3971 return ESR_Succeeded;
3974 case Stmt::ForStmtClass: {
3975 const ForStmt *FS = cast<ForStmt>(S);
3976 BlockScopeRAII Scope(Info);
3977 if (FS->getInit()) {
3978 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3979 if (ESR != ESR_Succeeded)
3983 BlockScopeRAII Scope(Info);
3984 bool Continue = true;
3985 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3986 FS->getCond(), Continue))
3991 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3992 if (ESR != ESR_Continue)
3996 FullExpressionRAII IncScope(Info);
3997 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4001 return ESR_Succeeded;
4004 case Stmt::CXXForRangeStmtClass: {
4005 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4006 BlockScopeRAII Scope(Info);
4008 // Initialize the __range variable.
4009 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4010 if (ESR != ESR_Succeeded)
4013 // Create the __begin and __end iterators.
4014 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4015 if (ESR != ESR_Succeeded)
4017 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4018 if (ESR != ESR_Succeeded)
4022 // Condition: __begin != __end.
4024 bool Continue = true;
4025 FullExpressionRAII CondExpr(Info);
4026 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4032 // User's variable declaration, initialized by *__begin.
4033 BlockScopeRAII InnerScope(Info);
4034 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4035 if (ESR != ESR_Succeeded)
4039 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4040 if (ESR != ESR_Continue)
4043 // Increment: ++__begin
4044 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4048 return ESR_Succeeded;
4051 case Stmt::SwitchStmtClass:
4052 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4054 case Stmt::ContinueStmtClass:
4055 return ESR_Continue;
4057 case Stmt::BreakStmtClass:
4060 case Stmt::LabelStmtClass:
4061 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4063 case Stmt::AttributedStmtClass:
4064 // As a general principle, C++11 attributes can be ignored without
4065 // any semantic impact.
4066 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4069 case Stmt::CaseStmtClass:
4070 case Stmt::DefaultStmtClass:
4071 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4075 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4076 /// default constructor. If so, we'll fold it whether or not it's marked as
4077 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4078 /// so we need special handling.
4079 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4080 const CXXConstructorDecl *CD,
4081 bool IsValueInitialization) {
4082 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4085 // Value-initialization does not call a trivial default constructor, so such a
4086 // call is a core constant expression whether or not the constructor is
4088 if (!CD->isConstexpr() && !IsValueInitialization) {
4089 if (Info.getLangOpts().CPlusPlus11) {
4090 // FIXME: If DiagDecl is an implicitly-declared special member function,
4091 // we should be much more explicit about why it's not constexpr.
4092 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4093 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4094 Info.Note(CD->getLocation(), diag::note_declared_at);
4096 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4102 /// CheckConstexprFunction - Check that a function can be called in a constant
4104 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4105 const FunctionDecl *Declaration,
4106 const FunctionDecl *Definition,
4108 // Potential constant expressions can contain calls to declared, but not yet
4109 // defined, constexpr functions.
4110 if (Info.checkingPotentialConstantExpression() && !Definition &&
4111 Declaration->isConstexpr())
4114 // Bail out with no diagnostic if the function declaration itself is invalid.
4115 // We will have produced a relevant diagnostic while parsing it.
4116 if (Declaration->isInvalidDecl())
4119 // Can we evaluate this function call?
4120 if (Definition && Definition->isConstexpr() &&
4121 !Definition->isInvalidDecl() && Body)
4124 if (Info.getLangOpts().CPlusPlus11) {
4125 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4127 // If this function is not constexpr because it is an inherited
4128 // non-constexpr constructor, diagnose that directly.
4129 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4130 if (CD && CD->isInheritingConstructor()) {
4131 auto *Inherited = CD->getInheritedConstructor().getConstructor();
4132 if (!Inherited->isConstexpr())
4133 DiagDecl = CD = Inherited;
4136 // FIXME: If DiagDecl is an implicitly-declared special member function
4137 // or an inheriting constructor, we should be much more explicit about why
4138 // it's not constexpr.
4139 if (CD && CD->isInheritingConstructor())
4140 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4141 << CD->getInheritedConstructor().getConstructor()->getParent();
4143 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4144 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4145 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4147 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4152 /// Determine if a class has any fields that might need to be copied by a
4153 /// trivial copy or move operation.
4154 static bool hasFields(const CXXRecordDecl *RD) {
4155 if (!RD || RD->isEmpty())
4157 for (auto *FD : RD->fields()) {
4158 if (FD->isUnnamedBitfield())
4162 for (auto &Base : RD->bases())
4163 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4169 typedef SmallVector<APValue, 8> ArgVector;
4172 /// EvaluateArgs - Evaluate the arguments to a function call.
4173 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4175 bool Success = true;
4176 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4178 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4179 // If we're checking for a potential constant expression, evaluate all
4180 // initializers even if some of them fail.
4181 if (!Info.noteFailure())
4189 /// Evaluate a function call.
4190 static bool HandleFunctionCall(SourceLocation CallLoc,
4191 const FunctionDecl *Callee, const LValue *This,
4192 ArrayRef<const Expr*> Args, const Stmt *Body,
4193 EvalInfo &Info, APValue &Result,
4194 const LValue *ResultSlot) {
4195 ArgVector ArgValues(Args.size());
4196 if (!EvaluateArgs(Args, ArgValues, Info))
4199 if (!Info.CheckCallLimit(CallLoc))
4202 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4204 // For a trivial copy or move assignment, perform an APValue copy. This is
4205 // essential for unions, where the operations performed by the assignment
4206 // operator cannot be represented as statements.
4208 // Skip this for non-union classes with no fields; in that case, the defaulted
4209 // copy/move does not actually read the object.
4210 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4211 if (MD && MD->isDefaulted() &&
4212 (MD->getParent()->isUnion() ||
4213 (MD->isTrivial() && hasFields(MD->getParent())))) {
4215 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4217 RHS.setFrom(Info.Ctx, ArgValues[0]);
4219 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4222 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4225 This->moveInto(Result);
4227 } else if (MD && isLambdaCallOperator(MD)) {
4228 // We're in a lambda; determine the lambda capture field maps.
4229 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4230 Frame.LambdaThisCaptureField);
4233 StmtResult Ret = {Result, ResultSlot};
4234 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4235 if (ESR == ESR_Succeeded) {
4236 if (Callee->getReturnType()->isVoidType())
4238 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4240 return ESR == ESR_Returned;
4243 /// Evaluate a constructor call.
4244 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4246 const CXXConstructorDecl *Definition,
4247 EvalInfo &Info, APValue &Result) {
4248 SourceLocation CallLoc = E->getExprLoc();
4249 if (!Info.CheckCallLimit(CallLoc))
4252 const CXXRecordDecl *RD = Definition->getParent();
4253 if (RD->getNumVBases()) {
4254 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4258 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4260 // FIXME: Creating an APValue just to hold a nonexistent return value is
4263 StmtResult Ret = {RetVal, nullptr};
4265 // If it's a delegating constructor, delegate.
4266 if (Definition->isDelegatingConstructor()) {
4267 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4269 FullExpressionRAII InitScope(Info);
4270 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4273 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4276 // For a trivial copy or move constructor, perform an APValue copy. This is
4277 // essential for unions (or classes with anonymous union members), where the
4278 // operations performed by the constructor cannot be represented by
4279 // ctor-initializers.
4281 // Skip this for empty non-union classes; we should not perform an
4282 // lvalue-to-rvalue conversion on them because their copy constructor does not
4283 // actually read them.
4284 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4285 (Definition->getParent()->isUnion() ||
4286 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4288 RHS.setFrom(Info.Ctx, ArgValues[0]);
4289 return handleLValueToRValueConversion(
4290 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4294 // Reserve space for the struct members.
4295 if (!RD->isUnion() && Result.isUninit())
4296 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4297 std::distance(RD->field_begin(), RD->field_end()));
4299 if (RD->isInvalidDecl()) return false;
4300 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4302 // A scope for temporaries lifetime-extended by reference members.
4303 BlockScopeRAII LifetimeExtendedScope(Info);
4305 bool Success = true;
4306 unsigned BasesSeen = 0;
4308 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4310 for (const auto *I : Definition->inits()) {
4311 LValue Subobject = This;
4312 APValue *Value = &Result;
4314 // Determine the subobject to initialize.
4315 FieldDecl *FD = nullptr;
4316 if (I->isBaseInitializer()) {
4317 QualType BaseType(I->getBaseClass(), 0);
4319 // Non-virtual base classes are initialized in the order in the class
4320 // definition. We have already checked for virtual base classes.
4321 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4322 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4323 "base class initializers not in expected order");
4326 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4327 BaseType->getAsCXXRecordDecl(), &Layout))
4329 Value = &Result.getStructBase(BasesSeen++);
4330 } else if ((FD = I->getMember())) {
4331 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4333 if (RD->isUnion()) {
4334 Result = APValue(FD);
4335 Value = &Result.getUnionValue();
4337 Value = &Result.getStructField(FD->getFieldIndex());
4339 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4340 // Walk the indirect field decl's chain to find the object to initialize,
4341 // and make sure we've initialized every step along it.
4342 for (auto *C : IFD->chain()) {
4343 FD = cast<FieldDecl>(C);
4344 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4345 // Switch the union field if it differs. This happens if we had
4346 // preceding zero-initialization, and we're now initializing a union
4347 // subobject other than the first.
4348 // FIXME: In this case, the values of the other subobjects are
4349 // specified, since zero-initialization sets all padding bits to zero.
4350 if (Value->isUninit() ||
4351 (Value->isUnion() && Value->getUnionField() != FD)) {
4353 *Value = APValue(FD);
4355 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4356 std::distance(CD->field_begin(), CD->field_end()));
4358 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4361 Value = &Value->getUnionValue();
4363 Value = &Value->getStructField(FD->getFieldIndex());
4366 llvm_unreachable("unknown base initializer kind");
4369 FullExpressionRAII InitScope(Info);
4370 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4371 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4373 // If we're checking for a potential constant expression, evaluate all
4374 // initializers even if some of them fail.
4375 if (!Info.noteFailure())
4382 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4385 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4386 ArrayRef<const Expr*> Args,
4387 const CXXConstructorDecl *Definition,
4388 EvalInfo &Info, APValue &Result) {
4389 ArgVector ArgValues(Args.size());
4390 if (!EvaluateArgs(Args, ArgValues, Info))
4393 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4397 //===----------------------------------------------------------------------===//
4398 // Generic Evaluation
4399 //===----------------------------------------------------------------------===//
4402 template <class Derived>
4403 class ExprEvaluatorBase
4404 : public ConstStmtVisitor<Derived, bool> {
4406 Derived &getDerived() { return static_cast<Derived&>(*this); }
4407 bool DerivedSuccess(const APValue &V, const Expr *E) {
4408 return getDerived().Success(V, E);
4410 bool DerivedZeroInitialization(const Expr *E) {
4411 return getDerived().ZeroInitialization(E);
4414 // Check whether a conditional operator with a non-constant condition is a
4415 // potential constant expression. If neither arm is a potential constant
4416 // expression, then the conditional operator is not either.
4417 template<typename ConditionalOperator>
4418 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4419 assert(Info.checkingPotentialConstantExpression());
4421 // Speculatively evaluate both arms.
4422 SmallVector<PartialDiagnosticAt, 8> Diag;
4424 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4425 StmtVisitorTy::Visit(E->getFalseExpr());
4431 SpeculativeEvaluationRAII Speculate(Info, &Diag);
4433 StmtVisitorTy::Visit(E->getTrueExpr());
4438 Error(E, diag::note_constexpr_conditional_never_const);
4442 template<typename ConditionalOperator>
4443 bool HandleConditionalOperator(const ConditionalOperator *E) {
4445 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4446 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4447 CheckPotentialConstantConditional(E);
4450 if (Info.noteFailure()) {
4451 StmtVisitorTy::Visit(E->getTrueExpr());
4452 StmtVisitorTy::Visit(E->getFalseExpr());
4457 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4458 return StmtVisitorTy::Visit(EvalExpr);
4463 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4464 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4466 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4467 return Info.CCEDiag(E, D);
4470 bool ZeroInitialization(const Expr *E) { return Error(E); }
4473 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4475 EvalInfo &getEvalInfo() { return Info; }
4477 /// Report an evaluation error. This should only be called when an error is
4478 /// first discovered. When propagating an error, just return false.
4479 bool Error(const Expr *E, diag::kind D) {
4483 bool Error(const Expr *E) {
4484 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4487 bool VisitStmt(const Stmt *) {
4488 llvm_unreachable("Expression evaluator should not be called on stmts");
4490 bool VisitExpr(const Expr *E) {
4494 bool VisitParenExpr(const ParenExpr *E)
4495 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4496 bool VisitUnaryExtension(const UnaryOperator *E)
4497 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4498 bool VisitUnaryPlus(const UnaryOperator *E)
4499 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4500 bool VisitChooseExpr(const ChooseExpr *E)
4501 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4502 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4503 { return StmtVisitorTy::Visit(E->getResultExpr()); }
4504 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4505 { return StmtVisitorTy::Visit(E->getReplacement()); }
4506 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4507 { return StmtVisitorTy::Visit(E->getExpr()); }
4508 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4509 // The initializer may not have been parsed yet, or might be erroneous.
4512 return StmtVisitorTy::Visit(E->getExpr());
4514 // We cannot create any objects for which cleanups are required, so there is
4515 // nothing to do here; all cleanups must come from unevaluated subexpressions.
4516 bool VisitExprWithCleanups(const ExprWithCleanups *E)
4517 { return StmtVisitorTy::Visit(E->getSubExpr()); }
4519 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4520 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4521 return static_cast<Derived*>(this)->VisitCastExpr(E);
4523 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4524 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4525 return static_cast<Derived*>(this)->VisitCastExpr(E);
4528 bool VisitBinaryOperator(const BinaryOperator *E) {
4529 switch (E->getOpcode()) {
4534 VisitIgnoredValue(E->getLHS());
4535 return StmtVisitorTy::Visit(E->getRHS());
4540 if (!HandleMemberPointerAccess(Info, E, Obj))
4543 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4545 return DerivedSuccess(Result, E);
4550 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4551 // Evaluate and cache the common expression. We treat it as a temporary,
4552 // even though it's not quite the same thing.
4553 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4554 Info, E->getCommon()))
4557 return HandleConditionalOperator(E);
4560 bool VisitConditionalOperator(const ConditionalOperator *E) {
4561 bool IsBcpCall = false;
4562 // If the condition (ignoring parens) is a __builtin_constant_p call,
4563 // the result is a constant expression if it can be folded without
4564 // side-effects. This is an important GNU extension. See GCC PR38377
4566 if (const CallExpr *CallCE =
4567 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4568 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4571 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4572 // constant expression; we can't check whether it's potentially foldable.
4573 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4576 FoldConstant Fold(Info, IsBcpCall);
4577 if (!HandleConditionalOperator(E)) {
4578 Fold.keepDiagnostics();
4585 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4586 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4587 return DerivedSuccess(*Value, E);
4589 const Expr *Source = E->getSourceExpr();
4592 if (Source == E) { // sanity checking.
4593 assert(0 && "OpaqueValueExpr recursively refers to itself");
4596 return StmtVisitorTy::Visit(Source);
4599 bool VisitCallExpr(const CallExpr *E) {
4601 if (!handleCallExpr(E, Result, nullptr))
4603 return DerivedSuccess(Result, E);
4606 bool handleCallExpr(const CallExpr *E, APValue &Result,
4607 const LValue *ResultSlot) {
4608 const Expr *Callee = E->getCallee()->IgnoreParens();
4609 QualType CalleeType = Callee->getType();
4611 const FunctionDecl *FD = nullptr;
4612 LValue *This = nullptr, ThisVal;
4613 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4614 bool HasQualifier = false;
4616 // Extract function decl and 'this' pointer from the callee.
4617 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4618 const ValueDecl *Member = nullptr;
4619 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4620 // Explicit bound member calls, such as x.f() or p->g();
4621 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4623 Member = ME->getMemberDecl();
4625 HasQualifier = ME->hasQualifier();
4626 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4627 // Indirect bound member calls ('.*' or '->*').
4628 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4629 if (!Member) return false;
4632 return Error(Callee);
4634 FD = dyn_cast<FunctionDecl>(Member);
4636 return Error(Callee);
4637 } else if (CalleeType->isFunctionPointerType()) {
4639 if (!EvaluatePointer(Callee, Call, Info))
4642 if (!Call.getLValueOffset().isZero())
4643 return Error(Callee);
4644 FD = dyn_cast_or_null<FunctionDecl>(
4645 Call.getLValueBase().dyn_cast<const ValueDecl*>());
4647 return Error(Callee);
4648 // Don't call function pointers which have been cast to some other type.
4649 // Per DR (no number yet), the caller and callee can differ in noexcept.
4650 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4651 CalleeType->getPointeeType(), FD->getType())) {
4655 // Overloaded operator calls to member functions are represented as normal
4656 // calls with '*this' as the first argument.
4657 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4658 if (MD && !MD->isStatic()) {
4659 // FIXME: When selecting an implicit conversion for an overloaded
4660 // operator delete, we sometimes try to evaluate calls to conversion
4661 // operators without a 'this' parameter!
4665 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4668 Args = Args.slice(1);
4669 } else if (MD && MD->isLambdaStaticInvoker()) {
4670 // Map the static invoker for the lambda back to the call operator.
4671 // Conveniently, we don't have to slice out the 'this' argument (as is
4672 // being done for the non-static case), since a static member function
4673 // doesn't have an implicit argument passed in.
4674 const CXXRecordDecl *ClosureClass = MD->getParent();
4676 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4677 "Number of captures must be zero for conversion to function-ptr");
4679 const CXXMethodDecl *LambdaCallOp =
4680 ClosureClass->getLambdaCallOperator();
4682 // Set 'FD', the function that will be called below, to the call
4683 // operator. If the closure object represents a generic lambda, find
4684 // the corresponding specialization of the call operator.
4686 if (ClosureClass->isGenericLambda()) {
4687 assert(MD->isFunctionTemplateSpecialization() &&
4688 "A generic lambda's static-invoker function must be a "
4689 "template specialization");
4690 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4691 FunctionTemplateDecl *CallOpTemplate =
4692 LambdaCallOp->getDescribedFunctionTemplate();
4693 void *InsertPos = nullptr;
4694 FunctionDecl *CorrespondingCallOpSpecialization =
4695 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4696 assert(CorrespondingCallOpSpecialization &&
4697 "We must always have a function call operator specialization "
4698 "that corresponds to our static invoker specialization");
4699 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4708 if (This && !This->checkSubobject(Info, E, CSK_This))
4711 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4712 // calls to such functions in constant expressions.
4713 if (This && !HasQualifier &&
4714 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4715 return Error(E, diag::note_constexpr_virtual_call);
4717 const FunctionDecl *Definition = nullptr;
4718 Stmt *Body = FD->getBody(Definition);
4720 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4721 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4722 Result, ResultSlot))
4728 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4729 return StmtVisitorTy::Visit(E->getInitializer());
4731 bool VisitInitListExpr(const InitListExpr *E) {
4732 if (E->getNumInits() == 0)
4733 return DerivedZeroInitialization(E);
4734 if (E->getNumInits() == 1)
4735 return StmtVisitorTy::Visit(E->getInit(0));
4738 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4739 return DerivedZeroInitialization(E);
4741 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4742 return DerivedZeroInitialization(E);
4744 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4745 return DerivedZeroInitialization(E);
4748 /// A member expression where the object is a prvalue is itself a prvalue.
4749 bool VisitMemberExpr(const MemberExpr *E) {
4750 assert(!E->isArrow() && "missing call to bound member function?");
4753 if (!Evaluate(Val, Info, E->getBase()))
4756 QualType BaseTy = E->getBase()->getType();
4758 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4759 if (!FD) return Error(E);
4760 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4761 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4762 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4764 CompleteObject Obj(&Val, BaseTy);
4765 SubobjectDesignator Designator(BaseTy);
4766 Designator.addDeclUnchecked(FD);
4769 return extractSubobject(Info, E, Obj, Designator, Result) &&
4770 DerivedSuccess(Result, E);
4773 bool VisitCastExpr(const CastExpr *E) {
4774 switch (E->getCastKind()) {
4778 case CK_AtomicToNonAtomic: {
4780 // This does not need to be done in place even for class/array types:
4781 // atomic-to-non-atomic conversion implies copying the object
4783 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4785 return DerivedSuccess(AtomicVal, E);
4789 case CK_UserDefinedConversion:
4790 return StmtVisitorTy::Visit(E->getSubExpr());
4792 case CK_LValueToRValue: {
4794 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4797 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4798 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4801 return DerivedSuccess(RVal, E);
4808 bool VisitUnaryPostInc(const UnaryOperator *UO) {
4809 return VisitUnaryPostIncDec(UO);
4811 bool VisitUnaryPostDec(const UnaryOperator *UO) {
4812 return VisitUnaryPostIncDec(UO);
4814 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4815 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4819 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4822 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4823 UO->isIncrementOp(), &RVal))
4825 return DerivedSuccess(RVal, UO);
4828 bool VisitStmtExpr(const StmtExpr *E) {
4829 // We will have checked the full-expressions inside the statement expression
4830 // when they were completed, and don't need to check them again now.
4831 if (Info.checkingForOverflow())
4834 BlockScopeRAII Scope(Info);
4835 const CompoundStmt *CS = E->getSubStmt();
4836 if (CS->body_empty())
4839 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4840 BE = CS->body_end();
4843 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4845 Info.FFDiag((*BI)->getLocStart(),
4846 diag::note_constexpr_stmt_expr_unsupported);
4849 return this->Visit(FinalExpr);
4852 APValue ReturnValue;
4853 StmtResult Result = { ReturnValue, nullptr };
4854 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4855 if (ESR != ESR_Succeeded) {
4856 // FIXME: If the statement-expression terminated due to 'return',
4857 // 'break', or 'continue', it would be nice to propagate that to
4858 // the outer statement evaluation rather than bailing out.
4859 if (ESR != ESR_Failed)
4860 Info.FFDiag((*BI)->getLocStart(),
4861 diag::note_constexpr_stmt_expr_unsupported);
4866 llvm_unreachable("Return from function from the loop above.");
4869 /// Visit a value which is evaluated, but whose value is ignored.
4870 void VisitIgnoredValue(const Expr *E) {
4871 EvaluateIgnoredValue(Info, E);
4874 /// Potentially visit a MemberExpr's base expression.
4875 void VisitIgnoredBaseExpression(const Expr *E) {
4876 // While MSVC doesn't evaluate the base expression, it does diagnose the
4877 // presence of side-effecting behavior.
4878 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4880 VisitIgnoredValue(E);
4886 //===----------------------------------------------------------------------===//
4887 // Common base class for lvalue and temporary evaluation.
4888 //===----------------------------------------------------------------------===//
4890 template<class Derived>
4891 class LValueExprEvaluatorBase
4892 : public ExprEvaluatorBase<Derived> {
4896 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4897 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4899 bool Success(APValue::LValueBase B) {
4904 bool evaluatePointer(const Expr *E, LValue &Result) {
4905 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4909 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4910 : ExprEvaluatorBaseTy(Info), Result(Result),
4911 InvalidBaseOK(InvalidBaseOK) {}
4913 bool Success(const APValue &V, const Expr *E) {
4914 Result.setFrom(this->Info.Ctx, V);
4918 bool VisitMemberExpr(const MemberExpr *E) {
4919 // Handle non-static data members.
4923 EvalOK = evaluatePointer(E->getBase(), Result);
4924 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4925 } else if (E->getBase()->isRValue()) {
4926 assert(E->getBase()->getType()->isRecordType());
4927 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4928 BaseTy = E->getBase()->getType();
4930 EvalOK = this->Visit(E->getBase());
4931 BaseTy = E->getBase()->getType();
4936 Result.setInvalid(E);
4940 const ValueDecl *MD = E->getMemberDecl();
4941 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4942 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4943 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4945 if (!HandleLValueMember(this->Info, E, Result, FD))
4947 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4948 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4951 return this->Error(E);
4953 if (MD->getType()->isReferenceType()) {
4955 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4958 return Success(RefValue, E);
4963 bool VisitBinaryOperator(const BinaryOperator *E) {
4964 switch (E->getOpcode()) {
4966 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4970 return HandleMemberPointerAccess(this->Info, E, Result);
4974 bool VisitCastExpr(const CastExpr *E) {
4975 switch (E->getCastKind()) {
4977 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4979 case CK_DerivedToBase:
4980 case CK_UncheckedDerivedToBase:
4981 if (!this->Visit(E->getSubExpr()))
4984 // Now figure out the necessary offset to add to the base LV to get from
4985 // the derived class to the base class.
4986 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4993 //===----------------------------------------------------------------------===//
4994 // LValue Evaluation
4996 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4997 // function designators (in C), decl references to void objects (in C), and
4998 // temporaries (if building with -Wno-address-of-temporary).
5000 // LValue evaluation produces values comprising a base expression of one of the
5006 // * CompoundLiteralExpr in C (and in global scope in C++)
5010 // * ObjCStringLiteralExpr
5014 // * CallExpr for a MakeStringConstant builtin
5015 // - Locals and temporaries
5016 // * MaterializeTemporaryExpr
5017 // * Any Expr, with a CallIndex indicating the function in which the temporary
5018 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5019 // from the AST (FIXME).
5020 // * A MaterializeTemporaryExpr that has static storage duration, with no
5021 // CallIndex, for a lifetime-extended temporary.
5022 // plus an offset in bytes.
5023 //===----------------------------------------------------------------------===//
5025 class LValueExprEvaluator
5026 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5028 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5029 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5031 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5032 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5034 bool VisitDeclRefExpr(const DeclRefExpr *E);
5035 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5036 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5037 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5038 bool VisitMemberExpr(const MemberExpr *E);
5039 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5040 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5041 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5042 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5043 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5044 bool VisitUnaryDeref(const UnaryOperator *E);
5045 bool VisitUnaryReal(const UnaryOperator *E);
5046 bool VisitUnaryImag(const UnaryOperator *E);
5047 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5048 return VisitUnaryPreIncDec(UO);
5050 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5051 return VisitUnaryPreIncDec(UO);
5053 bool VisitBinAssign(const BinaryOperator *BO);
5054 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5056 bool VisitCastExpr(const CastExpr *E) {
5057 switch (E->getCastKind()) {
5059 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5061 case CK_LValueBitCast:
5062 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5063 if (!Visit(E->getSubExpr()))
5065 Result.Designator.setInvalid();
5068 case CK_BaseToDerived:
5069 if (!Visit(E->getSubExpr()))
5071 return HandleBaseToDerivedCast(Info, E, Result);
5075 } // end anonymous namespace
5077 /// Evaluate an expression as an lvalue. This can be legitimately called on
5078 /// expressions which are not glvalues, in three cases:
5079 /// * function designators in C, and
5080 /// * "extern void" objects
5081 /// * @selector() expressions in Objective-C
5082 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5083 bool InvalidBaseOK) {
5084 assert(E->isGLValue() || E->getType()->isFunctionType() ||
5085 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5086 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5089 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5090 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5092 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5093 return VisitVarDecl(E, VD);
5094 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5095 return Visit(BD->getBinding());
5100 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5102 // If we are within a lambda's call operator, check whether the 'VD' referred
5103 // to within 'E' actually represents a lambda-capture that maps to a
5104 // data-member/field within the closure object, and if so, evaluate to the
5105 // field or what the field refers to.
5106 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5107 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5108 if (Info.checkingPotentialConstantExpression())
5110 // Start with 'Result' referring to the complete closure object...
5111 Result = *Info.CurrentCall->This;
5112 // ... then update it to refer to the field of the closure object
5113 // that represents the capture.
5114 if (!HandleLValueMember(Info, E, Result, FD))
5116 // And if the field is of reference type, update 'Result' to refer to what
5117 // the field refers to.
5118 if (FD->getType()->isReferenceType()) {
5120 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5123 Result.setFrom(Info.Ctx, RVal);
5128 CallStackFrame *Frame = nullptr;
5129 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5130 // Only if a local variable was declared in the function currently being
5131 // evaluated, do we expect to be able to find its value in the current
5132 // frame. (Otherwise it was likely declared in an enclosing context and
5133 // could either have a valid evaluatable value (for e.g. a constexpr
5134 // variable) or be ill-formed (and trigger an appropriate evaluation
5136 if (Info.CurrentCall->Callee &&
5137 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5138 Frame = Info.CurrentCall;
5142 if (!VD->getType()->isReferenceType()) {
5144 Result.set(VD, Frame->Index);
5151 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5153 if (V->isUninit()) {
5154 if (!Info.checkingPotentialConstantExpression())
5155 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5158 return Success(*V, E);
5161 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5162 const MaterializeTemporaryExpr *E) {
5163 // Walk through the expression to find the materialized temporary itself.
5164 SmallVector<const Expr *, 2> CommaLHSs;
5165 SmallVector<SubobjectAdjustment, 2> Adjustments;
5166 const Expr *Inner = E->GetTemporaryExpr()->
5167 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5169 // If we passed any comma operators, evaluate their LHSs.
5170 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5171 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5174 // A materialized temporary with static storage duration can appear within the
5175 // result of a constant expression evaluation, so we need to preserve its
5176 // value for use outside this evaluation.
5178 if (E->getStorageDuration() == SD_Static) {
5179 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5183 Value = &Info.CurrentCall->
5184 createTemporary(E, E->getStorageDuration() == SD_Automatic);
5185 Result.set(E, Info.CurrentCall->Index);
5188 QualType Type = Inner->getType();
5190 // Materialize the temporary itself.
5191 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5192 (E->getStorageDuration() == SD_Static &&
5193 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5198 // Adjust our lvalue to refer to the desired subobject.
5199 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5201 switch (Adjustments[I].Kind) {
5202 case SubobjectAdjustment::DerivedToBaseAdjustment:
5203 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5206 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5209 case SubobjectAdjustment::FieldAdjustment:
5210 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5212 Type = Adjustments[I].Field->getType();
5215 case SubobjectAdjustment::MemberPointerAdjustment:
5216 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5217 Adjustments[I].Ptr.RHS))
5219 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5228 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5229 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5230 "lvalue compound literal in c++?");
5231 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5232 // only see this when folding in C, so there's no standard to follow here.
5236 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5237 if (!E->isPotentiallyEvaluated())
5240 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5241 << E->getExprOperand()->getType()
5242 << E->getExprOperand()->getSourceRange();
5246 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5250 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5251 // Handle static data members.
5252 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5253 VisitIgnoredBaseExpression(E->getBase());
5254 return VisitVarDecl(E, VD);
5257 // Handle static member functions.
5258 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5259 if (MD->isStatic()) {
5260 VisitIgnoredBaseExpression(E->getBase());
5265 // Handle non-static data members.
5266 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5269 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5270 // FIXME: Deal with vectors as array subscript bases.
5271 if (E->getBase()->getType()->isVectorType())
5274 bool Success = true;
5275 if (!evaluatePointer(E->getBase(), Result)) {
5276 if (!Info.noteFailure())
5282 if (!EvaluateInteger(E->getIdx(), Index, Info))
5286 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5289 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5290 return evaluatePointer(E->getSubExpr(), Result);
5293 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5294 if (!Visit(E->getSubExpr()))
5296 // __real is a no-op on scalar lvalues.
5297 if (E->getSubExpr()->getType()->isAnyComplexType())
5298 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5302 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5303 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5304 "lvalue __imag__ on scalar?");
5305 if (!Visit(E->getSubExpr()))
5307 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5311 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5312 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5315 if (!this->Visit(UO->getSubExpr()))
5318 return handleIncDec(
5319 this->Info, UO, Result, UO->getSubExpr()->getType(),
5320 UO->isIncrementOp(), nullptr);
5323 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5324 const CompoundAssignOperator *CAO) {
5325 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5330 // The overall lvalue result is the result of evaluating the LHS.
5331 if (!this->Visit(CAO->getLHS())) {
5332 if (Info.noteFailure())
5333 Evaluate(RHS, this->Info, CAO->getRHS());
5337 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5340 return handleCompoundAssignment(
5342 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5343 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5346 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5347 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5352 if (!this->Visit(E->getLHS())) {
5353 if (Info.noteFailure())
5354 Evaluate(NewVal, this->Info, E->getRHS());
5358 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5361 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5365 //===----------------------------------------------------------------------===//
5366 // Pointer Evaluation
5367 //===----------------------------------------------------------------------===//
5369 /// \brief Attempts to compute the number of bytes available at the pointer
5370 /// returned by a function with the alloc_size attribute. Returns true if we
5371 /// were successful. Places an unsigned number into `Result`.
5373 /// This expects the given CallExpr to be a call to a function with an
5374 /// alloc_size attribute.
5375 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5376 const CallExpr *Call,
5377 llvm::APInt &Result) {
5378 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5380 // alloc_size args are 1-indexed, 0 means not present.
5381 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5382 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5383 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5384 if (Call->getNumArgs() <= SizeArgNo)
5387 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5388 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5390 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5392 Into = Into.zextOrSelf(BitsInSizeT);
5397 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5400 if (!AllocSize->getNumElemsParam()) {
5401 Result = std::move(SizeOfElem);
5405 APSInt NumberOfElems;
5406 // Argument numbers start at 1
5407 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5408 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5412 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5416 Result = std::move(BytesAvailable);
5420 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5422 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5424 llvm::APInt &Result) {
5425 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5426 "Can't get the size of a non alloc_size function");
5427 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5428 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5429 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5432 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5433 /// a function with the alloc_size attribute. If it was possible to do so, this
5434 /// function will return true, make Result's Base point to said function call,
5435 /// and mark Result's Base as invalid.
5436 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5441 // Because we do no form of static analysis, we only support const variables.
5443 // Additionally, we can't support parameters, nor can we support static
5444 // variables (in the latter case, use-before-assign isn't UB; in the former,
5445 // we have no clue what they'll be assigned to).
5447 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5448 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5451 const Expr *Init = VD->getAnyInitializer();
5455 const Expr *E = Init->IgnoreParens();
5456 if (!tryUnwrapAllocSizeCall(E))
5459 // Store E instead of E unwrapped so that the type of the LValue's base is
5460 // what the user wanted.
5461 Result.setInvalid(E);
5463 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5464 Result.addUnsizedArray(Info, Pointee);
5469 class PointerExprEvaluator
5470 : public ExprEvaluatorBase<PointerExprEvaluator> {
5474 bool Success(const Expr *E) {
5479 bool evaluateLValue(const Expr *E, LValue &Result) {
5480 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5483 bool evaluatePointer(const Expr *E, LValue &Result) {
5484 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5487 bool visitNonBuiltinCallExpr(const CallExpr *E);
5490 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5491 : ExprEvaluatorBaseTy(info), Result(Result),
5492 InvalidBaseOK(InvalidBaseOK) {}
5494 bool Success(const APValue &V, const Expr *E) {
5495 Result.setFrom(Info.Ctx, V);
5498 bool ZeroInitialization(const Expr *E) {
5499 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5500 Result.setNull(E->getType(), TargetVal);
5504 bool VisitBinaryOperator(const BinaryOperator *E);
5505 bool VisitCastExpr(const CastExpr* E);
5506 bool VisitUnaryAddrOf(const UnaryOperator *E);
5507 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5508 { return Success(E); }
5509 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5510 if (Info.noteFailure())
5511 EvaluateIgnoredValue(Info, E->getSubExpr());
5514 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5515 { return Success(E); }
5516 bool VisitCallExpr(const CallExpr *E);
5517 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5518 bool VisitBlockExpr(const BlockExpr *E) {
5519 if (!E->getBlockDecl()->hasCaptures())
5523 bool VisitCXXThisExpr(const CXXThisExpr *E) {
5524 // Can't look at 'this' when checking a potential constant expression.
5525 if (Info.checkingPotentialConstantExpression())
5527 if (!Info.CurrentCall->This) {
5528 if (Info.getLangOpts().CPlusPlus11)
5529 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5534 Result = *Info.CurrentCall->This;
5535 // If we are inside a lambda's call operator, the 'this' expression refers
5536 // to the enclosing '*this' object (either by value or reference) which is
5537 // either copied into the closure object's field that represents the '*this'
5538 // or refers to '*this'.
5539 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5540 // Update 'Result' to refer to the data member/field of the closure object
5541 // that represents the '*this' capture.
5542 if (!HandleLValueMember(Info, E, Result,
5543 Info.CurrentCall->LambdaThisCaptureField))
5545 // If we captured '*this' by reference, replace the field with its referent.
5546 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5547 ->isPointerType()) {
5549 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5553 Result.setFrom(Info.Ctx, RVal);
5559 // FIXME: Missing: @protocol, @selector
5561 } // end anonymous namespace
5563 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5564 bool InvalidBaseOK) {
5565 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5566 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5569 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5570 if (E->getOpcode() != BO_Add &&
5571 E->getOpcode() != BO_Sub)
5572 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5574 const Expr *PExp = E->getLHS();
5575 const Expr *IExp = E->getRHS();
5576 if (IExp->getType()->isPointerType())
5577 std::swap(PExp, IExp);
5579 bool EvalPtrOK = evaluatePointer(PExp, Result);
5580 if (!EvalPtrOK && !Info.noteFailure())
5583 llvm::APSInt Offset;
5584 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5587 if (E->getOpcode() == BO_Sub)
5588 negateAsSigned(Offset);
5590 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5591 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5594 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5595 return evaluateLValue(E->getSubExpr(), Result);
5598 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5599 const Expr* SubExpr = E->getSubExpr();
5601 switch (E->getCastKind()) {
5606 case CK_CPointerToObjCPointerCast:
5607 case CK_BlockPointerToObjCPointerCast:
5608 case CK_AnyPointerToBlockPointerCast:
5609 case CK_AddressSpaceConversion:
5610 if (!Visit(SubExpr))
5612 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5613 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5614 // also static_casts, but we disallow them as a resolution to DR1312.
5615 if (!E->getType()->isVoidPointerType()) {
5616 Result.Designator.setInvalid();
5617 if (SubExpr->getType()->isVoidPointerType())
5618 CCEDiag(E, diag::note_constexpr_invalid_cast)
5619 << 3 << SubExpr->getType();
5621 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5623 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5624 ZeroInitialization(E);
5627 case CK_DerivedToBase:
5628 case CK_UncheckedDerivedToBase:
5629 if (!evaluatePointer(E->getSubExpr(), Result))
5631 if (!Result.Base && Result.Offset.isZero())
5634 // Now figure out the necessary offset to add to the base LV to get from
5635 // the derived class to the base class.
5636 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5637 castAs<PointerType>()->getPointeeType(),
5640 case CK_BaseToDerived:
5641 if (!Visit(E->getSubExpr()))
5643 if (!Result.Base && Result.Offset.isZero())
5645 return HandleBaseToDerivedCast(Info, E, Result);
5647 case CK_NullToPointer:
5648 VisitIgnoredValue(E->getSubExpr());
5649 return ZeroInitialization(E);
5651 case CK_IntegralToPointer: {
5652 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5655 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5658 if (Value.isInt()) {
5659 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5660 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5661 Result.Base = (Expr*)nullptr;
5662 Result.InvalidBase = false;
5663 Result.Offset = CharUnits::fromQuantity(N);
5664 Result.CallIndex = 0;
5665 Result.Designator.setInvalid();
5666 Result.IsNullPtr = false;
5669 // Cast is of an lvalue, no need to change value.
5670 Result.setFrom(Info.Ctx, Value);
5674 case CK_ArrayToPointerDecay:
5675 if (SubExpr->isGLValue()) {
5676 if (!evaluateLValue(SubExpr, Result))
5679 Result.set(SubExpr, Info.CurrentCall->Index);
5680 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5681 Info, Result, SubExpr))
5684 // The result is a pointer to the first element of the array.
5685 if (const ConstantArrayType *CAT
5686 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5687 Result.addArray(Info, E, CAT);
5689 Result.Designator.setInvalid();
5692 case CK_FunctionToPointerDecay:
5693 return evaluateLValue(SubExpr, Result);
5695 case CK_LValueToRValue: {
5697 if (!evaluateLValue(E->getSubExpr(), LVal))
5701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5702 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5704 return InvalidBaseOK &&
5705 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5706 return Success(RVal, E);
5710 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5713 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5714 // C++ [expr.alignof]p3:
5715 // When alignof is applied to a reference type, the result is the
5716 // alignment of the referenced type.
5717 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5718 T = Ref->getPointeeType();
5720 // __alignof is defined to return the preferred alignment.
5721 if (T.getQualifiers().hasUnaligned())
5722 return CharUnits::One();
5723 return Info.Ctx.toCharUnitsFromBits(
5724 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5727 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5728 E = E->IgnoreParens();
5730 // The kinds of expressions that we have special-case logic here for
5731 // should be kept up to date with the special checks for those
5732 // expressions in Sema.
5734 // alignof decl is always accepted, even if it doesn't make sense: we default
5735 // to 1 in those cases.
5736 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5737 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5738 /*RefAsPointee*/true);
5740 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5741 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5742 /*RefAsPointee*/true);
5744 return GetAlignOfType(Info, E->getType());
5747 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5748 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5749 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5752 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5755 Result.setInvalid(E);
5756 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5757 Result.addUnsizedArray(Info, PointeeTy);
5761 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5762 if (IsStringLiteralCall(E))
5765 if (unsigned BuiltinOp = E->getBuiltinCallee())
5766 return VisitBuiltinCallExpr(E, BuiltinOp);
5768 return visitNonBuiltinCallExpr(E);
5771 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5772 unsigned BuiltinOp) {
5773 switch (BuiltinOp) {
5774 case Builtin::BI__builtin_addressof:
5775 return evaluateLValue(E->getArg(0), Result);
5776 case Builtin::BI__builtin_assume_aligned: {
5777 // We need to be very careful here because: if the pointer does not have the
5778 // asserted alignment, then the behavior is undefined, and undefined
5779 // behavior is non-constant.
5780 if (!evaluatePointer(E->getArg(0), Result))
5783 LValue OffsetResult(Result);
5785 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5787 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5789 if (E->getNumArgs() > 2) {
5791 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5794 int64_t AdditionalOffset = -Offset.getZExtValue();
5795 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5798 // If there is a base object, then it must have the correct alignment.
5799 if (OffsetResult.Base) {
5800 CharUnits BaseAlignment;
5801 if (const ValueDecl *VD =
5802 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5803 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5806 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5809 if (BaseAlignment < Align) {
5810 Result.Designator.setInvalid();
5811 // FIXME: Add support to Diagnostic for long / long long.
5812 CCEDiag(E->getArg(0),
5813 diag::note_constexpr_baa_insufficient_alignment) << 0
5814 << (unsigned)BaseAlignment.getQuantity()
5815 << (unsigned)Align.getQuantity();
5820 // The offset must also have the correct alignment.
5821 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5822 Result.Designator.setInvalid();
5825 ? CCEDiag(E->getArg(0),
5826 diag::note_constexpr_baa_insufficient_alignment) << 1
5827 : CCEDiag(E->getArg(0),
5828 diag::note_constexpr_baa_value_insufficient_alignment))
5829 << (int)OffsetResult.Offset.getQuantity()
5830 << (unsigned)Align.getQuantity();
5837 case Builtin::BIstrchr:
5838 case Builtin::BIwcschr:
5839 case Builtin::BImemchr:
5840 case Builtin::BIwmemchr:
5841 if (Info.getLangOpts().CPlusPlus11)
5842 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5843 << /*isConstexpr*/0 << /*isConstructor*/0
5844 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5846 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5848 case Builtin::BI__builtin_strchr:
5849 case Builtin::BI__builtin_wcschr:
5850 case Builtin::BI__builtin_memchr:
5851 case Builtin::BI__builtin_char_memchr:
5852 case Builtin::BI__builtin_wmemchr: {
5853 if (!Visit(E->getArg(0)))
5856 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5858 uint64_t MaxLength = uint64_t(-1);
5859 if (BuiltinOp != Builtin::BIstrchr &&
5860 BuiltinOp != Builtin::BIwcschr &&
5861 BuiltinOp != Builtin::BI__builtin_strchr &&
5862 BuiltinOp != Builtin::BI__builtin_wcschr) {
5864 if (!EvaluateInteger(E->getArg(2), N, Info))
5866 MaxLength = N.getExtValue();
5869 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5871 // Figure out what value we're actually looking for (after converting to
5872 // the corresponding unsigned type if necessary).
5873 uint64_t DesiredVal;
5874 bool StopAtNull = false;
5875 switch (BuiltinOp) {
5876 case Builtin::BIstrchr:
5877 case Builtin::BI__builtin_strchr:
5878 // strchr compares directly to the passed integer, and therefore
5879 // always fails if given an int that is not a char.
5880 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5881 E->getArg(1)->getType(),
5884 return ZeroInitialization(E);
5887 case Builtin::BImemchr:
5888 case Builtin::BI__builtin_memchr:
5889 case Builtin::BI__builtin_char_memchr:
5890 // memchr compares by converting both sides to unsigned char. That's also
5891 // correct for strchr if we get this far (to cope with plain char being
5892 // unsigned in the strchr case).
5893 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5896 case Builtin::BIwcschr:
5897 case Builtin::BI__builtin_wcschr:
5900 case Builtin::BIwmemchr:
5901 case Builtin::BI__builtin_wmemchr:
5902 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5903 DesiredVal = Desired.getZExtValue();
5907 for (; MaxLength; --MaxLength) {
5909 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5912 if (Char.getInt().getZExtValue() == DesiredVal)
5914 if (StopAtNull && !Char.getInt())
5916 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5919 // Not found: return nullptr.
5920 return ZeroInitialization(E);
5924 return visitNonBuiltinCallExpr(E);
5928 //===----------------------------------------------------------------------===//
5929 // Member Pointer Evaluation
5930 //===----------------------------------------------------------------------===//
5933 class MemberPointerExprEvaluator
5934 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5937 bool Success(const ValueDecl *D) {
5938 Result = MemberPtr(D);
5943 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5944 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5946 bool Success(const APValue &V, const Expr *E) {
5950 bool ZeroInitialization(const Expr *E) {
5951 return Success((const ValueDecl*)nullptr);
5954 bool VisitCastExpr(const CastExpr *E);
5955 bool VisitUnaryAddrOf(const UnaryOperator *E);
5957 } // end anonymous namespace
5959 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5961 assert(E->isRValue() && E->getType()->isMemberPointerType());
5962 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5965 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5966 switch (E->getCastKind()) {
5968 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5970 case CK_NullToMemberPointer:
5971 VisitIgnoredValue(E->getSubExpr());
5972 return ZeroInitialization(E);
5974 case CK_BaseToDerivedMemberPointer: {
5975 if (!Visit(E->getSubExpr()))
5977 if (E->path_empty())
5979 // Base-to-derived member pointer casts store the path in derived-to-base
5980 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5981 // the wrong end of the derived->base arc, so stagger the path by one class.
5982 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5983 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5984 PathI != PathE; ++PathI) {
5985 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5986 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5987 if (!Result.castToDerived(Derived))
5990 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5991 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5996 case CK_DerivedToBaseMemberPointer:
5997 if (!Visit(E->getSubExpr()))
5999 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6000 PathE = E->path_end(); PathI != PathE; ++PathI) {
6001 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6002 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6003 if (!Result.castToBase(Base))
6010 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6011 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6012 // member can be formed.
6013 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6016 //===----------------------------------------------------------------------===//
6017 // Record Evaluation
6018 //===----------------------------------------------------------------------===//
6021 class RecordExprEvaluator
6022 : public ExprEvaluatorBase<RecordExprEvaluator> {
6027 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6028 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6030 bool Success(const APValue &V, const Expr *E) {
6034 bool ZeroInitialization(const Expr *E) {
6035 return ZeroInitialization(E, E->getType());
6037 bool ZeroInitialization(const Expr *E, QualType T);
6039 bool VisitCallExpr(const CallExpr *E) {
6040 return handleCallExpr(E, Result, &This);
6042 bool VisitCastExpr(const CastExpr *E);
6043 bool VisitInitListExpr(const InitListExpr *E);
6044 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6045 return VisitCXXConstructExpr(E, E->getType());
6047 bool VisitLambdaExpr(const LambdaExpr *E);
6048 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6049 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6050 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6054 /// Perform zero-initialization on an object of non-union class type.
6055 /// C++11 [dcl.init]p5:
6056 /// To zero-initialize an object or reference of type T means:
6058 /// -- if T is a (possibly cv-qualified) non-union class type,
6059 /// each non-static data member and each base-class subobject is
6060 /// zero-initialized
6061 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6062 const RecordDecl *RD,
6063 const LValue &This, APValue &Result) {
6064 assert(!RD->isUnion() && "Expected non-union class type");
6065 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6066 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6067 std::distance(RD->field_begin(), RD->field_end()));
6069 if (RD->isInvalidDecl()) return false;
6070 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6074 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6075 End = CD->bases_end(); I != End; ++I, ++Index) {
6076 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6077 LValue Subobject = This;
6078 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6080 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6081 Result.getStructBase(Index)))
6086 for (const auto *I : RD->fields()) {
6087 // -- if T is a reference type, no initialization is performed.
6088 if (I->getType()->isReferenceType())
6091 LValue Subobject = This;
6092 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6095 ImplicitValueInitExpr VIE(I->getType());
6096 if (!EvaluateInPlace(
6097 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6104 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6105 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6106 if (RD->isInvalidDecl()) return false;
6107 if (RD->isUnion()) {
6108 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6109 // object's first non-static named data member is zero-initialized
6110 RecordDecl::field_iterator I = RD->field_begin();
6111 if (I == RD->field_end()) {
6112 Result = APValue((const FieldDecl*)nullptr);
6116 LValue Subobject = This;
6117 if (!HandleLValueMember(Info, E, Subobject, *I))
6119 Result = APValue(*I);
6120 ImplicitValueInitExpr VIE(I->getType());
6121 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6124 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6125 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6129 return HandleClassZeroInitialization(Info, E, RD, This, Result);
6132 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6133 switch (E->getCastKind()) {
6135 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6137 case CK_ConstructorConversion:
6138 return Visit(E->getSubExpr());
6140 case CK_DerivedToBase:
6141 case CK_UncheckedDerivedToBase: {
6142 APValue DerivedObject;
6143 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6145 if (!DerivedObject.isStruct())
6146 return Error(E->getSubExpr());
6148 // Derived-to-base rvalue conversion: just slice off the derived part.
6149 APValue *Value = &DerivedObject;
6150 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6151 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6152 PathE = E->path_end(); PathI != PathE; ++PathI) {
6153 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6154 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6155 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6164 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6165 if (E->isTransparent())
6166 return Visit(E->getInit(0));
6168 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6169 if (RD->isInvalidDecl()) return false;
6170 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6172 if (RD->isUnion()) {
6173 const FieldDecl *Field = E->getInitializedFieldInUnion();
6174 Result = APValue(Field);
6178 // If the initializer list for a union does not contain any elements, the
6179 // first element of the union is value-initialized.
6180 // FIXME: The element should be initialized from an initializer list.
6181 // Is this difference ever observable for initializer lists which
6183 ImplicitValueInitExpr VIE(Field->getType());
6184 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6186 LValue Subobject = This;
6187 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6190 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6191 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6192 isa<CXXDefaultInitExpr>(InitExpr));
6194 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6197 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6198 if (Result.isUninit())
6199 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6200 std::distance(RD->field_begin(), RD->field_end()));
6201 unsigned ElementNo = 0;
6202 bool Success = true;
6204 // Initialize base classes.
6206 for (const auto &Base : CXXRD->bases()) {
6207 assert(ElementNo < E->getNumInits() && "missing init for base class");
6208 const Expr *Init = E->getInit(ElementNo);
6210 LValue Subobject = This;
6211 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6214 APValue &FieldVal = Result.getStructBase(ElementNo);
6215 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6216 if (!Info.noteFailure())
6224 // Initialize members.
6225 for (const auto *Field : RD->fields()) {
6226 // Anonymous bit-fields are not considered members of the class for
6227 // purposes of aggregate initialization.
6228 if (Field->isUnnamedBitfield())
6231 LValue Subobject = This;
6233 bool HaveInit = ElementNo < E->getNumInits();
6235 // FIXME: Diagnostics here should point to the end of the initializer
6236 // list, not the start.
6237 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6238 Subobject, Field, &Layout))
6241 // Perform an implicit value-initialization for members beyond the end of
6242 // the initializer list.
6243 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6244 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6246 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6247 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6248 isa<CXXDefaultInitExpr>(Init));
6250 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6251 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6252 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6253 FieldVal, Field))) {
6254 if (!Info.noteFailure())
6263 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6265 // Note that E's type is not necessarily the type of our class here; we might
6266 // be initializing an array element instead.
6267 const CXXConstructorDecl *FD = E->getConstructor();
6268 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6270 bool ZeroInit = E->requiresZeroInitialization();
6271 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6272 // If we've already performed zero-initialization, we're already done.
6273 if (!Result.isUninit())
6276 // We can get here in two different ways:
6277 // 1) We're performing value-initialization, and should zero-initialize
6279 // 2) We're performing default-initialization of an object with a trivial
6280 // constexpr default constructor, in which case we should start the
6281 // lifetimes of all the base subobjects (there can be no data member
6282 // subobjects in this case) per [basic.life]p1.
6283 // Either way, ZeroInitialization is appropriate.
6284 return ZeroInitialization(E, T);
6287 const FunctionDecl *Definition = nullptr;
6288 auto Body = FD->getBody(Definition);
6290 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6293 // Avoid materializing a temporary for an elidable copy/move constructor.
6294 if (E->isElidable() && !ZeroInit)
6295 if (const MaterializeTemporaryExpr *ME
6296 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6297 return Visit(ME->GetTemporaryExpr());
6299 if (ZeroInit && !ZeroInitialization(E, T))
6302 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6303 return HandleConstructorCall(E, This, Args,
6304 cast<CXXConstructorDecl>(Definition), Info,
6308 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6309 const CXXInheritedCtorInitExpr *E) {
6310 if (!Info.CurrentCall) {
6311 assert(Info.checkingPotentialConstantExpression());
6315 const CXXConstructorDecl *FD = E->getConstructor();
6316 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6319 const FunctionDecl *Definition = nullptr;
6320 auto Body = FD->getBody(Definition);
6322 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6325 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6326 cast<CXXConstructorDecl>(Definition), Info,
6330 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6331 const CXXStdInitializerListExpr *E) {
6332 const ConstantArrayType *ArrayType =
6333 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6336 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6339 // Get a pointer to the first element of the array.
6340 Array.addArray(Info, E, ArrayType);
6342 // FIXME: Perform the checks on the field types in SemaInit.
6343 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6344 RecordDecl::field_iterator Field = Record->field_begin();
6345 if (Field == Record->field_end())
6349 if (!Field->getType()->isPointerType() ||
6350 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6351 ArrayType->getElementType()))
6354 // FIXME: What if the initializer_list type has base classes, etc?
6355 Result = APValue(APValue::UninitStruct(), 0, 2);
6356 Array.moveInto(Result.getStructField(0));
6358 if (++Field == Record->field_end())
6361 if (Field->getType()->isPointerType() &&
6362 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6363 ArrayType->getElementType())) {
6365 if (!HandleLValueArrayAdjustment(Info, E, Array,
6366 ArrayType->getElementType(),
6367 ArrayType->getSize().getZExtValue()))
6369 Array.moveInto(Result.getStructField(1));
6370 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6372 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6376 if (++Field != Record->field_end())
6382 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6383 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6384 if (ClosureClass->isInvalidDecl()) return false;
6386 if (Info.checkingPotentialConstantExpression()) return true;
6388 const size_t NumFields =
6389 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6391 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6392 E->capture_init_end()) &&
6393 "The number of lambda capture initializers should equal the number of "
6394 "fields within the closure type");
6396 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6397 // Iterate through all the lambda's closure object's fields and initialize
6399 auto *CaptureInitIt = E->capture_init_begin();
6400 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6401 bool Success = true;
6402 for (const auto *Field : ClosureClass->fields()) {
6403 assert(CaptureInitIt != E->capture_init_end());
6404 // Get the initializer for this field
6405 Expr *const CurFieldInit = *CaptureInitIt++;
6407 // If there is no initializer, either this is a VLA or an error has
6412 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6413 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6414 if (!Info.keepEvaluatingAfterFailure())
6423 static bool EvaluateRecord(const Expr *E, const LValue &This,
6424 APValue &Result, EvalInfo &Info) {
6425 assert(E->isRValue() && E->getType()->isRecordType() &&
6426 "can't evaluate expression as a record rvalue");
6427 return RecordExprEvaluator(Info, This, Result).Visit(E);
6430 //===----------------------------------------------------------------------===//
6431 // Temporary Evaluation
6433 // Temporaries are represented in the AST as rvalues, but generally behave like
6434 // lvalues. The full-object of which the temporary is a subobject is implicitly
6435 // materialized so that a reference can bind to it.
6436 //===----------------------------------------------------------------------===//
6438 class TemporaryExprEvaluator
6439 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6441 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6442 LValueExprEvaluatorBaseTy(Info, Result, false) {}
6444 /// Visit an expression which constructs the value of this temporary.
6445 bool VisitConstructExpr(const Expr *E) {
6446 Result.set(E, Info.CurrentCall->Index);
6447 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6451 bool VisitCastExpr(const CastExpr *E) {
6452 switch (E->getCastKind()) {
6454 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6456 case CK_ConstructorConversion:
6457 return VisitConstructExpr(E->getSubExpr());
6460 bool VisitInitListExpr(const InitListExpr *E) {
6461 return VisitConstructExpr(E);
6463 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6464 return VisitConstructExpr(E);
6466 bool VisitCallExpr(const CallExpr *E) {
6467 return VisitConstructExpr(E);
6469 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6470 return VisitConstructExpr(E);
6472 bool VisitLambdaExpr(const LambdaExpr *E) {
6473 return VisitConstructExpr(E);
6476 } // end anonymous namespace
6478 /// Evaluate an expression of record type as a temporary.
6479 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6480 assert(E->isRValue() && E->getType()->isRecordType());
6481 return TemporaryExprEvaluator(Info, Result).Visit(E);
6484 //===----------------------------------------------------------------------===//
6485 // Vector Evaluation
6486 //===----------------------------------------------------------------------===//
6489 class VectorExprEvaluator
6490 : public ExprEvaluatorBase<VectorExprEvaluator> {
6494 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6495 : ExprEvaluatorBaseTy(info), Result(Result) {}
6497 bool Success(ArrayRef<APValue> V, const Expr *E) {
6498 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6499 // FIXME: remove this APValue copy.
6500 Result = APValue(V.data(), V.size());
6503 bool Success(const APValue &V, const Expr *E) {
6504 assert(V.isVector());
6508 bool ZeroInitialization(const Expr *E);
6510 bool VisitUnaryReal(const UnaryOperator *E)
6511 { return Visit(E->getSubExpr()); }
6512 bool VisitCastExpr(const CastExpr* E);
6513 bool VisitInitListExpr(const InitListExpr *E);
6514 bool VisitUnaryImag(const UnaryOperator *E);
6515 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6516 // binary comparisons, binary and/or/xor,
6517 // shufflevector, ExtVectorElementExpr
6519 } // end anonymous namespace
6521 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6522 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6523 return VectorExprEvaluator(Info, Result).Visit(E);
6526 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6527 const VectorType *VTy = E->getType()->castAs<VectorType>();
6528 unsigned NElts = VTy->getNumElements();
6530 const Expr *SE = E->getSubExpr();
6531 QualType SETy = SE->getType();
6533 switch (E->getCastKind()) {
6534 case CK_VectorSplat: {
6535 APValue Val = APValue();
6536 if (SETy->isIntegerType()) {
6538 if (!EvaluateInteger(SE, IntResult, Info))
6540 Val = APValue(std::move(IntResult));
6541 } else if (SETy->isRealFloatingType()) {
6542 APFloat FloatResult(0.0);
6543 if (!EvaluateFloat(SE, FloatResult, Info))
6545 Val = APValue(std::move(FloatResult));
6550 // Splat and create vector APValue.
6551 SmallVector<APValue, 4> Elts(NElts, Val);
6552 return Success(Elts, E);
6555 // Evaluate the operand into an APInt we can extract from.
6556 llvm::APInt SValInt;
6557 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6559 // Extract the elements
6560 QualType EltTy = VTy->getElementType();
6561 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6562 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6563 SmallVector<APValue, 4> Elts;
6564 if (EltTy->isRealFloatingType()) {
6565 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6566 unsigned FloatEltSize = EltSize;
6567 if (&Sem == &APFloat::x87DoubleExtended())
6569 for (unsigned i = 0; i < NElts; i++) {
6572 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6574 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6575 Elts.push_back(APValue(APFloat(Sem, Elt)));
6577 } else if (EltTy->isIntegerType()) {
6578 for (unsigned i = 0; i < NElts; i++) {
6581 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6583 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6584 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6589 return Success(Elts, E);
6592 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6597 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6598 const VectorType *VT = E->getType()->castAs<VectorType>();
6599 unsigned NumInits = E->getNumInits();
6600 unsigned NumElements = VT->getNumElements();
6602 QualType EltTy = VT->getElementType();
6603 SmallVector<APValue, 4> Elements;
6605 // The number of initializers can be less than the number of
6606 // vector elements. For OpenCL, this can be due to nested vector
6607 // initialization. For GCC compatibility, missing trailing elements
6608 // should be initialized with zeroes.
6609 unsigned CountInits = 0, CountElts = 0;
6610 while (CountElts < NumElements) {
6611 // Handle nested vector initialization.
6612 if (CountInits < NumInits
6613 && E->getInit(CountInits)->getType()->isVectorType()) {
6615 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6617 unsigned vlen = v.getVectorLength();
6618 for (unsigned j = 0; j < vlen; j++)
6619 Elements.push_back(v.getVectorElt(j));
6621 } else if (EltTy->isIntegerType()) {
6622 llvm::APSInt sInt(32);
6623 if (CountInits < NumInits) {
6624 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6626 } else // trailing integer zero.
6627 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6628 Elements.push_back(APValue(sInt));
6631 llvm::APFloat f(0.0);
6632 if (CountInits < NumInits) {
6633 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6635 } else // trailing float zero.
6636 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6637 Elements.push_back(APValue(f));
6642 return Success(Elements, E);
6646 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6647 const VectorType *VT = E->getType()->getAs<VectorType>();
6648 QualType EltTy = VT->getElementType();
6649 APValue ZeroElement;
6650 if (EltTy->isIntegerType())
6651 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6654 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6656 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6657 return Success(Elements, E);
6660 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6661 VisitIgnoredValue(E->getSubExpr());
6662 return ZeroInitialization(E);
6665 //===----------------------------------------------------------------------===//
6667 //===----------------------------------------------------------------------===//
6670 class ArrayExprEvaluator
6671 : public ExprEvaluatorBase<ArrayExprEvaluator> {
6676 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6677 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6679 bool Success(const APValue &V, const Expr *E) {
6680 assert((V.isArray() || V.isLValue()) &&
6681 "expected array or string literal");
6686 bool ZeroInitialization(const Expr *E) {
6687 const ConstantArrayType *CAT =
6688 Info.Ctx.getAsConstantArrayType(E->getType());
6692 Result = APValue(APValue::UninitArray(), 0,
6693 CAT->getSize().getZExtValue());
6694 if (!Result.hasArrayFiller()) return true;
6696 // Zero-initialize all elements.
6697 LValue Subobject = This;
6698 Subobject.addArray(Info, E, CAT);
6699 ImplicitValueInitExpr VIE(CAT->getElementType());
6700 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6703 bool VisitCallExpr(const CallExpr *E) {
6704 return handleCallExpr(E, Result, &This);
6706 bool VisitInitListExpr(const InitListExpr *E);
6707 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6708 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6709 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6710 const LValue &Subobject,
6711 APValue *Value, QualType Type);
6713 } // end anonymous namespace
6715 static bool EvaluateArray(const Expr *E, const LValue &This,
6716 APValue &Result, EvalInfo &Info) {
6717 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6718 return ArrayExprEvaluator(Info, This, Result).Visit(E);
6721 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6722 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6726 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6727 // an appropriately-typed string literal enclosed in braces.
6728 if (E->isStringLiteralInit()) {
6730 if (!EvaluateLValue(E->getInit(0), LV, Info))
6734 return Success(Val, E);
6737 bool Success = true;
6739 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6740 "zero-initialized array shouldn't have any initialized elts");
6742 if (Result.isArray() && Result.hasArrayFiller())
6743 Filler = Result.getArrayFiller();
6745 unsigned NumEltsToInit = E->getNumInits();
6746 unsigned NumElts = CAT->getSize().getZExtValue();
6747 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6749 // If the initializer might depend on the array index, run it for each
6750 // array element. For now, just whitelist non-class value-initialization.
6751 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6752 NumEltsToInit = NumElts;
6754 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6756 // If the array was previously zero-initialized, preserve the
6757 // zero-initialized values.
6758 if (!Filler.isUninit()) {
6759 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6760 Result.getArrayInitializedElt(I) = Filler;
6761 if (Result.hasArrayFiller())
6762 Result.getArrayFiller() = Filler;
6765 LValue Subobject = This;
6766 Subobject.addArray(Info, E, CAT);
6767 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6769 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6770 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6771 Info, Subobject, Init) ||
6772 !HandleLValueArrayAdjustment(Info, Init, Subobject,
6773 CAT->getElementType(), 1)) {
6774 if (!Info.noteFailure())
6780 if (!Result.hasArrayFiller())
6783 // If we get here, we have a trivial filler, which we can just evaluate
6784 // once and splat over the rest of the array elements.
6785 assert(FillerExpr && "no array filler for incomplete init list");
6786 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6787 FillerExpr) && Success;
6790 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6791 if (E->getCommonExpr() &&
6792 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6793 Info, E->getCommonExpr()->getSourceExpr()))
6796 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6798 uint64_t Elements = CAT->getSize().getZExtValue();
6799 Result = APValue(APValue::UninitArray(), Elements, Elements);
6801 LValue Subobject = This;
6802 Subobject.addArray(Info, E, CAT);
6804 bool Success = true;
6805 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6806 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6807 Info, Subobject, E->getSubExpr()) ||
6808 !HandleLValueArrayAdjustment(Info, E, Subobject,
6809 CAT->getElementType(), 1)) {
6810 if (!Info.noteFailure())
6819 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6820 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6823 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6824 const LValue &Subobject,
6827 bool HadZeroInit = !Value->isUninit();
6829 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6830 unsigned N = CAT->getSize().getZExtValue();
6832 // Preserve the array filler if we had prior zero-initialization.
6834 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6837 *Value = APValue(APValue::UninitArray(), N, N);
6840 for (unsigned I = 0; I != N; ++I)
6841 Value->getArrayInitializedElt(I) = Filler;
6843 // Initialize the elements.
6844 LValue ArrayElt = Subobject;
6845 ArrayElt.addArray(Info, E, CAT);
6846 for (unsigned I = 0; I != N; ++I)
6847 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6848 CAT->getElementType()) ||
6849 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6850 CAT->getElementType(), 1))
6856 if (!Type->isRecordType())
6859 return RecordExprEvaluator(Info, Subobject, *Value)
6860 .VisitCXXConstructExpr(E, Type);
6863 //===----------------------------------------------------------------------===//
6864 // Integer Evaluation
6866 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6867 // types and back in constant folding. Integer values are thus represented
6868 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6869 //===----------------------------------------------------------------------===//
6872 class IntExprEvaluator
6873 : public ExprEvaluatorBase<IntExprEvaluator> {
6876 IntExprEvaluator(EvalInfo &info, APValue &result)
6877 : ExprEvaluatorBaseTy(info), Result(result) {}
6879 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6880 assert(E->getType()->isIntegralOrEnumerationType() &&
6881 "Invalid evaluation result.");
6882 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6883 "Invalid evaluation result.");
6884 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6885 "Invalid evaluation result.");
6886 Result = APValue(SI);
6889 bool Success(const llvm::APSInt &SI, const Expr *E) {
6890 return Success(SI, E, Result);
6893 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6894 assert(E->getType()->isIntegralOrEnumerationType() &&
6895 "Invalid evaluation result.");
6896 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6897 "Invalid evaluation result.");
6898 Result = APValue(APSInt(I));
6899 Result.getInt().setIsUnsigned(
6900 E->getType()->isUnsignedIntegerOrEnumerationType());
6903 bool Success(const llvm::APInt &I, const Expr *E) {
6904 return Success(I, E, Result);
6907 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6908 assert(E->getType()->isIntegralOrEnumerationType() &&
6909 "Invalid evaluation result.");
6910 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6913 bool Success(uint64_t Value, const Expr *E) {
6914 return Success(Value, E, Result);
6917 bool Success(CharUnits Size, const Expr *E) {
6918 return Success(Size.getQuantity(), E);
6921 bool Success(const APValue &V, const Expr *E) {
6922 if (V.isLValue() || V.isAddrLabelDiff()) {
6926 return Success(V.getInt(), E);
6929 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6931 //===--------------------------------------------------------------------===//
6933 //===--------------------------------------------------------------------===//
6935 bool VisitIntegerLiteral(const IntegerLiteral *E) {
6936 return Success(E->getValue(), E);
6938 bool VisitCharacterLiteral(const CharacterLiteral *E) {
6939 return Success(E->getValue(), E);
6942 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6943 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6944 if (CheckReferencedDecl(E, E->getDecl()))
6947 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6949 bool VisitMemberExpr(const MemberExpr *E) {
6950 if (CheckReferencedDecl(E, E->getMemberDecl())) {
6951 VisitIgnoredBaseExpression(E->getBase());
6955 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6958 bool VisitCallExpr(const CallExpr *E);
6959 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6960 bool VisitBinaryOperator(const BinaryOperator *E);
6961 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6962 bool VisitUnaryOperator(const UnaryOperator *E);
6964 bool VisitCastExpr(const CastExpr* E);
6965 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6967 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6968 return Success(E->getValue(), E);
6971 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6972 return Success(E->getValue(), E);
6975 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6976 if (Info.ArrayInitIndex == uint64_t(-1)) {
6977 // We were asked to evaluate this subexpression independent of the
6978 // enclosing ArrayInitLoopExpr. We can't do that.
6982 return Success(Info.ArrayInitIndex, E);
6985 // Note, GNU defines __null as an integer, not a pointer.
6986 bool VisitGNUNullExpr(const GNUNullExpr *E) {
6987 return ZeroInitialization(E);
6990 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6991 return Success(E->getValue(), E);
6994 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6995 return Success(E->getValue(), E);
6998 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6999 return Success(E->getValue(), E);
7002 bool VisitUnaryReal(const UnaryOperator *E);
7003 bool VisitUnaryImag(const UnaryOperator *E);
7005 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7006 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7008 // FIXME: Missing: array subscript of vector, member of vector
7010 } // end anonymous namespace
7012 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7013 /// produce either the integer value or a pointer.
7015 /// GCC has a heinous extension which folds casts between pointer types and
7016 /// pointer-sized integral types. We support this by allowing the evaluation of
7017 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7018 /// Some simple arithmetic on such values is supported (they are treated much
7020 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7022 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7023 return IntExprEvaluator(Info, Result).Visit(E);
7026 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7028 if (!EvaluateIntegerOrLValue(E, Val, Info))
7031 // FIXME: It would be better to produce the diagnostic for casting
7032 // a pointer to an integer.
7033 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7036 Result = Val.getInt();
7040 /// Check whether the given declaration can be directly converted to an integral
7041 /// rvalue. If not, no diagnostic is produced; there are other things we can
7043 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7044 // Enums are integer constant exprs.
7045 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7046 // Check for signedness/width mismatches between E type and ECD value.
7047 bool SameSign = (ECD->getInitVal().isSigned()
7048 == E->getType()->isSignedIntegerOrEnumerationType());
7049 bool SameWidth = (ECD->getInitVal().getBitWidth()
7050 == Info.Ctx.getIntWidth(E->getType()));
7051 if (SameSign && SameWidth)
7052 return Success(ECD->getInitVal(), E);
7054 // Get rid of mismatch (otherwise Success assertions will fail)
7055 // by computing a new value matching the type of E.
7056 llvm::APSInt Val = ECD->getInitVal();
7058 Val.setIsSigned(!ECD->getInitVal().isSigned());
7060 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7061 return Success(Val, E);
7067 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7069 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7070 const LangOptions &LangOpts) {
7071 // The following enum mimics the values returned by GCC.
7072 // FIXME: Does GCC differ between lvalue and rvalue references here?
7073 enum gcc_type_class {
7075 void_type_class, integer_type_class, char_type_class,
7076 enumeral_type_class, boolean_type_class,
7077 pointer_type_class, reference_type_class, offset_type_class,
7078 real_type_class, complex_type_class,
7079 function_type_class, method_type_class,
7080 record_type_class, union_type_class,
7081 array_type_class, string_type_class,
7085 // If no argument was supplied, default to "no_type_class". This isn't
7086 // ideal, however it is what gcc does.
7087 if (E->getNumArgs() == 0)
7088 return no_type_class;
7090 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7091 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7093 switch (CanTy->getTypeClass()) {
7094 #define TYPE(ID, BASE)
7095 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7096 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7097 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7098 #include "clang/AST/TypeNodes.def"
7099 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7102 switch (BT->getKind()) {
7103 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7104 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7105 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7106 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7107 #include "clang/AST/BuiltinTypes.def"
7108 case BuiltinType::Void:
7109 return void_type_class;
7111 case BuiltinType::Bool:
7112 return boolean_type_class;
7114 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7115 case BuiltinType::UChar:
7116 case BuiltinType::UShort:
7117 case BuiltinType::UInt:
7118 case BuiltinType::ULong:
7119 case BuiltinType::ULongLong:
7120 case BuiltinType::UInt128:
7121 return integer_type_class;
7123 case BuiltinType::NullPtr:
7124 return pointer_type_class;
7126 case BuiltinType::WChar_U:
7127 case BuiltinType::Char16:
7128 case BuiltinType::Char32:
7129 case BuiltinType::ObjCId:
7130 case BuiltinType::ObjCClass:
7131 case BuiltinType::ObjCSel:
7132 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7133 case BuiltinType::Id:
7134 #include "clang/Basic/OpenCLImageTypes.def"
7135 case BuiltinType::OCLSampler:
7136 case BuiltinType::OCLEvent:
7137 case BuiltinType::OCLClkEvent:
7138 case BuiltinType::OCLQueue:
7139 case BuiltinType::OCLReserveID:
7140 case BuiltinType::Dependent:
7141 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7145 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7149 return pointer_type_class;
7152 case Type::MemberPointer:
7153 if (CanTy->isMemberDataPointerType())
7154 return offset_type_class;
7156 // We expect member pointers to be either data or function pointers,
7158 assert(CanTy->isMemberFunctionPointerType());
7159 return method_type_class;
7163 return complex_type_class;
7165 case Type::FunctionNoProto:
7166 case Type::FunctionProto:
7167 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7170 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7171 switch (RT->getDecl()->getTagKind()) {
7172 case TagTypeKind::TTK_Struct:
7173 case TagTypeKind::TTK_Class:
7174 case TagTypeKind::TTK_Interface:
7175 return record_type_class;
7177 case TagTypeKind::TTK_Enum:
7178 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7180 case TagTypeKind::TTK_Union:
7181 return union_type_class;
7184 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7186 case Type::ConstantArray:
7187 case Type::VariableArray:
7188 case Type::IncompleteArray:
7189 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7191 case Type::BlockPointer:
7192 case Type::LValueReference:
7193 case Type::RValueReference:
7195 case Type::ExtVector:
7197 case Type::DeducedTemplateSpecialization:
7198 case Type::ObjCObject:
7199 case Type::ObjCInterface:
7200 case Type::ObjCObjectPointer:
7203 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7206 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7209 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7210 /// __builtin_constant_p when applied to the given lvalue.
7212 /// An lvalue is only "constant" if it is a pointer or reference to the first
7213 /// character of a string literal.
7214 template<typename LValue>
7215 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7216 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7217 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7220 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7221 /// GCC as we can manage.
7222 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7223 QualType ArgType = Arg->getType();
7225 // __builtin_constant_p always has one operand. The rules which gcc follows
7226 // are not precisely documented, but are as follows:
7228 // - If the operand is of integral, floating, complex or enumeration type,
7229 // and can be folded to a known value of that type, it returns 1.
7230 // - If the operand and can be folded to a pointer to the first character
7231 // of a string literal (or such a pointer cast to an integral type), it
7234 // Otherwise, it returns 0.
7236 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7237 // its support for this does not currently work.
7238 if (ArgType->isIntegralOrEnumerationType()) {
7239 Expr::EvalResult Result;
7240 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7243 APValue &V = Result.Val;
7244 if (V.getKind() == APValue::Int)
7246 if (V.getKind() == APValue::LValue)
7247 return EvaluateBuiltinConstantPForLValue(V);
7248 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7249 return Arg->isEvaluatable(Ctx);
7250 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7252 Expr::EvalStatus Status;
7253 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7254 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7255 : EvaluatePointer(Arg, LV, Info)) &&
7256 !Status.HasSideEffects)
7257 return EvaluateBuiltinConstantPForLValue(LV);
7260 // Anything else isn't considered to be sufficiently constant.
7264 /// Retrieves the "underlying object type" of the given expression,
7265 /// as used by __builtin_object_size.
7266 static QualType getObjectType(APValue::LValueBase B) {
7267 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7268 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7269 return VD->getType();
7270 } else if (const Expr *E = B.get<const Expr*>()) {
7271 if (isa<CompoundLiteralExpr>(E))
7272 return E->getType();
7278 /// A more selective version of E->IgnoreParenCasts for
7279 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7280 /// to change the type of E.
7281 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7283 /// Always returns an RValue with a pointer representation.
7284 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7285 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7287 auto *NoParens = E->IgnoreParens();
7288 auto *Cast = dyn_cast<CastExpr>(NoParens);
7289 if (Cast == nullptr)
7292 // We only conservatively allow a few kinds of casts, because this code is
7293 // inherently a simple solution that seeks to support the common case.
7294 auto CastKind = Cast->getCastKind();
7295 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7296 CastKind != CK_AddressSpaceConversion)
7299 auto *SubExpr = Cast->getSubExpr();
7300 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7302 return ignorePointerCastsAndParens(SubExpr);
7305 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7306 /// record layout. e.g.
7307 /// struct { struct { int a, b; } fst, snd; } obj;
7313 /// obj.snd.b // yes
7315 /// Please note: this function is specialized for how __builtin_object_size
7316 /// views "objects".
7318 /// If this encounters an invalid RecordDecl, it will always return true.
7319 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7320 assert(!LVal.Designator.Invalid);
7322 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7323 const RecordDecl *Parent = FD->getParent();
7324 Invalid = Parent->isInvalidDecl();
7325 if (Invalid || Parent->isUnion())
7327 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7328 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7331 auto &Base = LVal.getLValueBase();
7332 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7333 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7335 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7337 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7338 for (auto *FD : IFD->chain()) {
7340 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7347 QualType BaseType = getType(Base);
7348 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7349 assert(isBaseAnAllocSizeCall(Base) &&
7350 "Unsized array in non-alloc_size call?");
7351 // If this is an alloc_size base, we should ignore the initial array index
7353 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7356 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7357 const auto &Entry = LVal.Designator.Entries[I];
7358 if (BaseType->isArrayType()) {
7359 // Because __builtin_object_size treats arrays as objects, we can ignore
7360 // the index iff this is the last array in the Designator.
7363 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7364 uint64_t Index = Entry.ArrayIndex;
7365 if (Index + 1 != CAT->getSize())
7367 BaseType = CAT->getElementType();
7368 } else if (BaseType->isAnyComplexType()) {
7369 const auto *CT = BaseType->castAs<ComplexType>();
7370 uint64_t Index = Entry.ArrayIndex;
7373 BaseType = CT->getElementType();
7374 } else if (auto *FD = getAsField(Entry)) {
7376 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7378 BaseType = FD->getType();
7380 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7387 /// Tests to see if the LValue has a user-specified designator (that isn't
7388 /// necessarily valid). Note that this always returns 'true' if the LValue has
7389 /// an unsized array as its first designator entry, because there's currently no
7390 /// way to tell if the user typed *foo or foo[0].
7391 static bool refersToCompleteObject(const LValue &LVal) {
7392 if (LVal.Designator.Invalid)
7395 if (!LVal.Designator.Entries.empty())
7396 return LVal.Designator.isMostDerivedAnUnsizedArray();
7398 if (!LVal.InvalidBase)
7401 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7403 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7404 return !E || !isa<MemberExpr>(E);
7407 /// Attempts to detect a user writing into a piece of memory that's impossible
7408 /// to figure out the size of by just using types.
7409 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7410 const SubobjectDesignator &Designator = LVal.Designator;
7412 // - Users can only write off of the end when we have an invalid base. Invalid
7413 // bases imply we don't know where the memory came from.
7414 // - We used to be a bit more aggressive here; we'd only be conservative if
7415 // the array at the end was flexible, or if it had 0 or 1 elements. This
7416 // broke some common standard library extensions (PR30346), but was
7417 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7418 // with some sort of whitelist. OTOH, it seems that GCC is always
7419 // conservative with the last element in structs (if it's an array), so our
7420 // current behavior is more compatible than a whitelisting approach would
7422 return LVal.InvalidBase &&
7423 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7424 Designator.MostDerivedIsArrayElement &&
7425 isDesignatorAtObjectEnd(Ctx, LVal);
7428 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7429 /// Fails if the conversion would cause loss of precision.
7430 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7431 CharUnits &Result) {
7432 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7433 if (Int.ugt(CharUnitsMax))
7435 Result = CharUnits::fromQuantity(Int.getZExtValue());
7439 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7440 /// determine how many bytes exist from the beginning of the object to either
7441 /// the end of the current subobject, or the end of the object itself, depending
7442 /// on what the LValue looks like + the value of Type.
7444 /// If this returns false, the value of Result is undefined.
7445 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7446 unsigned Type, const LValue &LVal,
7447 CharUnits &EndOffset) {
7448 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7450 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7451 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7453 return HandleSizeof(Info, ExprLoc, Ty, Result);
7456 // We want to evaluate the size of the entire object. This is a valid fallback
7457 // for when Type=1 and the designator is invalid, because we're asked for an
7459 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7460 // Type=3 wants a lower bound, so we can't fall back to this.
7461 if (Type == 3 && !DetermineForCompleteObject)
7464 llvm::APInt APEndOffset;
7465 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7466 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7467 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7469 if (LVal.InvalidBase)
7472 QualType BaseTy = getObjectType(LVal.getLValueBase());
7473 return CheckedHandleSizeof(BaseTy, EndOffset);
7476 // We want to evaluate the size of a subobject.
7477 const SubobjectDesignator &Designator = LVal.Designator;
7479 // The following is a moderately common idiom in C:
7481 // struct Foo { int a; char c[1]; };
7482 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7483 // strcpy(&F->c[0], Bar);
7485 // In order to not break too much legacy code, we need to support it.
7486 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7487 // If we can resolve this to an alloc_size call, we can hand that back,
7488 // because we know for certain how many bytes there are to write to.
7489 llvm::APInt APEndOffset;
7490 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7491 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7492 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7494 // If we cannot determine the size of the initial allocation, then we can't
7495 // given an accurate upper-bound. However, we are still able to give
7496 // conservative lower-bounds for Type=3.
7501 CharUnits BytesPerElem;
7502 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7505 // According to the GCC documentation, we want the size of the subobject
7506 // denoted by the pointer. But that's not quite right -- what we actually
7507 // want is the size of the immediately-enclosing array, if there is one.
7508 int64_t ElemsRemaining;
7509 if (Designator.MostDerivedIsArrayElement &&
7510 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7511 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7512 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7513 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7515 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7518 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7522 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7523 /// returns true and stores the result in @p Size.
7525 /// If @p WasError is non-null, this will report whether the failure to evaluate
7526 /// is to be treated as an Error in IntExprEvaluator.
7527 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7528 EvalInfo &Info, uint64_t &Size) {
7529 // Determine the denoted object.
7532 // The operand of __builtin_object_size is never evaluated for side-effects.
7533 // If there are any, but we can determine the pointed-to object anyway, then
7534 // ignore the side-effects.
7535 SpeculativeEvaluationRAII SpeculativeEval(Info);
7536 FoldOffsetRAII Fold(Info);
7538 if (E->isGLValue()) {
7539 // It's possible for us to be given GLValues if we're called via
7540 // Expr::tryEvaluateObjectSize.
7542 if (!EvaluateAsRValue(Info, E, RVal))
7544 LVal.setFrom(Info.Ctx, RVal);
7545 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7546 /*InvalidBaseOK=*/true))
7550 // If we point to before the start of the object, there are no accessible
7552 if (LVal.getLValueOffset().isNegative()) {
7557 CharUnits EndOffset;
7558 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7561 // If we've fallen outside of the end offset, just pretend there's nothing to
7562 // write to/read from.
7563 if (EndOffset <= LVal.getLValueOffset())
7566 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7570 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7571 if (unsigned BuiltinOp = E->getBuiltinCallee())
7572 return VisitBuiltinCallExpr(E, BuiltinOp);
7574 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7577 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7578 unsigned BuiltinOp) {
7579 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7581 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7583 case Builtin::BI__builtin_object_size: {
7584 // The type was checked when we built the expression.
7586 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7587 assert(Type <= 3 && "unexpected type");
7590 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7591 return Success(Size, E);
7593 if (E->getArg(0)->HasSideEffects(Info.Ctx))
7594 return Success((Type & 2) ? 0 : -1, E);
7596 // Expression had no side effects, but we couldn't statically determine the
7597 // size of the referenced object.
7598 switch (Info.EvalMode) {
7599 case EvalInfo::EM_ConstantExpression:
7600 case EvalInfo::EM_PotentialConstantExpression:
7601 case EvalInfo::EM_ConstantFold:
7602 case EvalInfo::EM_EvaluateForOverflow:
7603 case EvalInfo::EM_IgnoreSideEffects:
7604 case EvalInfo::EM_OffsetFold:
7605 // Leave it to IR generation.
7607 case EvalInfo::EM_ConstantExpressionUnevaluated:
7608 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7609 // Reduce it to a constant now.
7610 return Success((Type & 2) ? 0 : -1, E);
7613 llvm_unreachable("unexpected EvalMode");
7616 case Builtin::BI__builtin_bswap16:
7617 case Builtin::BI__builtin_bswap32:
7618 case Builtin::BI__builtin_bswap64: {
7620 if (!EvaluateInteger(E->getArg(0), Val, Info))
7623 return Success(Val.byteSwap(), E);
7626 case Builtin::BI__builtin_classify_type:
7627 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7629 // FIXME: BI__builtin_clrsb
7630 // FIXME: BI__builtin_clrsbl
7631 // FIXME: BI__builtin_clrsbll
7633 case Builtin::BI__builtin_clz:
7634 case Builtin::BI__builtin_clzl:
7635 case Builtin::BI__builtin_clzll:
7636 case Builtin::BI__builtin_clzs: {
7638 if (!EvaluateInteger(E->getArg(0), Val, Info))
7643 return Success(Val.countLeadingZeros(), E);
7646 case Builtin::BI__builtin_constant_p:
7647 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7649 case Builtin::BI__builtin_ctz:
7650 case Builtin::BI__builtin_ctzl:
7651 case Builtin::BI__builtin_ctzll:
7652 case Builtin::BI__builtin_ctzs: {
7654 if (!EvaluateInteger(E->getArg(0), Val, Info))
7659 return Success(Val.countTrailingZeros(), E);
7662 case Builtin::BI__builtin_eh_return_data_regno: {
7663 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7664 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7665 return Success(Operand, E);
7668 case Builtin::BI__builtin_expect:
7669 return Visit(E->getArg(0));
7671 case Builtin::BI__builtin_ffs:
7672 case Builtin::BI__builtin_ffsl:
7673 case Builtin::BI__builtin_ffsll: {
7675 if (!EvaluateInteger(E->getArg(0), Val, Info))
7678 unsigned N = Val.countTrailingZeros();
7679 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7682 case Builtin::BI__builtin_fpclassify: {
7684 if (!EvaluateFloat(E->getArg(5), Val, Info))
7687 switch (Val.getCategory()) {
7688 case APFloat::fcNaN: Arg = 0; break;
7689 case APFloat::fcInfinity: Arg = 1; break;
7690 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7691 case APFloat::fcZero: Arg = 4; break;
7693 return Visit(E->getArg(Arg));
7696 case Builtin::BI__builtin_isinf_sign: {
7698 return EvaluateFloat(E->getArg(0), Val, Info) &&
7699 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7702 case Builtin::BI__builtin_isinf: {
7704 return EvaluateFloat(E->getArg(0), Val, Info) &&
7705 Success(Val.isInfinity() ? 1 : 0, E);
7708 case Builtin::BI__builtin_isfinite: {
7710 return EvaluateFloat(E->getArg(0), Val, Info) &&
7711 Success(Val.isFinite() ? 1 : 0, E);
7714 case Builtin::BI__builtin_isnan: {
7716 return EvaluateFloat(E->getArg(0), Val, Info) &&
7717 Success(Val.isNaN() ? 1 : 0, E);
7720 case Builtin::BI__builtin_isnormal: {
7722 return EvaluateFloat(E->getArg(0), Val, Info) &&
7723 Success(Val.isNormal() ? 1 : 0, E);
7726 case Builtin::BI__builtin_parity:
7727 case Builtin::BI__builtin_parityl:
7728 case Builtin::BI__builtin_parityll: {
7730 if (!EvaluateInteger(E->getArg(0), Val, Info))
7733 return Success(Val.countPopulation() % 2, E);
7736 case Builtin::BI__builtin_popcount:
7737 case Builtin::BI__builtin_popcountl:
7738 case Builtin::BI__builtin_popcountll: {
7740 if (!EvaluateInteger(E->getArg(0), Val, Info))
7743 return Success(Val.countPopulation(), E);
7746 case Builtin::BIstrlen:
7747 case Builtin::BIwcslen:
7748 // A call to strlen is not a constant expression.
7749 if (Info.getLangOpts().CPlusPlus11)
7750 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7751 << /*isConstexpr*/0 << /*isConstructor*/0
7752 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7754 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7756 case Builtin::BI__builtin_strlen:
7757 case Builtin::BI__builtin_wcslen: {
7758 // As an extension, we support __builtin_strlen() as a constant expression,
7759 // and support folding strlen() to a constant.
7761 if (!EvaluatePointer(E->getArg(0), String, Info))
7764 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7766 // Fast path: if it's a string literal, search the string value.
7767 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7768 String.getLValueBase().dyn_cast<const Expr *>())) {
7769 // The string literal may have embedded null characters. Find the first
7770 // one and truncate there.
7771 StringRef Str = S->getBytes();
7772 int64_t Off = String.Offset.getQuantity();
7773 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7774 S->getCharByteWidth() == 1 &&
7775 // FIXME: Add fast-path for wchar_t too.
7776 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7777 Str = Str.substr(Off);
7779 StringRef::size_type Pos = Str.find(0);
7780 if (Pos != StringRef::npos)
7781 Str = Str.substr(0, Pos);
7783 return Success(Str.size(), E);
7786 // Fall through to slow path to issue appropriate diagnostic.
7789 // Slow path: scan the bytes of the string looking for the terminating 0.
7790 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7792 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7796 return Success(Strlen, E);
7797 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7802 case Builtin::BIstrcmp:
7803 case Builtin::BIwcscmp:
7804 case Builtin::BIstrncmp:
7805 case Builtin::BIwcsncmp:
7806 case Builtin::BImemcmp:
7807 case Builtin::BIwmemcmp:
7808 // A call to strlen is not a constant expression.
7809 if (Info.getLangOpts().CPlusPlus11)
7810 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7811 << /*isConstexpr*/0 << /*isConstructor*/0
7812 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7814 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7816 case Builtin::BI__builtin_strcmp:
7817 case Builtin::BI__builtin_wcscmp:
7818 case Builtin::BI__builtin_strncmp:
7819 case Builtin::BI__builtin_wcsncmp:
7820 case Builtin::BI__builtin_memcmp:
7821 case Builtin::BI__builtin_wmemcmp: {
7822 LValue String1, String2;
7823 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7824 !EvaluatePointer(E->getArg(1), String2, Info))
7827 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7829 uint64_t MaxLength = uint64_t(-1);
7830 if (BuiltinOp != Builtin::BIstrcmp &&
7831 BuiltinOp != Builtin::BIwcscmp &&
7832 BuiltinOp != Builtin::BI__builtin_strcmp &&
7833 BuiltinOp != Builtin::BI__builtin_wcscmp) {
7835 if (!EvaluateInteger(E->getArg(2), N, Info))
7837 MaxLength = N.getExtValue();
7839 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7840 BuiltinOp != Builtin::BIwmemcmp &&
7841 BuiltinOp != Builtin::BI__builtin_memcmp &&
7842 BuiltinOp != Builtin::BI__builtin_wmemcmp);
7843 for (; MaxLength; --MaxLength) {
7844 APValue Char1, Char2;
7845 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7846 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7847 !Char1.isInt() || !Char2.isInt())
7849 if (Char1.getInt() != Char2.getInt())
7850 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7851 if (StopAtNull && !Char1.getInt())
7852 return Success(0, E);
7853 assert(!(StopAtNull && !Char2.getInt()));
7854 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7855 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7858 // We hit the strncmp / memcmp limit.
7859 return Success(0, E);
7862 case Builtin::BI__atomic_always_lock_free:
7863 case Builtin::BI__atomic_is_lock_free:
7864 case Builtin::BI__c11_atomic_is_lock_free: {
7866 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7869 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7870 // of two less than the maximum inline atomic width, we know it is
7871 // lock-free. If the size isn't a power of two, or greater than the
7872 // maximum alignment where we promote atomics, we know it is not lock-free
7873 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7874 // the answer can only be determined at runtime; for example, 16-byte
7875 // atomics have lock-free implementations on some, but not all,
7876 // x86-64 processors.
7878 // Check power-of-two.
7879 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7880 if (Size.isPowerOfTwo()) {
7881 // Check against inlining width.
7882 unsigned InlineWidthBits =
7883 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7884 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7885 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7886 Size == CharUnits::One() ||
7887 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7888 Expr::NPC_NeverValueDependent))
7889 // OK, we will inline appropriately-aligned operations of this size,
7890 // and _Atomic(T) is appropriately-aligned.
7891 return Success(1, E);
7893 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7894 castAs<PointerType>()->getPointeeType();
7895 if (!PointeeType->isIncompleteType() &&
7896 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7897 // OK, we will inline operations on this object.
7898 return Success(1, E);
7903 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7904 Success(0, E) : Error(E);
7909 static bool HasSameBase(const LValue &A, const LValue &B) {
7910 if (!A.getLValueBase())
7911 return !B.getLValueBase();
7912 if (!B.getLValueBase())
7915 if (A.getLValueBase().getOpaqueValue() !=
7916 B.getLValueBase().getOpaqueValue()) {
7917 const Decl *ADecl = GetLValueBaseDecl(A);
7920 const Decl *BDecl = GetLValueBaseDecl(B);
7921 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7925 return IsGlobalLValue(A.getLValueBase()) ||
7926 A.getLValueCallIndex() == B.getLValueCallIndex();
7929 /// \brief Determine whether this is a pointer past the end of the complete
7930 /// object referred to by the lvalue.
7931 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7933 // A null pointer can be viewed as being "past the end" but we don't
7934 // choose to look at it that way here.
7935 if (!LV.getLValueBase())
7938 // If the designator is valid and refers to a subobject, we're not pointing
7940 if (!LV.getLValueDesignator().Invalid &&
7941 !LV.getLValueDesignator().isOnePastTheEnd())
7944 // A pointer to an incomplete type might be past-the-end if the type's size is
7945 // zero. We cannot tell because the type is incomplete.
7946 QualType Ty = getType(LV.getLValueBase());
7947 if (Ty->isIncompleteType())
7950 // We're a past-the-end pointer if we point to the byte after the object,
7951 // no matter what our type or path is.
7952 auto Size = Ctx.getTypeSizeInChars(Ty);
7953 return LV.getLValueOffset() == Size;
7958 /// \brief Data recursive integer evaluator of certain binary operators.
7960 /// We use a data recursive algorithm for binary operators so that we are able
7961 /// to handle extreme cases of chained binary operators without causing stack
7963 class DataRecursiveIntBinOpEvaluator {
7968 EvalResult() : Failed(false) { }
7970 void swap(EvalResult &RHS) {
7972 Failed = RHS.Failed;
7979 EvalResult LHSResult; // meaningful only for binary operator expression.
7980 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7983 Job(Job &&) = default;
7985 void startSpeculativeEval(EvalInfo &Info) {
7986 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7990 SpeculativeEvaluationRAII SpecEvalRAII;
7993 SmallVector<Job, 16> Queue;
7995 IntExprEvaluator &IntEval;
7997 APValue &FinalResult;
8000 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8001 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8003 /// \brief True if \param E is a binary operator that we are going to handle
8004 /// data recursively.
8005 /// We handle binary operators that are comma, logical, or that have operands
8006 /// with integral or enumeration type.
8007 static bool shouldEnqueue(const BinaryOperator *E) {
8008 return E->getOpcode() == BO_Comma ||
8011 E->getType()->isIntegralOrEnumerationType() &&
8012 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8013 E->getRHS()->getType()->isIntegralOrEnumerationType());
8016 bool Traverse(const BinaryOperator *E) {
8018 EvalResult PrevResult;
8019 while (!Queue.empty())
8020 process(PrevResult);
8022 if (PrevResult.Failed) return false;
8024 FinalResult.swap(PrevResult.Val);
8029 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8030 return IntEval.Success(Value, E, Result);
8032 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8033 return IntEval.Success(Value, E, Result);
8035 bool Error(const Expr *E) {
8036 return IntEval.Error(E);
8038 bool Error(const Expr *E, diag::kind D) {
8039 return IntEval.Error(E, D);
8042 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8043 return Info.CCEDiag(E, D);
8046 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8047 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8048 bool &SuppressRHSDiags);
8050 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8051 const BinaryOperator *E, APValue &Result);
8053 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8054 Result.Failed = !Evaluate(Result.Val, Info, E);
8056 Result.Val = APValue();
8059 void process(EvalResult &Result);
8061 void enqueue(const Expr *E) {
8062 E = E->IgnoreParens();
8063 Queue.resize(Queue.size()+1);
8065 Queue.back().Kind = Job::AnyExprKind;
8071 bool DataRecursiveIntBinOpEvaluator::
8072 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8073 bool &SuppressRHSDiags) {
8074 if (E->getOpcode() == BO_Comma) {
8075 // Ignore LHS but note if we could not evaluate it.
8076 if (LHSResult.Failed)
8077 return Info.noteSideEffect();
8081 if (E->isLogicalOp()) {
8083 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8084 // We were able to evaluate the LHS, see if we can get away with not
8085 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8086 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8087 Success(LHSAsBool, E, LHSResult.Val);
8088 return false; // Ignore RHS
8091 LHSResult.Failed = true;
8093 // Since we weren't able to evaluate the left hand side, it
8094 // might have had side effects.
8095 if (!Info.noteSideEffect())
8098 // We can't evaluate the LHS; however, sometimes the result
8099 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8100 // Don't ignore RHS and suppress diagnostics from this arm.
8101 SuppressRHSDiags = true;
8107 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8108 E->getRHS()->getType()->isIntegralOrEnumerationType());
8110 if (LHSResult.Failed && !Info.noteFailure())
8111 return false; // Ignore RHS;
8116 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8118 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8119 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8121 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8122 CharUnits &Offset = LVal.getLValueOffset();
8123 uint64_t Offset64 = Offset.getQuantity();
8124 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8125 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8126 : Offset64 + Index64);
8129 bool DataRecursiveIntBinOpEvaluator::
8130 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8131 const BinaryOperator *E, APValue &Result) {
8132 if (E->getOpcode() == BO_Comma) {
8133 if (RHSResult.Failed)
8135 Result = RHSResult.Val;
8139 if (E->isLogicalOp()) {
8140 bool lhsResult, rhsResult;
8141 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8142 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8146 if (E->getOpcode() == BO_LOr)
8147 return Success(lhsResult || rhsResult, E, Result);
8149 return Success(lhsResult && rhsResult, E, Result);
8153 // We can't evaluate the LHS; however, sometimes the result
8154 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8155 if (rhsResult == (E->getOpcode() == BO_LOr))
8156 return Success(rhsResult, E, Result);
8163 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8164 E->getRHS()->getType()->isIntegralOrEnumerationType());
8166 if (LHSResult.Failed || RHSResult.Failed)
8169 const APValue &LHSVal = LHSResult.Val;
8170 const APValue &RHSVal = RHSResult.Val;
8172 // Handle cases like (unsigned long)&a + 4.
8173 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8175 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8179 // Handle cases like 4 + (unsigned long)&a
8180 if (E->getOpcode() == BO_Add &&
8181 RHSVal.isLValue() && LHSVal.isInt()) {
8183 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8187 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8188 // Handle (intptr_t)&&A - (intptr_t)&&B.
8189 if (!LHSVal.getLValueOffset().isZero() ||
8190 !RHSVal.getLValueOffset().isZero())
8192 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8193 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8194 if (!LHSExpr || !RHSExpr)
8196 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8197 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8198 if (!LHSAddrExpr || !RHSAddrExpr)
8200 // Make sure both labels come from the same function.
8201 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8202 RHSAddrExpr->getLabel()->getDeclContext())
8204 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8208 // All the remaining cases expect both operands to be an integer
8209 if (!LHSVal.isInt() || !RHSVal.isInt())
8212 // Set up the width and signedness manually, in case it can't be deduced
8213 // from the operation we're performing.
8214 // FIXME: Don't do this in the cases where we can deduce it.
8215 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8216 E->getType()->isUnsignedIntegerOrEnumerationType());
8217 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8218 RHSVal.getInt(), Value))
8220 return Success(Value, E, Result);
8223 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8224 Job &job = Queue.back();
8227 case Job::AnyExprKind: {
8228 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8229 if (shouldEnqueue(Bop)) {
8230 job.Kind = Job::BinOpKind;
8231 enqueue(Bop->getLHS());
8236 EvaluateExpr(job.E, Result);
8241 case Job::BinOpKind: {
8242 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8243 bool SuppressRHSDiags = false;
8244 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8248 if (SuppressRHSDiags)
8249 job.startSpeculativeEval(Info);
8250 job.LHSResult.swap(Result);
8251 job.Kind = Job::BinOpVisitedLHSKind;
8252 enqueue(Bop->getRHS());
8256 case Job::BinOpVisitedLHSKind: {
8257 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8260 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8266 llvm_unreachable("Invalid Job::Kind!");
8270 /// Used when we determine that we should fail, but can keep evaluating prior to
8271 /// noting that we had a failure.
8272 class DelayedNoteFailureRAII {
8277 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8278 : Info(Info), NoteFailure(NoteFailure) {}
8279 ~DelayedNoteFailureRAII() {
8281 bool ContinueAfterFailure = Info.noteFailure();
8282 (void)ContinueAfterFailure;
8283 assert(ContinueAfterFailure &&
8284 "Shouldn't have kept evaluating on failure.");
8290 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8291 // We don't call noteFailure immediately because the assignment happens after
8292 // we evaluate LHS and RHS.
8293 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8296 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8297 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8298 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8300 QualType LHSTy = E->getLHS()->getType();
8301 QualType RHSTy = E->getRHS()->getType();
8303 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8304 ComplexValue LHS, RHS;
8306 if (E->isAssignmentOp()) {
8308 EvaluateLValue(E->getLHS(), LV, Info);
8310 } else if (LHSTy->isRealFloatingType()) {
8311 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8313 LHS.makeComplexFloat();
8314 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8317 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8319 if (!LHSOK && !Info.noteFailure())
8322 if (E->getRHS()->getType()->isRealFloatingType()) {
8323 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8325 RHS.makeComplexFloat();
8326 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8327 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8330 if (LHS.isComplexFloat()) {
8331 APFloat::cmpResult CR_r =
8332 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8333 APFloat::cmpResult CR_i =
8334 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8336 if (E->getOpcode() == BO_EQ)
8337 return Success((CR_r == APFloat::cmpEqual &&
8338 CR_i == APFloat::cmpEqual), E);
8340 assert(E->getOpcode() == BO_NE &&
8341 "Invalid complex comparison.");
8342 return Success(((CR_r == APFloat::cmpGreaterThan ||
8343 CR_r == APFloat::cmpLessThan ||
8344 CR_r == APFloat::cmpUnordered) ||
8345 (CR_i == APFloat::cmpGreaterThan ||
8346 CR_i == APFloat::cmpLessThan ||
8347 CR_i == APFloat::cmpUnordered)), E);
8350 if (E->getOpcode() == BO_EQ)
8351 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8352 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8354 assert(E->getOpcode() == BO_NE &&
8355 "Invalid compex comparison.");
8356 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8357 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8362 if (LHSTy->isRealFloatingType() &&
8363 RHSTy->isRealFloatingType()) {
8364 APFloat RHS(0.0), LHS(0.0);
8366 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8367 if (!LHSOK && !Info.noteFailure())
8370 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8373 APFloat::cmpResult CR = LHS.compare(RHS);
8375 switch (E->getOpcode()) {
8377 llvm_unreachable("Invalid binary operator!");
8379 return Success(CR == APFloat::cmpLessThan, E);
8381 return Success(CR == APFloat::cmpGreaterThan, E);
8383 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8385 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8388 return Success(CR == APFloat::cmpEqual, E);
8390 return Success(CR == APFloat::cmpGreaterThan
8391 || CR == APFloat::cmpLessThan
8392 || CR == APFloat::cmpUnordered, E);
8396 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8397 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8398 LValue LHSValue, RHSValue;
8400 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8401 if (!LHSOK && !Info.noteFailure())
8404 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8407 // Reject differing bases from the normal codepath; we special-case
8408 // comparisons to null.
8409 if (!HasSameBase(LHSValue, RHSValue)) {
8410 if (E->getOpcode() == BO_Sub) {
8411 // Handle &&A - &&B.
8412 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8414 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8415 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8416 if (!LHSExpr || !RHSExpr)
8418 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8419 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8420 if (!LHSAddrExpr || !RHSAddrExpr)
8422 // Make sure both labels come from the same function.
8423 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8424 RHSAddrExpr->getLabel()->getDeclContext())
8426 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8428 // Inequalities and subtractions between unrelated pointers have
8429 // unspecified or undefined behavior.
8430 if (!E->isEqualityOp())
8432 // A constant address may compare equal to the address of a symbol.
8433 // The one exception is that address of an object cannot compare equal
8434 // to a null pointer constant.
8435 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8436 (!RHSValue.Base && !RHSValue.Offset.isZero()))
8438 // It's implementation-defined whether distinct literals will have
8439 // distinct addresses. In clang, the result of such a comparison is
8440 // unspecified, so it is not a constant expression. However, we do know
8441 // that the address of a literal will be non-null.
8442 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8443 LHSValue.Base && RHSValue.Base)
8445 // We can't tell whether weak symbols will end up pointing to the same
8447 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8449 // We can't compare the address of the start of one object with the
8450 // past-the-end address of another object, per C++ DR1652.
8451 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8452 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8453 (RHSValue.Base && RHSValue.Offset.isZero() &&
8454 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8456 // We can't tell whether an object is at the same address as another
8457 // zero sized object.
8458 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8459 (LHSValue.Base && isZeroSized(RHSValue)))
8461 // Pointers with different bases cannot represent the same object.
8462 // (Note that clang defaults to -fmerge-all-constants, which can
8463 // lead to inconsistent results for comparisons involving the address
8464 // of a constant; this generally doesn't matter in practice.)
8465 return Success(E->getOpcode() == BO_NE, E);
8468 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8469 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8471 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8472 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8474 if (E->getOpcode() == BO_Sub) {
8475 // C++11 [expr.add]p6:
8476 // Unless both pointers point to elements of the same array object, or
8477 // one past the last element of the array object, the behavior is
8479 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8480 !AreElementsOfSameArray(getType(LHSValue.Base),
8481 LHSDesignator, RHSDesignator))
8482 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8484 QualType Type = E->getLHS()->getType();
8485 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8487 CharUnits ElementSize;
8488 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8491 // As an extension, a type may have zero size (empty struct or union in
8492 // C, array of zero length). Pointer subtraction in such cases has
8493 // undefined behavior, so is not constant.
8494 if (ElementSize.isZero()) {
8495 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8500 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8501 // and produce incorrect results when it overflows. Such behavior
8502 // appears to be non-conforming, but is common, so perhaps we should
8503 // assume the standard intended for such cases to be undefined behavior
8504 // and check for them.
8506 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8507 // overflow in the final conversion to ptrdiff_t.
8509 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8511 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8513 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8514 APSInt TrueResult = (LHS - RHS) / ElemSize;
8515 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8517 if (Result.extend(65) != TrueResult &&
8518 !HandleOverflow(Info, E, TrueResult, E->getType()))
8520 return Success(Result, E);
8523 // C++11 [expr.rel]p3:
8524 // Pointers to void (after pointer conversions) can be compared, with a
8525 // result defined as follows: If both pointers represent the same
8526 // address or are both the null pointer value, the result is true if the
8527 // operator is <= or >= and false otherwise; otherwise the result is
8529 // We interpret this as applying to pointers to *cv* void.
8530 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8531 E->isRelationalOp())
8532 CCEDiag(E, diag::note_constexpr_void_comparison);
8534 // C++11 [expr.rel]p2:
8535 // - If two pointers point to non-static data members of the same object,
8536 // or to subobjects or array elements fo such members, recursively, the
8537 // pointer to the later declared member compares greater provided the
8538 // two members have the same access control and provided their class is
8541 // - Otherwise pointer comparisons are unspecified.
8542 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8543 E->isRelationalOp()) {
8546 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8547 RHSDesignator, WasArrayIndex);
8548 // At the point where the designators diverge, the comparison has a
8549 // specified value if:
8550 // - we are comparing array indices
8551 // - we are comparing fields of a union, or fields with the same access
8552 // Otherwise, the result is unspecified and thus the comparison is not a
8553 // constant expression.
8554 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8555 Mismatch < RHSDesignator.Entries.size()) {
8556 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8557 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8559 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8561 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8562 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8563 << RF->getParent() << RF;
8565 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8566 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8567 << LF->getParent() << LF;
8568 else if (!LF->getParent()->isUnion() &&
8569 LF->getAccess() != RF->getAccess())
8570 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8571 << LF << LF->getAccess() << RF << RF->getAccess()
8576 // The comparison here must be unsigned, and performed with the same
8577 // width as the pointer.
8578 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8579 uint64_t CompareLHS = LHSOffset.getQuantity();
8580 uint64_t CompareRHS = RHSOffset.getQuantity();
8581 assert(PtrSize <= 64 && "Unexpected pointer width");
8582 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8586 // If there is a base and this is a relational operator, we can only
8587 // compare pointers within the object in question; otherwise, the result
8588 // depends on where the object is located in memory.
8589 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8590 QualType BaseTy = getType(LHSValue.Base);
8591 if (BaseTy->isIncompleteType())
8593 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8594 uint64_t OffsetLimit = Size.getQuantity();
8595 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8599 switch (E->getOpcode()) {
8600 default: llvm_unreachable("missing comparison operator");
8601 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8602 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8603 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8604 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8605 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8606 case BO_NE: return Success(CompareLHS != CompareRHS, E);
8611 if (LHSTy->isMemberPointerType()) {
8612 assert(E->isEqualityOp() && "unexpected member pointer operation");
8613 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8615 MemberPtr LHSValue, RHSValue;
8617 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8618 if (!LHSOK && !Info.noteFailure())
8621 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8624 // C++11 [expr.eq]p2:
8625 // If both operands are null, they compare equal. Otherwise if only one is
8626 // null, they compare unequal.
8627 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8628 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8629 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8632 // Otherwise if either is a pointer to a virtual member function, the
8633 // result is unspecified.
8634 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8635 if (MD->isVirtual())
8636 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8637 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8638 if (MD->isVirtual())
8639 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8641 // Otherwise they compare equal if and only if they would refer to the
8642 // same member of the same most derived object or the same subobject if
8643 // they were dereferenced with a hypothetical object of the associated
8645 bool Equal = LHSValue == RHSValue;
8646 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8649 if (LHSTy->isNullPtrType()) {
8650 assert(E->isComparisonOp() && "unexpected nullptr operation");
8651 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8652 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8653 // are compared, the result is true of the operator is <=, >= or ==, and
8655 BinaryOperator::Opcode Opcode = E->getOpcode();
8656 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8659 assert((!LHSTy->isIntegralOrEnumerationType() ||
8660 !RHSTy->isIntegralOrEnumerationType()) &&
8661 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8662 // We can't continue from here for non-integral types.
8663 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8666 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8667 /// a result as the expression's type.
8668 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8669 const UnaryExprOrTypeTraitExpr *E) {
8670 switch(E->getKind()) {
8671 case UETT_AlignOf: {
8672 if (E->isArgumentType())
8673 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8675 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8678 case UETT_VecStep: {
8679 QualType Ty = E->getTypeOfArgument();
8681 if (Ty->isVectorType()) {
8682 unsigned n = Ty->castAs<VectorType>()->getNumElements();
8684 // The vec_step built-in functions that take a 3-component
8685 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8689 return Success(n, E);
8691 return Success(1, E);
8695 QualType SrcTy = E->getTypeOfArgument();
8696 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8697 // the result is the size of the referenced type."
8698 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8699 SrcTy = Ref->getPointeeType();
8702 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8704 return Success(Sizeof, E);
8706 case UETT_OpenMPRequiredSimdAlign:
8707 assert(E->isArgumentType());
8709 Info.Ctx.toCharUnitsFromBits(
8710 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8715 llvm_unreachable("unknown expr/type trait");
8718 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8720 unsigned n = OOE->getNumComponents();
8723 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8724 for (unsigned i = 0; i != n; ++i) {
8725 OffsetOfNode ON = OOE->getComponent(i);
8726 switch (ON.getKind()) {
8727 case OffsetOfNode::Array: {
8728 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8730 if (!EvaluateInteger(Idx, IdxResult, Info))
8732 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8735 CurrentType = AT->getElementType();
8736 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8737 Result += IdxResult.getSExtValue() * ElementSize;
8741 case OffsetOfNode::Field: {
8742 FieldDecl *MemberDecl = ON.getField();
8743 const RecordType *RT = CurrentType->getAs<RecordType>();
8746 RecordDecl *RD = RT->getDecl();
8747 if (RD->isInvalidDecl()) return false;
8748 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8749 unsigned i = MemberDecl->getFieldIndex();
8750 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8751 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8752 CurrentType = MemberDecl->getType().getNonReferenceType();
8756 case OffsetOfNode::Identifier:
8757 llvm_unreachable("dependent __builtin_offsetof");
8759 case OffsetOfNode::Base: {
8760 CXXBaseSpecifier *BaseSpec = ON.getBase();
8761 if (BaseSpec->isVirtual())
8764 // Find the layout of the class whose base we are looking into.
8765 const RecordType *RT = CurrentType->getAs<RecordType>();
8768 RecordDecl *RD = RT->getDecl();
8769 if (RD->isInvalidDecl()) return false;
8770 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8772 // Find the base class itself.
8773 CurrentType = BaseSpec->getType();
8774 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8778 // Add the offset to the base.
8779 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8784 return Success(Result, OOE);
8787 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8788 switch (E->getOpcode()) {
8790 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8794 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8795 // If so, we could clear the diagnostic ID.
8796 return Visit(E->getSubExpr());
8798 // The result is just the value.
8799 return Visit(E->getSubExpr());
8801 if (!Visit(E->getSubExpr()))
8803 if (!Result.isInt()) return Error(E);
8804 const APSInt &Value = Result.getInt();
8805 if (Value.isSigned() && Value.isMinSignedValue() &&
8806 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8809 return Success(-Value, E);
8812 if (!Visit(E->getSubExpr()))
8814 if (!Result.isInt()) return Error(E);
8815 return Success(~Result.getInt(), E);
8819 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8821 return Success(!bres, E);
8826 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8827 /// result type is integer.
8828 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8829 const Expr *SubExpr = E->getSubExpr();
8830 QualType DestType = E->getType();
8831 QualType SrcType = SubExpr->getType();
8833 switch (E->getCastKind()) {
8834 case CK_BaseToDerived:
8835 case CK_DerivedToBase:
8836 case CK_UncheckedDerivedToBase:
8839 case CK_ArrayToPointerDecay:
8840 case CK_FunctionToPointerDecay:
8841 case CK_NullToPointer:
8842 case CK_NullToMemberPointer:
8843 case CK_BaseToDerivedMemberPointer:
8844 case CK_DerivedToBaseMemberPointer:
8845 case CK_ReinterpretMemberPointer:
8846 case CK_ConstructorConversion:
8847 case CK_IntegralToPointer:
8849 case CK_VectorSplat:
8850 case CK_IntegralToFloating:
8851 case CK_FloatingCast:
8852 case CK_CPointerToObjCPointerCast:
8853 case CK_BlockPointerToObjCPointerCast:
8854 case CK_AnyPointerToBlockPointerCast:
8855 case CK_ObjCObjectLValueCast:
8856 case CK_FloatingRealToComplex:
8857 case CK_FloatingComplexToReal:
8858 case CK_FloatingComplexCast:
8859 case CK_FloatingComplexToIntegralComplex:
8860 case CK_IntegralRealToComplex:
8861 case CK_IntegralComplexCast:
8862 case CK_IntegralComplexToFloatingComplex:
8863 case CK_BuiltinFnToFnPtr:
8864 case CK_ZeroToOCLEvent:
8865 case CK_ZeroToOCLQueue:
8866 case CK_NonAtomicToAtomic:
8867 case CK_AddressSpaceConversion:
8868 case CK_IntToOCLSampler:
8869 llvm_unreachable("invalid cast kind for integral value");
8873 case CK_LValueBitCast:
8874 case CK_ARCProduceObject:
8875 case CK_ARCConsumeObject:
8876 case CK_ARCReclaimReturnedObject:
8877 case CK_ARCExtendBlockObject:
8878 case CK_CopyAndAutoreleaseBlockObject:
8881 case CK_UserDefinedConversion:
8882 case CK_LValueToRValue:
8883 case CK_AtomicToNonAtomic:
8885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8887 case CK_MemberPointerToBoolean:
8888 case CK_PointerToBoolean:
8889 case CK_IntegralToBoolean:
8890 case CK_FloatingToBoolean:
8891 case CK_BooleanToSignedIntegral:
8892 case CK_FloatingComplexToBoolean:
8893 case CK_IntegralComplexToBoolean: {
8895 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8897 uint64_t IntResult = BoolResult;
8898 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8899 IntResult = (uint64_t)-1;
8900 return Success(IntResult, E);
8903 case CK_IntegralCast: {
8904 if (!Visit(SubExpr))
8907 if (!Result.isInt()) {
8908 // Allow casts of address-of-label differences if they are no-ops
8909 // or narrowing. (The narrowing case isn't actually guaranteed to
8910 // be constant-evaluatable except in some narrow cases which are hard
8911 // to detect here. We let it through on the assumption the user knows
8912 // what they are doing.)
8913 if (Result.isAddrLabelDiff())
8914 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8915 // Only allow casts of lvalues if they are lossless.
8916 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8919 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8920 Result.getInt()), E);
8923 case CK_PointerToIntegral: {
8924 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8927 if (!EvaluatePointer(SubExpr, LV, Info))
8930 if (LV.getLValueBase()) {
8931 // Only allow based lvalue casts if they are lossless.
8932 // FIXME: Allow a larger integer size than the pointer size, and allow
8933 // narrowing back down to pointer width in subsequent integral casts.
8934 // FIXME: Check integer type's active bits, not its type size.
8935 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8938 LV.Designator.setInvalid();
8939 LV.moveInto(Result);
8944 if (LV.isNullPointer())
8945 V = Info.Ctx.getTargetNullPointerValue(SrcType);
8947 V = LV.getLValueOffset().getQuantity();
8949 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8950 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8953 case CK_IntegralComplexToReal: {
8955 if (!EvaluateComplex(SubExpr, C, Info))
8957 return Success(C.getComplexIntReal(), E);
8960 case CK_FloatingToIntegral: {
8962 if (!EvaluateFloat(SubExpr, F, Info))
8966 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8968 return Success(Value, E);
8972 llvm_unreachable("unknown cast resulting in integral value");
8975 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8976 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8978 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8980 if (!LV.isComplexInt())
8982 return Success(LV.getComplexIntReal(), E);
8985 return Visit(E->getSubExpr());
8988 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8989 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8991 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8993 if (!LV.isComplexInt())
8995 return Success(LV.getComplexIntImag(), E);
8998 VisitIgnoredValue(E->getSubExpr());
8999 return Success(0, E);
9002 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9003 return Success(E->getPackLength(), E);
9006 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9007 return Success(E->getValue(), E);
9010 //===----------------------------------------------------------------------===//
9012 //===----------------------------------------------------------------------===//
9015 class FloatExprEvaluator
9016 : public ExprEvaluatorBase<FloatExprEvaluator> {
9019 FloatExprEvaluator(EvalInfo &info, APFloat &result)
9020 : ExprEvaluatorBaseTy(info), Result(result) {}
9022 bool Success(const APValue &V, const Expr *e) {
9023 Result = V.getFloat();
9027 bool ZeroInitialization(const Expr *E) {
9028 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9032 bool VisitCallExpr(const CallExpr *E);
9034 bool VisitUnaryOperator(const UnaryOperator *E);
9035 bool VisitBinaryOperator(const BinaryOperator *E);
9036 bool VisitFloatingLiteral(const FloatingLiteral *E);
9037 bool VisitCastExpr(const CastExpr *E);
9039 bool VisitUnaryReal(const UnaryOperator *E);
9040 bool VisitUnaryImag(const UnaryOperator *E);
9042 // FIXME: Missing: array subscript of vector, member of vector
9044 } // end anonymous namespace
9046 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9047 assert(E->isRValue() && E->getType()->isRealFloatingType());
9048 return FloatExprEvaluator(Info, Result).Visit(E);
9051 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9055 llvm::APFloat &Result) {
9056 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9057 if (!S) return false;
9059 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9063 // Treat empty strings as if they were zero.
9064 if (S->getString().empty())
9065 fill = llvm::APInt(32, 0);
9066 else if (S->getString().getAsInteger(0, fill))
9069 if (Context.getTargetInfo().isNan2008()) {
9071 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9073 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9075 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9076 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9077 // a different encoding to what became a standard in 2008, and for pre-
9078 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9079 // sNaN. This is now known as "legacy NaN" encoding.
9081 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9083 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9089 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9090 switch (E->getBuiltinCallee()) {
9092 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9094 case Builtin::BI__builtin_huge_val:
9095 case Builtin::BI__builtin_huge_valf:
9096 case Builtin::BI__builtin_huge_vall:
9097 case Builtin::BI__builtin_inf:
9098 case Builtin::BI__builtin_inff:
9099 case Builtin::BI__builtin_infl: {
9100 const llvm::fltSemantics &Sem =
9101 Info.Ctx.getFloatTypeSemantics(E->getType());
9102 Result = llvm::APFloat::getInf(Sem);
9106 case Builtin::BI__builtin_nans:
9107 case Builtin::BI__builtin_nansf:
9108 case Builtin::BI__builtin_nansl:
9109 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9114 case Builtin::BI__builtin_nan:
9115 case Builtin::BI__builtin_nanf:
9116 case Builtin::BI__builtin_nanl:
9117 // If this is __builtin_nan() turn this into a nan, otherwise we
9118 // can't constant fold it.
9119 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9124 case Builtin::BI__builtin_fabs:
9125 case Builtin::BI__builtin_fabsf:
9126 case Builtin::BI__builtin_fabsl:
9127 if (!EvaluateFloat(E->getArg(0), Result, Info))
9130 if (Result.isNegative())
9131 Result.changeSign();
9134 // FIXME: Builtin::BI__builtin_powi
9135 // FIXME: Builtin::BI__builtin_powif
9136 // FIXME: Builtin::BI__builtin_powil
9138 case Builtin::BI__builtin_copysign:
9139 case Builtin::BI__builtin_copysignf:
9140 case Builtin::BI__builtin_copysignl: {
9142 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9143 !EvaluateFloat(E->getArg(1), RHS, Info))
9145 Result.copySign(RHS);
9151 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9152 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9154 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9156 Result = CV.FloatReal;
9160 return Visit(E->getSubExpr());
9163 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9164 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9166 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9168 Result = CV.FloatImag;
9172 VisitIgnoredValue(E->getSubExpr());
9173 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9174 Result = llvm::APFloat::getZero(Sem);
9178 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9179 switch (E->getOpcode()) {
9180 default: return Error(E);
9182 return EvaluateFloat(E->getSubExpr(), Result, Info);
9184 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9186 Result.changeSign();
9191 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9192 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9193 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9196 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9197 if (!LHSOK && !Info.noteFailure())
9199 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9200 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9203 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9204 Result = E->getValue();
9208 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9209 const Expr* SubExpr = E->getSubExpr();
9211 switch (E->getCastKind()) {
9213 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9215 case CK_IntegralToFloating: {
9217 return EvaluateInteger(SubExpr, IntResult, Info) &&
9218 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9219 E->getType(), Result);
9222 case CK_FloatingCast: {
9223 if (!Visit(SubExpr))
9225 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9229 case CK_FloatingComplexToReal: {
9231 if (!EvaluateComplex(SubExpr, V, Info))
9233 Result = V.getComplexFloatReal();
9239 //===----------------------------------------------------------------------===//
9240 // Complex Evaluation (for float and integer)
9241 //===----------------------------------------------------------------------===//
9244 class ComplexExprEvaluator
9245 : public ExprEvaluatorBase<ComplexExprEvaluator> {
9246 ComplexValue &Result;
9249 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9250 : ExprEvaluatorBaseTy(info), Result(Result) {}
9252 bool Success(const APValue &V, const Expr *e) {
9257 bool ZeroInitialization(const Expr *E);
9259 //===--------------------------------------------------------------------===//
9261 //===--------------------------------------------------------------------===//
9263 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9264 bool VisitCastExpr(const CastExpr *E);
9265 bool VisitBinaryOperator(const BinaryOperator *E);
9266 bool VisitUnaryOperator(const UnaryOperator *E);
9267 bool VisitInitListExpr(const InitListExpr *E);
9269 } // end anonymous namespace
9271 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9273 assert(E->isRValue() && E->getType()->isAnyComplexType());
9274 return ComplexExprEvaluator(Info, Result).Visit(E);
9277 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9278 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9279 if (ElemTy->isRealFloatingType()) {
9280 Result.makeComplexFloat();
9281 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9282 Result.FloatReal = Zero;
9283 Result.FloatImag = Zero;
9285 Result.makeComplexInt();
9286 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9287 Result.IntReal = Zero;
9288 Result.IntImag = Zero;
9293 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9294 const Expr* SubExpr = E->getSubExpr();
9296 if (SubExpr->getType()->isRealFloatingType()) {
9297 Result.makeComplexFloat();
9298 APFloat &Imag = Result.FloatImag;
9299 if (!EvaluateFloat(SubExpr, Imag, Info))
9302 Result.FloatReal = APFloat(Imag.getSemantics());
9305 assert(SubExpr->getType()->isIntegerType() &&
9306 "Unexpected imaginary literal.");
9308 Result.makeComplexInt();
9309 APSInt &Imag = Result.IntImag;
9310 if (!EvaluateInteger(SubExpr, Imag, Info))
9313 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9318 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9320 switch (E->getCastKind()) {
9322 case CK_BaseToDerived:
9323 case CK_DerivedToBase:
9324 case CK_UncheckedDerivedToBase:
9327 case CK_ArrayToPointerDecay:
9328 case CK_FunctionToPointerDecay:
9329 case CK_NullToPointer:
9330 case CK_NullToMemberPointer:
9331 case CK_BaseToDerivedMemberPointer:
9332 case CK_DerivedToBaseMemberPointer:
9333 case CK_MemberPointerToBoolean:
9334 case CK_ReinterpretMemberPointer:
9335 case CK_ConstructorConversion:
9336 case CK_IntegralToPointer:
9337 case CK_PointerToIntegral:
9338 case CK_PointerToBoolean:
9340 case CK_VectorSplat:
9341 case CK_IntegralCast:
9342 case CK_BooleanToSignedIntegral:
9343 case CK_IntegralToBoolean:
9344 case CK_IntegralToFloating:
9345 case CK_FloatingToIntegral:
9346 case CK_FloatingToBoolean:
9347 case CK_FloatingCast:
9348 case CK_CPointerToObjCPointerCast:
9349 case CK_BlockPointerToObjCPointerCast:
9350 case CK_AnyPointerToBlockPointerCast:
9351 case CK_ObjCObjectLValueCast:
9352 case CK_FloatingComplexToReal:
9353 case CK_FloatingComplexToBoolean:
9354 case CK_IntegralComplexToReal:
9355 case CK_IntegralComplexToBoolean:
9356 case CK_ARCProduceObject:
9357 case CK_ARCConsumeObject:
9358 case CK_ARCReclaimReturnedObject:
9359 case CK_ARCExtendBlockObject:
9360 case CK_CopyAndAutoreleaseBlockObject:
9361 case CK_BuiltinFnToFnPtr:
9362 case CK_ZeroToOCLEvent:
9363 case CK_ZeroToOCLQueue:
9364 case CK_NonAtomicToAtomic:
9365 case CK_AddressSpaceConversion:
9366 case CK_IntToOCLSampler:
9367 llvm_unreachable("invalid cast kind for complex value");
9369 case CK_LValueToRValue:
9370 case CK_AtomicToNonAtomic:
9372 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9375 case CK_LValueBitCast:
9376 case CK_UserDefinedConversion:
9379 case CK_FloatingRealToComplex: {
9380 APFloat &Real = Result.FloatReal;
9381 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9384 Result.makeComplexFloat();
9385 Result.FloatImag = APFloat(Real.getSemantics());
9389 case CK_FloatingComplexCast: {
9390 if (!Visit(E->getSubExpr()))
9393 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9395 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9397 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9398 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9401 case CK_FloatingComplexToIntegralComplex: {
9402 if (!Visit(E->getSubExpr()))
9405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9408 Result.makeComplexInt();
9409 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9410 To, Result.IntReal) &&
9411 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9412 To, Result.IntImag);
9415 case CK_IntegralRealToComplex: {
9416 APSInt &Real = Result.IntReal;
9417 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9420 Result.makeComplexInt();
9421 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9425 case CK_IntegralComplexCast: {
9426 if (!Visit(E->getSubExpr()))
9429 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9431 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9433 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9434 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9438 case CK_IntegralComplexToFloatingComplex: {
9439 if (!Visit(E->getSubExpr()))
9442 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9444 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9445 Result.makeComplexFloat();
9446 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9447 To, Result.FloatReal) &&
9448 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9449 To, Result.FloatImag);
9453 llvm_unreachable("unknown cast resulting in complex value");
9456 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9457 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9458 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9460 // Track whether the LHS or RHS is real at the type system level. When this is
9461 // the case we can simplify our evaluation strategy.
9462 bool LHSReal = false, RHSReal = false;
9465 if (E->getLHS()->getType()->isRealFloatingType()) {
9467 APFloat &Real = Result.FloatReal;
9468 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9470 Result.makeComplexFloat();
9471 Result.FloatImag = APFloat(Real.getSemantics());
9474 LHSOK = Visit(E->getLHS());
9476 if (!LHSOK && !Info.noteFailure())
9480 if (E->getRHS()->getType()->isRealFloatingType()) {
9482 APFloat &Real = RHS.FloatReal;
9483 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9485 RHS.makeComplexFloat();
9486 RHS.FloatImag = APFloat(Real.getSemantics());
9487 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9490 assert(!(LHSReal && RHSReal) &&
9491 "Cannot have both operands of a complex operation be real.");
9492 switch (E->getOpcode()) {
9493 default: return Error(E);
9495 if (Result.isComplexFloat()) {
9496 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9497 APFloat::rmNearestTiesToEven);
9499 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9501 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9502 APFloat::rmNearestTiesToEven);
9504 Result.getComplexIntReal() += RHS.getComplexIntReal();
9505 Result.getComplexIntImag() += RHS.getComplexIntImag();
9509 if (Result.isComplexFloat()) {
9510 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9511 APFloat::rmNearestTiesToEven);
9513 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9514 Result.getComplexFloatImag().changeSign();
9515 } else if (!RHSReal) {
9516 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9517 APFloat::rmNearestTiesToEven);
9520 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9521 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9525 if (Result.isComplexFloat()) {
9526 // This is an implementation of complex multiplication according to the
9527 // constraints laid out in C11 Annex G. The implemention uses the
9528 // following naming scheme:
9529 // (a + ib) * (c + id)
9530 ComplexValue LHS = Result;
9531 APFloat &A = LHS.getComplexFloatReal();
9532 APFloat &B = LHS.getComplexFloatImag();
9533 APFloat &C = RHS.getComplexFloatReal();
9534 APFloat &D = RHS.getComplexFloatImag();
9535 APFloat &ResR = Result.getComplexFloatReal();
9536 APFloat &ResI = Result.getComplexFloatImag();
9538 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9541 } else if (RHSReal) {
9545 // In the fully general case, we need to handle NaNs and infinities
9553 if (ResR.isNaN() && ResI.isNaN()) {
9554 bool Recalc = false;
9555 if (A.isInfinity() || B.isInfinity()) {
9556 A = APFloat::copySign(
9557 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9558 B = APFloat::copySign(
9559 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9561 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9563 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9566 if (C.isInfinity() || D.isInfinity()) {
9567 C = APFloat::copySign(
9568 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9569 D = APFloat::copySign(
9570 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9572 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9574 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9577 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9578 AD.isInfinity() || BC.isInfinity())) {
9580 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9582 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9584 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9586 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9590 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9591 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9596 ComplexValue LHS = Result;
9597 Result.getComplexIntReal() =
9598 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9599 LHS.getComplexIntImag() * RHS.getComplexIntImag());
9600 Result.getComplexIntImag() =
9601 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9602 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9606 if (Result.isComplexFloat()) {
9607 // This is an implementation of complex division according to the
9608 // constraints laid out in C11 Annex G. The implemention uses the
9609 // following naming scheme:
9610 // (a + ib) / (c + id)
9611 ComplexValue LHS = Result;
9612 APFloat &A = LHS.getComplexFloatReal();
9613 APFloat &B = LHS.getComplexFloatImag();
9614 APFloat &C = RHS.getComplexFloatReal();
9615 APFloat &D = RHS.getComplexFloatImag();
9616 APFloat &ResR = Result.getComplexFloatReal();
9617 APFloat &ResI = Result.getComplexFloatImag();
9623 // No real optimizations we can do here, stub out with zero.
9624 B = APFloat::getZero(A.getSemantics());
9627 APFloat MaxCD = maxnum(abs(C), abs(D));
9628 if (MaxCD.isFinite()) {
9629 DenomLogB = ilogb(MaxCD);
9630 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9631 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9633 APFloat Denom = C * C + D * D;
9634 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9635 APFloat::rmNearestTiesToEven);
9636 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9637 APFloat::rmNearestTiesToEven);
9638 if (ResR.isNaN() && ResI.isNaN()) {
9639 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9640 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9641 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9642 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9644 A = APFloat::copySign(
9645 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9646 B = APFloat::copySign(
9647 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9648 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9649 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9650 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9651 C = APFloat::copySign(
9652 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9653 D = APFloat::copySign(
9654 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9655 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9656 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9661 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9662 return Error(E, diag::note_expr_divide_by_zero);
9664 ComplexValue LHS = Result;
9665 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9666 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9667 Result.getComplexIntReal() =
9668 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9669 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9670 Result.getComplexIntImag() =
9671 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9672 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9680 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9681 // Get the operand value into 'Result'.
9682 if (!Visit(E->getSubExpr()))
9685 switch (E->getOpcode()) {
9691 // The result is always just the subexpr.
9694 if (Result.isComplexFloat()) {
9695 Result.getComplexFloatReal().changeSign();
9696 Result.getComplexFloatImag().changeSign();
9699 Result.getComplexIntReal() = -Result.getComplexIntReal();
9700 Result.getComplexIntImag() = -Result.getComplexIntImag();
9704 if (Result.isComplexFloat())
9705 Result.getComplexFloatImag().changeSign();
9707 Result.getComplexIntImag() = -Result.getComplexIntImag();
9712 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9713 if (E->getNumInits() == 2) {
9714 if (E->getType()->isComplexType()) {
9715 Result.makeComplexFloat();
9716 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9718 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9721 Result.makeComplexInt();
9722 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9724 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9729 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9732 //===----------------------------------------------------------------------===//
9733 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9734 // implicit conversion.
9735 //===----------------------------------------------------------------------===//
9738 class AtomicExprEvaluator :
9739 public ExprEvaluatorBase<AtomicExprEvaluator> {
9743 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9744 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9746 bool Success(const APValue &V, const Expr *E) {
9751 bool ZeroInitialization(const Expr *E) {
9752 ImplicitValueInitExpr VIE(
9753 E->getType()->castAs<AtomicType>()->getValueType());
9754 // For atomic-qualified class (and array) types in C++, initialize the
9755 // _Atomic-wrapped subobject directly, in-place.
9756 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9757 : Evaluate(Result, Info, &VIE);
9760 bool VisitCastExpr(const CastExpr *E) {
9761 switch (E->getCastKind()) {
9763 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9764 case CK_NonAtomicToAtomic:
9765 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9766 : Evaluate(Result, Info, E->getSubExpr());
9770 } // end anonymous namespace
9772 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9774 assert(E->isRValue() && E->getType()->isAtomicType());
9775 return AtomicExprEvaluator(Info, This, Result).Visit(E);
9778 //===----------------------------------------------------------------------===//
9779 // Void expression evaluation, primarily for a cast to void on the LHS of a
9781 //===----------------------------------------------------------------------===//
9784 class VoidExprEvaluator
9785 : public ExprEvaluatorBase<VoidExprEvaluator> {
9787 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9789 bool Success(const APValue &V, const Expr *e) { return true; }
9791 bool VisitCastExpr(const CastExpr *E) {
9792 switch (E->getCastKind()) {
9794 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9796 VisitIgnoredValue(E->getSubExpr());
9801 bool VisitCallExpr(const CallExpr *E) {
9802 switch (E->getBuiltinCallee()) {
9804 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9805 case Builtin::BI__assume:
9806 case Builtin::BI__builtin_assume:
9807 // The argument is not evaluated!
9812 } // end anonymous namespace
9814 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9815 assert(E->isRValue() && E->getType()->isVoidType());
9816 return VoidExprEvaluator(Info).Visit(E);
9819 //===----------------------------------------------------------------------===//
9820 // Top level Expr::EvaluateAsRValue method.
9821 //===----------------------------------------------------------------------===//
9823 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9824 // In C, function designators are not lvalues, but we evaluate them as if they
9826 QualType T = E->getType();
9827 if (E->isGLValue() || T->isFunctionType()) {
9829 if (!EvaluateLValue(E, LV, Info))
9831 LV.moveInto(Result);
9832 } else if (T->isVectorType()) {
9833 if (!EvaluateVector(E, Result, Info))
9835 } else if (T->isIntegralOrEnumerationType()) {
9836 if (!IntExprEvaluator(Info, Result).Visit(E))
9838 } else if (T->hasPointerRepresentation()) {
9840 if (!EvaluatePointer(E, LV, Info))
9842 LV.moveInto(Result);
9843 } else if (T->isRealFloatingType()) {
9844 llvm::APFloat F(0.0);
9845 if (!EvaluateFloat(E, F, Info))
9847 Result = APValue(F);
9848 } else if (T->isAnyComplexType()) {
9850 if (!EvaluateComplex(E, C, Info))
9853 } else if (T->isMemberPointerType()) {
9855 if (!EvaluateMemberPointer(E, P, Info))
9859 } else if (T->isArrayType()) {
9861 LV.set(E, Info.CurrentCall->Index);
9862 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9863 if (!EvaluateArray(E, LV, Value, Info))
9866 } else if (T->isRecordType()) {
9868 LV.set(E, Info.CurrentCall->Index);
9869 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9870 if (!EvaluateRecord(E, LV, Value, Info))
9873 } else if (T->isVoidType()) {
9874 if (!Info.getLangOpts().CPlusPlus11)
9875 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9877 if (!EvaluateVoid(E, Info))
9879 } else if (T->isAtomicType()) {
9880 QualType Unqual = T.getAtomicUnqualifiedType();
9881 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9883 LV.set(E, Info.CurrentCall->Index);
9884 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9885 if (!EvaluateAtomic(E, &LV, Value, Info))
9888 if (!EvaluateAtomic(E, nullptr, Result, Info))
9891 } else if (Info.getLangOpts().CPlusPlus11) {
9892 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9895 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9902 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9903 /// cases, the in-place evaluation is essential, since later initializers for
9904 /// an object can indirectly refer to subobjects which were initialized earlier.
9905 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9906 const Expr *E, bool AllowNonLiteralTypes) {
9907 assert(!E->isValueDependent());
9909 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9912 if (E->isRValue()) {
9913 // Evaluate arrays and record types in-place, so that later initializers can
9914 // refer to earlier-initialized members of the object.
9915 QualType T = E->getType();
9916 if (T->isArrayType())
9917 return EvaluateArray(E, This, Result, Info);
9918 else if (T->isRecordType())
9919 return EvaluateRecord(E, This, Result, Info);
9920 else if (T->isAtomicType()) {
9921 QualType Unqual = T.getAtomicUnqualifiedType();
9922 if (Unqual->isArrayType() || Unqual->isRecordType())
9923 return EvaluateAtomic(E, &This, Result, Info);
9927 // For any other type, in-place evaluation is unimportant.
9928 return Evaluate(Result, Info, E);
9931 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9932 /// lvalue-to-rvalue cast if it is an lvalue.
9933 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9934 if (E->getType().isNull())
9937 if (!CheckLiteralType(Info, E))
9940 if (!::Evaluate(Result, Info, E))
9943 if (E->isGLValue()) {
9945 LV.setFrom(Info.Ctx, Result);
9946 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9950 // Check this core constant expression is a constant expression.
9951 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9954 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9955 const ASTContext &Ctx, bool &IsConst) {
9956 // Fast-path evaluations of integer literals, since we sometimes see files
9957 // containing vast quantities of these.
9958 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9959 Result.Val = APValue(APSInt(L->getValue(),
9960 L->getType()->isUnsignedIntegerType()));
9965 // This case should be rare, but we need to check it before we check on
9967 if (Exp->getType().isNull()) {
9972 // FIXME: Evaluating values of large array and record types can cause
9973 // performance problems. Only do so in C++11 for now.
9974 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9975 Exp->getType()->isRecordType()) &&
9976 !Ctx.getLangOpts().CPlusPlus11) {
9984 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9985 /// any crazy technique (that has nothing to do with language standards) that
9986 /// we want to. If this function returns true, it returns the folded constant
9987 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9988 /// will be applied to the result.
9989 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9991 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9994 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9995 return ::EvaluateAsRValue(Info, this, Result.Val);
9998 bool Expr::EvaluateAsBooleanCondition(bool &Result,
9999 const ASTContext &Ctx) const {
10000 EvalResult Scratch;
10001 return EvaluateAsRValue(Scratch, Ctx) &&
10002 HandleConversionToBool(Scratch.Val, Result);
10005 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10006 Expr::SideEffectsKind SEK) {
10007 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10008 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10011 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10012 SideEffectsKind AllowSideEffects) const {
10013 if (!getType()->isIntegralOrEnumerationType())
10016 EvalResult ExprResult;
10017 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10018 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10021 Result = ExprResult.Val.getInt();
10025 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10026 SideEffectsKind AllowSideEffects) const {
10027 if (!getType()->isRealFloatingType())
10030 EvalResult ExprResult;
10031 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10032 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10035 Result = ExprResult.Val.getFloat();
10039 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10040 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10043 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10044 !CheckLValueConstantExpression(Info, getExprLoc(),
10045 Ctx.getLValueReferenceType(getType()), LV))
10048 LV.moveInto(Result.Val);
10052 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10054 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10055 // FIXME: Evaluating initializers for large array and record types can cause
10056 // performance problems. Only do so in C++11 for now.
10057 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10058 !Ctx.getLangOpts().CPlusPlus11)
10061 Expr::EvalStatus EStatus;
10062 EStatus.Diag = &Notes;
10064 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10065 ? EvalInfo::EM_ConstantExpression
10066 : EvalInfo::EM_ConstantFold);
10067 InitInfo.setEvaluatingDecl(VD, Value);
10072 // C++11 [basic.start.init]p2:
10073 // Variables with static storage duration or thread storage duration shall be
10074 // zero-initialized before any other initialization takes place.
10075 // This behavior is not present in C.
10076 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10077 !VD->getType()->isReferenceType()) {
10078 ImplicitValueInitExpr VIE(VD->getType());
10079 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10080 /*AllowNonLiteralTypes=*/true))
10084 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10085 /*AllowNonLiteralTypes=*/true) ||
10086 EStatus.HasSideEffects)
10089 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10093 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10094 /// constant folded, but discard the result.
10095 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10097 return EvaluateAsRValue(Result, Ctx) &&
10098 !hasUnacceptableSideEffect(Result, SEK);
10101 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10102 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10103 EvalResult EvalResult;
10104 EvalResult.Diag = Diag;
10105 bool Result = EvaluateAsRValue(EvalResult, Ctx);
10107 assert(Result && "Could not evaluate expression");
10108 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10110 return EvalResult.Val.getInt();
10113 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10115 EvalResult EvalResult;
10116 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10117 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10118 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10122 bool Expr::EvalResult::isGlobalLValue() const {
10123 assert(Val.isLValue());
10124 return IsGlobalLValue(Val.getLValueBase());
10128 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10129 /// an integer constant expression.
10131 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10134 // CheckICE - This function does the fundamental ICE checking: the returned
10135 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10136 // and a (possibly null) SourceLocation indicating the location of the problem.
10138 // Note that to reduce code duplication, this helper does no evaluation
10139 // itself; the caller checks whether the expression is evaluatable, and
10140 // in the rare cases where CheckICE actually cares about the evaluated
10141 // value, it calls into Evaluate.
10146 /// This expression is an ICE.
10148 /// This expression is not an ICE, but if it isn't evaluated, it's
10149 /// a legal subexpression for an ICE. This return value is used to handle
10150 /// the comma operator in C99 mode, and non-constant subexpressions.
10151 IK_ICEIfUnevaluated,
10152 /// This expression is not an ICE, and is not a legal subexpression for one.
10158 SourceLocation Loc;
10160 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10165 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10167 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10169 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10170 Expr::EvalResult EVResult;
10171 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10172 !EVResult.Val.isInt())
10173 return ICEDiag(IK_NotICE, E->getLocStart());
10178 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10179 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10180 if (!E->getType()->isIntegralOrEnumerationType())
10181 return ICEDiag(IK_NotICE, E->getLocStart());
10183 switch (E->getStmtClass()) {
10184 #define ABSTRACT_STMT(Node)
10185 #define STMT(Node, Base) case Expr::Node##Class:
10186 #define EXPR(Node, Base)
10187 #include "clang/AST/StmtNodes.inc"
10188 case Expr::PredefinedExprClass:
10189 case Expr::FloatingLiteralClass:
10190 case Expr::ImaginaryLiteralClass:
10191 case Expr::StringLiteralClass:
10192 case Expr::ArraySubscriptExprClass:
10193 case Expr::OMPArraySectionExprClass:
10194 case Expr::MemberExprClass:
10195 case Expr::CompoundAssignOperatorClass:
10196 case Expr::CompoundLiteralExprClass:
10197 case Expr::ExtVectorElementExprClass:
10198 case Expr::DesignatedInitExprClass:
10199 case Expr::ArrayInitLoopExprClass:
10200 case Expr::ArrayInitIndexExprClass:
10201 case Expr::NoInitExprClass:
10202 case Expr::DesignatedInitUpdateExprClass:
10203 case Expr::ImplicitValueInitExprClass:
10204 case Expr::ParenListExprClass:
10205 case Expr::VAArgExprClass:
10206 case Expr::AddrLabelExprClass:
10207 case Expr::StmtExprClass:
10208 case Expr::CXXMemberCallExprClass:
10209 case Expr::CUDAKernelCallExprClass:
10210 case Expr::CXXDynamicCastExprClass:
10211 case Expr::CXXTypeidExprClass:
10212 case Expr::CXXUuidofExprClass:
10213 case Expr::MSPropertyRefExprClass:
10214 case Expr::MSPropertySubscriptExprClass:
10215 case Expr::CXXNullPtrLiteralExprClass:
10216 case Expr::UserDefinedLiteralClass:
10217 case Expr::CXXThisExprClass:
10218 case Expr::CXXThrowExprClass:
10219 case Expr::CXXNewExprClass:
10220 case Expr::CXXDeleteExprClass:
10221 case Expr::CXXPseudoDestructorExprClass:
10222 case Expr::UnresolvedLookupExprClass:
10223 case Expr::TypoExprClass:
10224 case Expr::DependentScopeDeclRefExprClass:
10225 case Expr::CXXConstructExprClass:
10226 case Expr::CXXInheritedCtorInitExprClass:
10227 case Expr::CXXStdInitializerListExprClass:
10228 case Expr::CXXBindTemporaryExprClass:
10229 case Expr::ExprWithCleanupsClass:
10230 case Expr::CXXTemporaryObjectExprClass:
10231 case Expr::CXXUnresolvedConstructExprClass:
10232 case Expr::CXXDependentScopeMemberExprClass:
10233 case Expr::UnresolvedMemberExprClass:
10234 case Expr::ObjCStringLiteralClass:
10235 case Expr::ObjCBoxedExprClass:
10236 case Expr::ObjCArrayLiteralClass:
10237 case Expr::ObjCDictionaryLiteralClass:
10238 case Expr::ObjCEncodeExprClass:
10239 case Expr::ObjCMessageExprClass:
10240 case Expr::ObjCSelectorExprClass:
10241 case Expr::ObjCProtocolExprClass:
10242 case Expr::ObjCIvarRefExprClass:
10243 case Expr::ObjCPropertyRefExprClass:
10244 case Expr::ObjCSubscriptRefExprClass:
10245 case Expr::ObjCIsaExprClass:
10246 case Expr::ObjCAvailabilityCheckExprClass:
10247 case Expr::ShuffleVectorExprClass:
10248 case Expr::ConvertVectorExprClass:
10249 case Expr::BlockExprClass:
10250 case Expr::NoStmtClass:
10251 case Expr::OpaqueValueExprClass:
10252 case Expr::PackExpansionExprClass:
10253 case Expr::SubstNonTypeTemplateParmPackExprClass:
10254 case Expr::FunctionParmPackExprClass:
10255 case Expr::AsTypeExprClass:
10256 case Expr::ObjCIndirectCopyRestoreExprClass:
10257 case Expr::MaterializeTemporaryExprClass:
10258 case Expr::PseudoObjectExprClass:
10259 case Expr::AtomicExprClass:
10260 case Expr::LambdaExprClass:
10261 case Expr::CXXFoldExprClass:
10262 case Expr::CoawaitExprClass:
10263 case Expr::DependentCoawaitExprClass:
10264 case Expr::CoyieldExprClass:
10265 return ICEDiag(IK_NotICE, E->getLocStart());
10267 case Expr::InitListExprClass: {
10268 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10269 // form "T x = { a };" is equivalent to "T x = a;".
10270 // Unless we're initializing a reference, T is a scalar as it is known to be
10271 // of integral or enumeration type.
10273 if (cast<InitListExpr>(E)->getNumInits() == 1)
10274 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10275 return ICEDiag(IK_NotICE, E->getLocStart());
10278 case Expr::SizeOfPackExprClass:
10279 case Expr::GNUNullExprClass:
10280 // GCC considers the GNU __null value to be an integral constant expression.
10283 case Expr::SubstNonTypeTemplateParmExprClass:
10285 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10287 case Expr::ParenExprClass:
10288 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10289 case Expr::GenericSelectionExprClass:
10290 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10291 case Expr::IntegerLiteralClass:
10292 case Expr::CharacterLiteralClass:
10293 case Expr::ObjCBoolLiteralExprClass:
10294 case Expr::CXXBoolLiteralExprClass:
10295 case Expr::CXXScalarValueInitExprClass:
10296 case Expr::TypeTraitExprClass:
10297 case Expr::ArrayTypeTraitExprClass:
10298 case Expr::ExpressionTraitExprClass:
10299 case Expr::CXXNoexceptExprClass:
10301 case Expr::CallExprClass:
10302 case Expr::CXXOperatorCallExprClass: {
10303 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10304 // constant expressions, but they can never be ICEs because an ICE cannot
10305 // contain an operand of (pointer to) function type.
10306 const CallExpr *CE = cast<CallExpr>(E);
10307 if (CE->getBuiltinCallee())
10308 return CheckEvalInICE(E, Ctx);
10309 return ICEDiag(IK_NotICE, E->getLocStart());
10311 case Expr::DeclRefExprClass: {
10312 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10314 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10315 if (Ctx.getLangOpts().CPlusPlus &&
10316 D && IsConstNonVolatile(D->getType())) {
10317 // Parameter variables are never constants. Without this check,
10318 // getAnyInitializer() can find a default argument, which leads
10320 if (isa<ParmVarDecl>(D))
10321 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10324 // A variable of non-volatile const-qualified integral or enumeration
10325 // type initialized by an ICE can be used in ICEs.
10326 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10327 if (!Dcl->getType()->isIntegralOrEnumerationType())
10328 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10331 // Look for a declaration of this variable that has an initializer, and
10332 // check whether it is an ICE.
10333 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10336 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10339 return ICEDiag(IK_NotICE, E->getLocStart());
10341 case Expr::UnaryOperatorClass: {
10342 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10343 switch (Exp->getOpcode()) {
10351 // C99 6.6/3 allows increment and decrement within unevaluated
10352 // subexpressions of constant expressions, but they can never be ICEs
10353 // because an ICE cannot contain an lvalue operand.
10354 return ICEDiag(IK_NotICE, E->getLocStart());
10362 return CheckICE(Exp->getSubExpr(), Ctx);
10365 // OffsetOf falls through here.
10368 case Expr::OffsetOfExprClass: {
10369 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10370 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10371 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10372 // compliance: we should warn earlier for offsetof expressions with
10373 // array subscripts that aren't ICEs, and if the array subscripts
10374 // are ICEs, the value of the offsetof must be an integer constant.
10375 return CheckEvalInICE(E, Ctx);
10377 case Expr::UnaryExprOrTypeTraitExprClass: {
10378 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10379 if ((Exp->getKind() == UETT_SizeOf) &&
10380 Exp->getTypeOfArgument()->isVariableArrayType())
10381 return ICEDiag(IK_NotICE, E->getLocStart());
10384 case Expr::BinaryOperatorClass: {
10385 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10386 switch (Exp->getOpcode()) {
10400 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10401 // constant expressions, but they can never be ICEs because an ICE cannot
10402 // contain an lvalue operand.
10403 return ICEDiag(IK_NotICE, E->getLocStart());
10422 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10423 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10424 if (Exp->getOpcode() == BO_Div ||
10425 Exp->getOpcode() == BO_Rem) {
10426 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10427 // we don't evaluate one.
10428 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10429 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10431 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10432 if (REval.isSigned() && REval.isAllOnesValue()) {
10433 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10434 if (LEval.isMinSignedValue())
10435 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10439 if (Exp->getOpcode() == BO_Comma) {
10440 if (Ctx.getLangOpts().C99) {
10441 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10442 // if it isn't evaluated.
10443 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10444 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10446 // In both C89 and C++, commas in ICEs are illegal.
10447 return ICEDiag(IK_NotICE, E->getLocStart());
10450 return Worst(LHSResult, RHSResult);
10454 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10455 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10456 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10457 // Rare case where the RHS has a comma "side-effect"; we need
10458 // to actually check the condition to see whether the side
10459 // with the comma is evaluated.
10460 if ((Exp->getOpcode() == BO_LAnd) !=
10461 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10466 return Worst(LHSResult, RHSResult);
10471 case Expr::ImplicitCastExprClass:
10472 case Expr::CStyleCastExprClass:
10473 case Expr::CXXFunctionalCastExprClass:
10474 case Expr::CXXStaticCastExprClass:
10475 case Expr::CXXReinterpretCastExprClass:
10476 case Expr::CXXConstCastExprClass:
10477 case Expr::ObjCBridgedCastExprClass: {
10478 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10479 if (isa<ExplicitCastExpr>(E)) {
10480 if (const FloatingLiteral *FL
10481 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10482 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10483 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10484 APSInt IgnoredVal(DestWidth, !DestSigned);
10486 // If the value does not fit in the destination type, the behavior is
10487 // undefined, so we are not required to treat it as a constant
10489 if (FL->getValue().convertToInteger(IgnoredVal,
10490 llvm::APFloat::rmTowardZero,
10491 &Ignored) & APFloat::opInvalidOp)
10492 return ICEDiag(IK_NotICE, E->getLocStart());
10496 switch (cast<CastExpr>(E)->getCastKind()) {
10497 case CK_LValueToRValue:
10498 case CK_AtomicToNonAtomic:
10499 case CK_NonAtomicToAtomic:
10501 case CK_IntegralToBoolean:
10502 case CK_IntegralCast:
10503 return CheckICE(SubExpr, Ctx);
10505 return ICEDiag(IK_NotICE, E->getLocStart());
10508 case Expr::BinaryConditionalOperatorClass: {
10509 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10510 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10511 if (CommonResult.Kind == IK_NotICE) return CommonResult;
10512 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10513 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10514 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10515 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10516 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10517 return FalseResult;
10519 case Expr::ConditionalOperatorClass: {
10520 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10521 // If the condition (ignoring parens) is a __builtin_constant_p call,
10522 // then only the true side is actually considered in an integer constant
10523 // expression, and it is fully evaluated. This is an important GNU
10524 // extension. See GCC PR38377 for discussion.
10525 if (const CallExpr *CallCE
10526 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10527 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10528 return CheckEvalInICE(E, Ctx);
10529 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10530 if (CondResult.Kind == IK_NotICE)
10533 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10534 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10536 if (TrueResult.Kind == IK_NotICE)
10538 if (FalseResult.Kind == IK_NotICE)
10539 return FalseResult;
10540 if (CondResult.Kind == IK_ICEIfUnevaluated)
10542 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10544 // Rare case where the diagnostics depend on which side is evaluated
10545 // Note that if we get here, CondResult is 0, and at least one of
10546 // TrueResult and FalseResult is non-zero.
10547 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10548 return FalseResult;
10551 case Expr::CXXDefaultArgExprClass:
10552 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10553 case Expr::CXXDefaultInitExprClass:
10554 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10555 case Expr::ChooseExprClass: {
10556 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10560 llvm_unreachable("Invalid StmtClass!");
10563 /// Evaluate an expression as a C++11 integral constant expression.
10564 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10566 llvm::APSInt *Value,
10567 SourceLocation *Loc) {
10568 if (!E->getType()->isIntegralOrEnumerationType()) {
10569 if (Loc) *Loc = E->getExprLoc();
10574 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10577 if (!Result.isInt()) {
10578 if (Loc) *Loc = E->getExprLoc();
10582 if (Value) *Value = Result.getInt();
10586 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10587 SourceLocation *Loc) const {
10588 if (Ctx.getLangOpts().CPlusPlus11)
10589 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10591 ICEDiag D = CheckICE(this, Ctx);
10592 if (D.Kind != IK_ICE) {
10593 if (Loc) *Loc = D.Loc;
10599 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10600 SourceLocation *Loc, bool isEvaluated) const {
10601 if (Ctx.getLangOpts().CPlusPlus11)
10602 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10604 if (!isIntegerConstantExpr(Ctx, Loc))
10606 // The only possible side-effects here are due to UB discovered in the
10607 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10608 // required to treat the expression as an ICE, so we produce the folded
10610 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10611 llvm_unreachable("ICE cannot be evaluated!");
10615 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10616 return CheckICE(this, Ctx).Kind == IK_ICE;
10619 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10620 SourceLocation *Loc) const {
10621 // We support this checking in C++98 mode in order to diagnose compatibility
10623 assert(Ctx.getLangOpts().CPlusPlus);
10625 // Build evaluation settings.
10626 Expr::EvalStatus Status;
10627 SmallVector<PartialDiagnosticAt, 8> Diags;
10628 Status.Diag = &Diags;
10629 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10632 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10634 if (!Diags.empty()) {
10635 IsConstExpr = false;
10636 if (Loc) *Loc = Diags[0].first;
10637 } else if (!IsConstExpr) {
10638 // FIXME: This shouldn't happen.
10639 if (Loc) *Loc = getExprLoc();
10642 return IsConstExpr;
10645 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10646 const FunctionDecl *Callee,
10647 ArrayRef<const Expr*> Args,
10648 const Expr *This) const {
10649 Expr::EvalStatus Status;
10650 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10653 const LValue *ThisPtr = nullptr;
10656 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10657 assert(MD && "Don't provide `this` for non-methods.");
10658 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10660 if (EvaluateObjectArgument(Info, This, ThisVal))
10661 ThisPtr = &ThisVal;
10662 if (Info.EvalStatus.HasSideEffects)
10666 ArgVector ArgValues(Args.size());
10667 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10669 if ((*I)->isValueDependent() ||
10670 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10671 // If evaluation fails, throw away the argument entirely.
10672 ArgValues[I - Args.begin()] = APValue();
10673 if (Info.EvalStatus.HasSideEffects)
10677 // Build fake call to Callee.
10678 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10680 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10683 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10685 PartialDiagnosticAt> &Diags) {
10686 // FIXME: It would be useful to check constexpr function templates, but at the
10687 // moment the constant expression evaluator cannot cope with the non-rigorous
10688 // ASTs which we build for dependent expressions.
10689 if (FD->isDependentContext())
10692 Expr::EvalStatus Status;
10693 Status.Diag = &Diags;
10695 EvalInfo Info(FD->getASTContext(), Status,
10696 EvalInfo::EM_PotentialConstantExpression);
10698 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10699 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10701 // Fabricate an arbitrary expression on the stack and pretend that it
10702 // is a temporary being used as the 'this' pointer.
10704 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10705 This.set(&VIE, Info.CurrentCall->Index);
10707 ArrayRef<const Expr*> Args;
10710 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10711 // Evaluate the call as a constant initializer, to allow the construction
10712 // of objects of non-literal types.
10713 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10714 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10716 SourceLocation Loc = FD->getLocation();
10717 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10718 Args, FD->getBody(), Info, Scratch, nullptr);
10721 return Diags.empty();
10724 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10725 const FunctionDecl *FD,
10727 PartialDiagnosticAt> &Diags) {
10728 Expr::EvalStatus Status;
10729 Status.Diag = &Diags;
10731 EvalInfo Info(FD->getASTContext(), Status,
10732 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10734 // Fabricate a call stack frame to give the arguments a plausible cover story.
10735 ArrayRef<const Expr*> Args;
10736 ArgVector ArgValues(0);
10737 bool Success = EvaluateArgs(Args, ArgValues, Info);
10740 "Failed to set up arguments for potential constant evaluation");
10741 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10743 APValue ResultScratch;
10744 Evaluate(ResultScratch, Info, E);
10745 return Diags.empty();
10748 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10749 unsigned Type) const {
10750 if (!getType()->isPointerType())
10753 Expr::EvalStatus Status;
10754 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10755 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);