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/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/RecordLayout.h"
42 #include "clang/AST/StmtVisitor.h"
43 #include "clang/AST/TypeLoc.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.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
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 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
131 MostDerivedLength = I + 1;
132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
135 MostDerivedLength = I + 1;
137 // Path[I] describes a base class.
141 return MostDerivedLength;
144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
147 CSK_This, CSK_Real, CSK_Imag
150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
160 /// The length of the path to the most-derived object of which this is a
162 unsigned MostDerivedPathLength : 30;
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
171 typedef APValue::LValuePathEntry PathEntry;
173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
176 SubobjectDesignator() : Invalid(true) {}
178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
206 if (MostDerivedArraySize &&
207 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
212 /// Check that this refers to a valid subobject.
213 bool isValidSubobject() const {
216 return !isOnePastTheEnd();
218 /// Check that this refers to a valid subobject, and if not, produce a
219 /// relevant diagnostic and set the designator as invalid.
220 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222 /// Update this designator to refer to the first element within this array.
223 void addArrayUnchecked(const ConstantArrayType *CAT) {
225 Entry.ArrayIndex = 0;
226 Entries.push_back(Entry);
228 // This is a most-derived object.
229 MostDerivedType = CAT->getElementType();
230 MostDerivedArraySize = CAT->getSize().getZExtValue();
231 MostDerivedPathLength = Entries.size();
233 /// Update this designator to refer to the given base or member of this
235 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
237 APValue::BaseOrMemberType Value(D, Virtual);
238 Entry.BaseOrMember = Value.getOpaqueValue();
239 Entries.push_back(Entry);
241 // If this isn't a base class, it's a new most-derived object.
242 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
243 MostDerivedType = FD->getType();
244 MostDerivedArraySize = 0;
245 MostDerivedPathLength = Entries.size();
248 /// Update this designator to refer to the given complex component.
249 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 Entry.ArrayIndex = Imag;
252 Entries.push_back(Entry);
254 // This is technically a most-derived object, though in practice this
255 // is unlikely to matter.
256 MostDerivedType = EltTy;
257 MostDerivedArraySize = 2;
258 MostDerivedPathLength = Entries.size();
260 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
261 /// Add N to the address of this subobject.
262 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
264 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
265 Entries.back().ArrayIndex += N;
266 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
267 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
272 // [expr.add]p4: For the purposes of these operators, a pointer to a
273 // nonarray object behaves the same as a pointer to the first element of
274 // an array of length one with the type of the object as its element type.
275 if (IsOnePastTheEnd && N == (uint64_t)-1)
276 IsOnePastTheEnd = false;
277 else if (!IsOnePastTheEnd && N == 1)
278 IsOnePastTheEnd = true;
280 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
286 /// A stack frame in the constexpr call stack.
287 struct CallStackFrame {
290 /// Parent - The caller of this stack frame.
291 CallStackFrame *Caller;
293 /// CallLoc - The location of the call expression for this call.
294 SourceLocation CallLoc;
296 /// Callee - The function which was called.
297 const FunctionDecl *Callee;
299 /// Index - The call index of this call.
302 /// This - The binding for the this pointer in this call, if any.
305 /// Arguments - Parameter bindings for this function call, indexed by
306 /// parameters' function scope indices.
309 // Note that we intentionally use std::map here so that references to
310 // values are stable.
311 typedef std::map<const void*, APValue> MapTy;
312 typedef MapTy::const_iterator temp_iterator;
313 /// Temporaries - Temporary lvalues materialized within this stack frame.
316 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
317 const FunctionDecl *Callee, const LValue *This,
321 APValue *getTemporary(const void *Key) {
322 MapTy::iterator I = Temporaries.find(Key);
323 return I == Temporaries.end() ? 0 : &I->second;
325 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
328 /// Temporarily override 'this'.
329 class ThisOverrideRAII {
331 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
332 : Frame(Frame), OldThis(Frame.This) {
334 Frame.This = NewThis;
336 ~ThisOverrideRAII() {
337 Frame.This = OldThis;
340 CallStackFrame &Frame;
341 const LValue *OldThis;
344 /// A partial diagnostic which we might know in advance that we are not going
346 class OptionalDiagnostic {
347 PartialDiagnostic *Diag;
350 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
353 OptionalDiagnostic &operator<<(const T &v) {
359 OptionalDiagnostic &operator<<(const APSInt &I) {
361 SmallVector<char, 32> Buffer;
363 *Diag << StringRef(Buffer.data(), Buffer.size());
368 OptionalDiagnostic &operator<<(const APFloat &F) {
370 // FIXME: Force the precision of the source value down so we don't
371 // print digits which are usually useless (we don't really care here if
372 // we truncate a digit by accident in edge cases). Ideally,
373 // APFloat::toString would automatically print the shortest
374 // representation which rounds to the correct value, but it's a bit
375 // tricky to implement.
377 llvm::APFloat::semanticsPrecision(F.getSemantics());
378 precision = (precision * 59 + 195) / 196;
379 SmallVector<char, 32> Buffer;
380 F.toString(Buffer, precision);
381 *Diag << StringRef(Buffer.data(), Buffer.size());
387 /// A cleanup, and a flag indicating whether it is lifetime-extended.
389 llvm::PointerIntPair<APValue*, 1, bool> Value;
392 Cleanup(APValue *Val, bool IsLifetimeExtended)
393 : Value(Val, IsLifetimeExtended) {}
395 bool isLifetimeExtended() const { return Value.getInt(); }
397 *Value.getPointer() = APValue();
401 /// EvalInfo - This is a private struct used by the evaluator to capture
402 /// information about a subexpression as it is folded. It retains information
403 /// about the AST context, but also maintains information about the folded
406 /// If an expression could be evaluated, it is still possible it is not a C
407 /// "integer constant expression" or constant expression. If not, this struct
408 /// captures information about how and why not.
410 /// One bit of information passed *into* the request for constant folding
411 /// indicates whether the subexpression is "evaluated" or not according to C
412 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
413 /// evaluate the expression regardless of what the RHS is, but C only allows
414 /// certain things in certain situations.
418 /// EvalStatus - Contains information about the evaluation.
419 Expr::EvalStatus &EvalStatus;
421 /// CurrentCall - The top of the constexpr call stack.
422 CallStackFrame *CurrentCall;
424 /// CallStackDepth - The number of calls in the call stack right now.
425 unsigned CallStackDepth;
427 /// NextCallIndex - The next call index to assign.
428 unsigned NextCallIndex;
430 /// StepsLeft - The remaining number of evaluation steps we're permitted
431 /// to perform. This is essentially a limit for the number of statements
432 /// we will evaluate.
435 /// BottomFrame - The frame in which evaluation started. This must be
436 /// initialized after CurrentCall and CallStackDepth.
437 CallStackFrame BottomFrame;
439 /// A stack of values whose lifetimes end at the end of some surrounding
440 /// evaluation frame.
441 llvm::SmallVector<Cleanup, 16> CleanupStack;
443 /// EvaluatingDecl - This is the declaration whose initializer is being
444 /// evaluated, if any.
445 APValue::LValueBase EvaluatingDecl;
447 /// EvaluatingDeclValue - This is the value being constructed for the
448 /// declaration whose initializer is being evaluated, if any.
449 APValue *EvaluatingDeclValue;
451 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
452 /// notes attached to it will also be stored, otherwise they will not be.
453 bool HasActiveDiagnostic;
455 enum EvaluationMode {
456 /// Evaluate as a constant expression. Stop if we find that the expression
457 /// is not a constant expression.
458 EM_ConstantExpression,
460 /// Evaluate as a potential constant expression. Keep going if we hit a
461 /// construct that we can't evaluate yet (because we don't yet know the
462 /// value of something) but stop if we hit something that could never be
463 /// a constant expression.
464 EM_PotentialConstantExpression,
466 /// Fold the expression to a constant. Stop if we hit a side-effect that
470 /// Evaluate the expression looking for integer overflow and similar
471 /// issues. Don't worry about side-effects, and try to visit all
473 EM_EvaluateForOverflow,
475 /// Evaluate in any way we know how. Don't worry about side-effects that
476 /// can't be modeled.
480 /// Are we checking whether the expression is a potential constant
482 bool checkingPotentialConstantExpression() const {
483 return EvalMode == EM_PotentialConstantExpression;
486 /// Are we checking an expression for overflow?
487 // FIXME: We should check for any kind of undefined or suspicious behavior
488 // in such constructs, not just overflow.
489 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
491 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
492 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
493 CallStackDepth(0), NextCallIndex(1),
494 StepsLeft(getLangOpts().ConstexprStepLimit),
495 BottomFrame(*this, SourceLocation(), 0, 0, 0),
496 EvaluatingDecl((const ValueDecl*)0), EvaluatingDeclValue(0),
497 HasActiveDiagnostic(false), EvalMode(Mode) {}
499 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
500 EvaluatingDecl = Base;
501 EvaluatingDeclValue = &Value;
504 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
506 bool CheckCallLimit(SourceLocation Loc) {
507 // Don't perform any constexpr calls (other than the call we're checking)
508 // when checking a potential constant expression.
509 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
511 if (NextCallIndex == 0) {
512 // NextCallIndex has wrapped around.
513 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
516 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
518 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
519 << getLangOpts().ConstexprCallDepth;
523 CallStackFrame *getCallFrame(unsigned CallIndex) {
524 assert(CallIndex && "no call index in getCallFrame");
525 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
526 // be null in this loop.
527 CallStackFrame *Frame = CurrentCall;
528 while (Frame->Index > CallIndex)
529 Frame = Frame->Caller;
530 return (Frame->Index == CallIndex) ? Frame : 0;
533 bool nextStep(const Stmt *S) {
535 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
543 /// Add a diagnostic to the diagnostics list.
544 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
545 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
546 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
547 return EvalStatus.Diag->back().second;
550 /// Add notes containing a call stack to the current point of evaluation.
551 void addCallStack(unsigned Limit);
554 /// Diagnose that the evaluation cannot be folded.
555 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
556 = diag::note_invalid_subexpr_in_const_expr,
557 unsigned ExtraNotes = 0) {
558 if (EvalStatus.Diag) {
559 // If we have a prior diagnostic, it will be noting that the expression
560 // isn't a constant expression. This diagnostic is more important,
561 // unless we require this evaluation to produce a constant expression.
563 // FIXME: We might want to show both diagnostics to the user in
564 // EM_ConstantFold mode.
565 if (!EvalStatus.Diag->empty()) {
567 case EM_ConstantFold:
568 case EM_IgnoreSideEffects:
569 case EM_EvaluateForOverflow:
570 if (!EvalStatus.HasSideEffects)
572 // We've had side-effects; we want the diagnostic from them, not
573 // some later problem.
574 case EM_ConstantExpression:
575 case EM_PotentialConstantExpression:
576 HasActiveDiagnostic = false;
577 return OptionalDiagnostic();
581 unsigned CallStackNotes = CallStackDepth - 1;
582 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
584 CallStackNotes = std::min(CallStackNotes, Limit + 1);
585 if (checkingPotentialConstantExpression())
588 HasActiveDiagnostic = true;
589 EvalStatus.Diag->clear();
590 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
591 addDiag(Loc, DiagId);
592 if (!checkingPotentialConstantExpression())
594 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
596 HasActiveDiagnostic = false;
597 return OptionalDiagnostic();
600 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
601 = diag::note_invalid_subexpr_in_const_expr,
602 unsigned ExtraNotes = 0) {
604 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
605 HasActiveDiagnostic = false;
606 return OptionalDiagnostic();
609 /// Diagnose that the evaluation does not produce a C++11 core constant
612 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
613 /// EM_PotentialConstantExpression mode and we produce one of these.
614 template<typename LocArg>
615 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
616 = diag::note_invalid_subexpr_in_const_expr,
617 unsigned ExtraNotes = 0) {
618 // Don't override a previous diagnostic. Don't bother collecting
619 // diagnostics if we're evaluating for overflow.
620 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
621 HasActiveDiagnostic = false;
622 return OptionalDiagnostic();
624 return Diag(Loc, DiagId, ExtraNotes);
627 /// Add a note to a prior diagnostic.
628 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
629 if (!HasActiveDiagnostic)
630 return OptionalDiagnostic();
631 return OptionalDiagnostic(&addDiag(Loc, DiagId));
634 /// Add a stack of notes to a prior diagnostic.
635 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
636 if (HasActiveDiagnostic) {
637 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
638 Diags.begin(), Diags.end());
642 /// Should we continue evaluation after encountering a side-effect that we
644 bool keepEvaluatingAfterSideEffect() {
646 case EM_PotentialConstantExpression:
647 case EM_EvaluateForOverflow:
648 case EM_IgnoreSideEffects:
651 case EM_ConstantExpression:
652 case EM_ConstantFold:
655 llvm_unreachable("Missed EvalMode case");
658 /// Note that we have had a side-effect, and determine whether we should
660 bool noteSideEffect() {
661 EvalStatus.HasSideEffects = true;
662 return keepEvaluatingAfterSideEffect();
665 /// Should we continue evaluation as much as possible after encountering a
666 /// construct which can't be reduced to a value?
667 bool keepEvaluatingAfterFailure() {
672 case EM_PotentialConstantExpression:
673 case EM_EvaluateForOverflow:
676 case EM_ConstantExpression:
677 case EM_ConstantFold:
678 case EM_IgnoreSideEffects:
681 llvm_unreachable("Missed EvalMode case");
685 /// Object used to treat all foldable expressions as constant expressions.
686 struct FoldConstant {
689 bool HadNoPriorDiags;
690 EvalInfo::EvaluationMode OldMode;
692 explicit FoldConstant(EvalInfo &Info, bool Enabled)
695 HadNoPriorDiags(Info.EvalStatus.Diag &&
696 Info.EvalStatus.Diag->empty() &&
697 !Info.EvalStatus.HasSideEffects),
698 OldMode(Info.EvalMode) {
699 if (Enabled && Info.EvalMode == EvalInfo::EM_ConstantExpression)
700 Info.EvalMode = EvalInfo::EM_ConstantFold;
702 void keepDiagnostics() { Enabled = false; }
704 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
705 !Info.EvalStatus.HasSideEffects)
706 Info.EvalStatus.Diag->clear();
707 Info.EvalMode = OldMode;
711 /// RAII object used to suppress diagnostics and side-effects from a
712 /// speculative evaluation.
713 class SpeculativeEvaluationRAII {
715 Expr::EvalStatus Old;
718 SpeculativeEvaluationRAII(EvalInfo &Info,
719 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
720 : Info(Info), Old(Info.EvalStatus) {
721 Info.EvalStatus.Diag = NewDiag;
722 // If we're speculatively evaluating, we may have skipped over some
723 // evaluations and missed out a side effect.
724 Info.EvalStatus.HasSideEffects = true;
726 ~SpeculativeEvaluationRAII() {
727 Info.EvalStatus = Old;
731 /// RAII object wrapping a full-expression or block scope, and handling
732 /// the ending of the lifetime of temporaries created within it.
733 template<bool IsFullExpression>
736 unsigned OldStackSize;
738 ScopeRAII(EvalInfo &Info)
739 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
741 // Body moved to a static method to encourage the compiler to inline away
742 // instances of this class.
743 cleanup(Info, OldStackSize);
746 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
747 unsigned NewEnd = OldStackSize;
748 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
750 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
751 // Full-expression cleanup of a lifetime-extended temporary: nothing
752 // to do, just move this cleanup to the right place in the stack.
753 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
756 // End the lifetime of the object.
757 Info.CleanupStack[I].endLifetime();
760 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
761 Info.CleanupStack.end());
764 typedef ScopeRAII<false> BlockScopeRAII;
765 typedef ScopeRAII<true> FullExpressionRAII;
768 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
769 CheckSubobjectKind CSK) {
772 if (isOnePastTheEnd()) {
773 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
781 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
782 const Expr *E, uint64_t N) {
783 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
784 Info.CCEDiag(E, diag::note_constexpr_array_index)
785 << static_cast<int>(N) << /*array*/ 0
786 << static_cast<unsigned>(MostDerivedArraySize);
788 Info.CCEDiag(E, diag::note_constexpr_array_index)
789 << static_cast<int>(N) << /*non-array*/ 1;
793 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
794 const FunctionDecl *Callee, const LValue *This,
796 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
797 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
798 Info.CurrentCall = this;
799 ++Info.CallStackDepth;
802 CallStackFrame::~CallStackFrame() {
803 assert(Info.CurrentCall == this && "calls retired out of order");
804 --Info.CallStackDepth;
805 Info.CurrentCall = Caller;
808 APValue &CallStackFrame::createTemporary(const void *Key,
809 bool IsLifetimeExtended) {
810 APValue &Result = Temporaries[Key];
811 assert(Result.isUninit() && "temporary created multiple times");
812 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
816 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
818 void EvalInfo::addCallStack(unsigned Limit) {
819 // Determine which calls to skip, if any.
820 unsigned ActiveCalls = CallStackDepth - 1;
821 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
822 if (Limit && Limit < ActiveCalls) {
823 SkipStart = Limit / 2 + Limit % 2;
824 SkipEnd = ActiveCalls - Limit / 2;
827 // Walk the call stack and add the diagnostics.
828 unsigned CallIdx = 0;
829 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
830 Frame = Frame->Caller, ++CallIdx) {
832 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
833 if (CallIdx == SkipStart) {
834 // Note that we're skipping calls.
835 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
836 << unsigned(ActiveCalls - Limit);
841 SmallVector<char, 128> Buffer;
842 llvm::raw_svector_ostream Out(Buffer);
843 describeCall(Frame, Out);
844 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
849 struct ComplexValue {
854 APSInt IntReal, IntImag;
855 APFloat FloatReal, FloatImag;
857 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
859 void makeComplexFloat() { IsInt = false; }
860 bool isComplexFloat() const { return !IsInt; }
861 APFloat &getComplexFloatReal() { return FloatReal; }
862 APFloat &getComplexFloatImag() { return FloatImag; }
864 void makeComplexInt() { IsInt = true; }
865 bool isComplexInt() const { return IsInt; }
866 APSInt &getComplexIntReal() { return IntReal; }
867 APSInt &getComplexIntImag() { return IntImag; }
869 void moveInto(APValue &v) const {
870 if (isComplexFloat())
871 v = APValue(FloatReal, FloatImag);
873 v = APValue(IntReal, IntImag);
875 void setFrom(const APValue &v) {
876 assert(v.isComplexFloat() || v.isComplexInt());
877 if (v.isComplexFloat()) {
879 FloatReal = v.getComplexFloatReal();
880 FloatImag = v.getComplexFloatImag();
883 IntReal = v.getComplexIntReal();
884 IntImag = v.getComplexIntImag();
890 APValue::LValueBase Base;
893 SubobjectDesignator Designator;
895 const APValue::LValueBase getLValueBase() const { return Base; }
896 CharUnits &getLValueOffset() { return Offset; }
897 const CharUnits &getLValueOffset() const { return Offset; }
898 unsigned getLValueCallIndex() const { return CallIndex; }
899 SubobjectDesignator &getLValueDesignator() { return Designator; }
900 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
902 void moveInto(APValue &V) const {
903 if (Designator.Invalid)
904 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
906 V = APValue(Base, Offset, Designator.Entries,
907 Designator.IsOnePastTheEnd, CallIndex);
909 void setFrom(ASTContext &Ctx, const APValue &V) {
910 assert(V.isLValue());
911 Base = V.getLValueBase();
912 Offset = V.getLValueOffset();
913 CallIndex = V.getLValueCallIndex();
914 Designator = SubobjectDesignator(Ctx, V);
917 void set(APValue::LValueBase B, unsigned I = 0) {
919 Offset = CharUnits::Zero();
921 Designator = SubobjectDesignator(getType(B));
924 // Check that this LValue is not based on a null pointer. If it is, produce
925 // a diagnostic and mark the designator as invalid.
926 bool checkNullPointer(EvalInfo &Info, const Expr *E,
927 CheckSubobjectKind CSK) {
928 if (Designator.Invalid)
931 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
933 Designator.setInvalid();
939 // Check this LValue refers to an object. If not, set the designator to be
940 // invalid and emit a diagnostic.
941 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
942 // Outside C++11, do not build a designator referring to a subobject of
943 // any object: we won't use such a designator for anything.
944 if (!Info.getLangOpts().CPlusPlus11)
945 Designator.setInvalid();
946 return checkNullPointer(Info, E, CSK) &&
947 Designator.checkSubobject(Info, E, CSK);
950 void addDecl(EvalInfo &Info, const Expr *E,
951 const Decl *D, bool Virtual = false) {
952 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
953 Designator.addDeclUnchecked(D, Virtual);
955 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
956 if (checkSubobject(Info, E, CSK_ArrayToPointer))
957 Designator.addArrayUnchecked(CAT);
959 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
960 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
961 Designator.addComplexUnchecked(EltTy, Imag);
963 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
964 if (checkNullPointer(Info, E, CSK_ArrayIndex))
965 Designator.adjustIndex(Info, E, N);
971 explicit MemberPtr(const ValueDecl *Decl) :
972 DeclAndIsDerivedMember(Decl, false), Path() {}
974 /// The member or (direct or indirect) field referred to by this member
975 /// pointer, or 0 if this is a null member pointer.
976 const ValueDecl *getDecl() const {
977 return DeclAndIsDerivedMember.getPointer();
979 /// Is this actually a member of some type derived from the relevant class?
980 bool isDerivedMember() const {
981 return DeclAndIsDerivedMember.getInt();
983 /// Get the class which the declaration actually lives in.
984 const CXXRecordDecl *getContainingRecord() const {
985 return cast<CXXRecordDecl>(
986 DeclAndIsDerivedMember.getPointer()->getDeclContext());
989 void moveInto(APValue &V) const {
990 V = APValue(getDecl(), isDerivedMember(), Path);
992 void setFrom(const APValue &V) {
993 assert(V.isMemberPointer());
994 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
995 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
997 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
998 Path.insert(Path.end(), P.begin(), P.end());
1001 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1002 /// whether the member is a member of some class derived from the class type
1003 /// of the member pointer.
1004 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1005 /// Path - The path of base/derived classes from the member declaration's
1006 /// class (exclusive) to the class type of the member pointer (inclusive).
1007 SmallVector<const CXXRecordDecl*, 4> Path;
1009 /// Perform a cast towards the class of the Decl (either up or down the
1011 bool castBack(const CXXRecordDecl *Class) {
1012 assert(!Path.empty());
1013 const CXXRecordDecl *Expected;
1014 if (Path.size() >= 2)
1015 Expected = Path[Path.size() - 2];
1017 Expected = getContainingRecord();
1018 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1019 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1020 // if B does not contain the original member and is not a base or
1021 // derived class of the class containing the original member, the result
1022 // of the cast is undefined.
1023 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1024 // (D::*). We consider that to be a language defect.
1030 /// Perform a base-to-derived member pointer cast.
1031 bool castToDerived(const CXXRecordDecl *Derived) {
1034 if (!isDerivedMember()) {
1035 Path.push_back(Derived);
1038 if (!castBack(Derived))
1041 DeclAndIsDerivedMember.setInt(false);
1044 /// Perform a derived-to-base member pointer cast.
1045 bool castToBase(const CXXRecordDecl *Base) {
1049 DeclAndIsDerivedMember.setInt(true);
1050 if (isDerivedMember()) {
1051 Path.push_back(Base);
1054 return castBack(Base);
1058 /// Compare two member pointers, which are assumed to be of the same type.
1059 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1060 if (!LHS.getDecl() || !RHS.getDecl())
1061 return !LHS.getDecl() && !RHS.getDecl();
1062 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1064 return LHS.Path == RHS.Path;
1068 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1069 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1070 const LValue &This, const Expr *E,
1071 bool AllowNonLiteralTypes = false);
1072 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1073 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
1074 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1076 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1077 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1078 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1080 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1081 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1082 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
1084 //===----------------------------------------------------------------------===//
1086 //===----------------------------------------------------------------------===//
1088 /// Produce a string describing the given constexpr call.
1089 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1090 unsigned ArgIndex = 0;
1091 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1092 !isa<CXXConstructorDecl>(Frame->Callee) &&
1093 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1096 Out << *Frame->Callee << '(';
1098 if (Frame->This && IsMemberCall) {
1100 Frame->This->moveInto(Val);
1101 Val.printPretty(Out, Frame->Info.Ctx,
1102 Frame->This->Designator.MostDerivedType);
1103 // FIXME: Add parens around Val if needed.
1104 Out << "->" << *Frame->Callee << '(';
1105 IsMemberCall = false;
1108 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1109 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1110 if (ArgIndex > (unsigned)IsMemberCall)
1113 const ParmVarDecl *Param = *I;
1114 const APValue &Arg = Frame->Arguments[ArgIndex];
1115 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1117 if (ArgIndex == 0 && IsMemberCall)
1118 Out << "->" << *Frame->Callee << '(';
1124 /// Evaluate an expression to see if it had side-effects, and discard its
1126 /// \return \c true if the caller should keep evaluating.
1127 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1129 if (!Evaluate(Scratch, Info, E))
1130 // We don't need the value, but we might have skipped a side effect here.
1131 return Info.noteSideEffect();
1135 /// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1136 /// return its existing value.
1137 static int64_t getExtValue(const APSInt &Value) {
1138 return Value.isSigned() ? Value.getSExtValue()
1139 : static_cast<int64_t>(Value.getZExtValue());
1142 /// Should this call expression be treated as a string literal?
1143 static bool IsStringLiteralCall(const CallExpr *E) {
1144 unsigned Builtin = E->isBuiltinCall();
1145 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1146 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1149 static bool IsGlobalLValue(APValue::LValueBase B) {
1150 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1151 // constant expression of pointer type that evaluates to...
1153 // ... a null pointer value, or a prvalue core constant expression of type
1155 if (!B) return true;
1157 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1158 // ... the address of an object with static storage duration,
1159 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1160 return VD->hasGlobalStorage();
1161 // ... the address of a function,
1162 return isa<FunctionDecl>(D);
1165 const Expr *E = B.get<const Expr*>();
1166 switch (E->getStmtClass()) {
1169 case Expr::CompoundLiteralExprClass: {
1170 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1171 return CLE->isFileScope() && CLE->isLValue();
1173 case Expr::MaterializeTemporaryExprClass:
1174 // A materialized temporary might have been lifetime-extended to static
1175 // storage duration.
1176 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1177 // A string literal has static storage duration.
1178 case Expr::StringLiteralClass:
1179 case Expr::PredefinedExprClass:
1180 case Expr::ObjCStringLiteralClass:
1181 case Expr::ObjCEncodeExprClass:
1182 case Expr::CXXTypeidExprClass:
1183 case Expr::CXXUuidofExprClass:
1185 case Expr::CallExprClass:
1186 return IsStringLiteralCall(cast<CallExpr>(E));
1187 // For GCC compatibility, &&label has static storage duration.
1188 case Expr::AddrLabelExprClass:
1190 // A Block literal expression may be used as the initialization value for
1191 // Block variables at global or local static scope.
1192 case Expr::BlockExprClass:
1193 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1194 case Expr::ImplicitValueInitExprClass:
1196 // We can never form an lvalue with an implicit value initialization as its
1197 // base through expression evaluation, so these only appear in one case: the
1198 // implicit variable declaration we invent when checking whether a constexpr
1199 // constructor can produce a constant expression. We must assume that such
1200 // an expression might be a global lvalue.
1205 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1206 assert(Base && "no location for a null lvalue");
1207 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1209 Info.Note(VD->getLocation(), diag::note_declared_at);
1211 Info.Note(Base.get<const Expr*>()->getExprLoc(),
1212 diag::note_constexpr_temporary_here);
1215 /// Check that this reference or pointer core constant expression is a valid
1216 /// value for an address or reference constant expression. Return true if we
1217 /// can fold this expression, whether or not it's a constant expression.
1218 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1219 QualType Type, const LValue &LVal) {
1220 bool IsReferenceType = Type->isReferenceType();
1222 APValue::LValueBase Base = LVal.getLValueBase();
1223 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1225 // Check that the object is a global. Note that the fake 'this' object we
1226 // manufacture when checking potential constant expressions is conservatively
1227 // assumed to be global here.
1228 if (!IsGlobalLValue(Base)) {
1229 if (Info.getLangOpts().CPlusPlus11) {
1230 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1231 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1232 << IsReferenceType << !Designator.Entries.empty()
1234 NoteLValueLocation(Info, Base);
1238 // Don't allow references to temporaries to escape.
1241 assert((Info.checkingPotentialConstantExpression() ||
1242 LVal.getLValueCallIndex() == 0) &&
1243 "have call index for global lvalue");
1245 // Check if this is a thread-local variable.
1246 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1247 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1248 if (Var->getTLSKind())
1253 // Allow address constant expressions to be past-the-end pointers. This is
1254 // an extension: the standard requires them to point to an object.
1255 if (!IsReferenceType)
1258 // A reference constant expression must refer to an object.
1260 // FIXME: diagnostic
1265 // Does this refer one past the end of some object?
1266 if (Designator.isOnePastTheEnd()) {
1267 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1268 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1269 << !Designator.Entries.empty() << !!VD << VD;
1270 NoteLValueLocation(Info, Base);
1276 /// Check that this core constant expression is of literal type, and if not,
1277 /// produce an appropriate diagnostic.
1278 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1279 const LValue *This = 0) {
1280 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1283 // C++1y: A constant initializer for an object o [...] may also invoke
1284 // constexpr constructors for o and its subobjects even if those objects
1285 // are of non-literal class types.
1286 if (Info.getLangOpts().CPlusPlus1y && This &&
1287 Info.EvaluatingDecl == This->getLValueBase())
1290 // Prvalue constant expressions must be of literal types.
1291 if (Info.getLangOpts().CPlusPlus11)
1292 Info.Diag(E, diag::note_constexpr_nonliteral)
1295 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1299 /// Check that this core constant expression value is a valid value for a
1300 /// constant expression. If not, report an appropriate diagnostic. Does not
1301 /// check that the expression is of literal type.
1302 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1303 QualType Type, const APValue &Value) {
1304 if (Value.isUninit()) {
1305 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1310 // Core issue 1454: For a literal constant expression of array or class type,
1311 // each subobject of its value shall have been initialized by a constant
1313 if (Value.isArray()) {
1314 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1315 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1316 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1317 Value.getArrayInitializedElt(I)))
1320 if (!Value.hasArrayFiller())
1322 return CheckConstantExpression(Info, DiagLoc, EltTy,
1323 Value.getArrayFiller());
1325 if (Value.isUnion() && Value.getUnionField()) {
1326 return CheckConstantExpression(Info, DiagLoc,
1327 Value.getUnionField()->getType(),
1328 Value.getUnionValue());
1330 if (Value.isStruct()) {
1331 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1332 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1333 unsigned BaseIndex = 0;
1334 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1335 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1336 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1337 Value.getStructBase(BaseIndex)))
1341 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1343 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1344 Value.getStructField(I->getFieldIndex())))
1349 if (Value.isLValue()) {
1351 LVal.setFrom(Info.Ctx, Value);
1352 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1355 // Everything else is fine.
1359 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1360 return LVal.Base.dyn_cast<const ValueDecl*>();
1363 static bool IsLiteralLValue(const LValue &Value) {
1364 if (Value.CallIndex)
1366 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1367 return E && !isa<MaterializeTemporaryExpr>(E);
1370 static bool IsWeakLValue(const LValue &Value) {
1371 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1372 return Decl && Decl->isWeak();
1375 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1376 // A null base expression indicates a null pointer. These are always
1377 // evaluatable, and they are false unless the offset is zero.
1378 if (!Value.getLValueBase()) {
1379 Result = !Value.getLValueOffset().isZero();
1383 // We have a non-null base. These are generally known to be true, but if it's
1384 // a weak declaration it can be null at runtime.
1386 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1387 return !Decl || !Decl->isWeak();
1390 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1391 switch (Val.getKind()) {
1392 case APValue::Uninitialized:
1395 Result = Val.getInt().getBoolValue();
1397 case APValue::Float:
1398 Result = !Val.getFloat().isZero();
1400 case APValue::ComplexInt:
1401 Result = Val.getComplexIntReal().getBoolValue() ||
1402 Val.getComplexIntImag().getBoolValue();
1404 case APValue::ComplexFloat:
1405 Result = !Val.getComplexFloatReal().isZero() ||
1406 !Val.getComplexFloatImag().isZero();
1408 case APValue::LValue:
1409 return EvalPointerValueAsBool(Val, Result);
1410 case APValue::MemberPointer:
1411 Result = Val.getMemberPointerDecl();
1413 case APValue::Vector:
1414 case APValue::Array:
1415 case APValue::Struct:
1416 case APValue::Union:
1417 case APValue::AddrLabelDiff:
1421 llvm_unreachable("unknown APValue kind");
1424 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1426 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1428 if (!Evaluate(Val, Info, E))
1430 return HandleConversionToBool(Val, Result);
1433 template<typename T>
1434 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1435 const T &SrcValue, QualType DestType) {
1436 Info.CCEDiag(E, diag::note_constexpr_overflow)
1437 << SrcValue << DestType;
1440 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1441 QualType SrcType, const APFloat &Value,
1442 QualType DestType, APSInt &Result) {
1443 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1444 // Determine whether we are converting to unsigned or signed.
1445 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1447 Result = APSInt(DestWidth, !DestSigned);
1449 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1450 & APFloat::opInvalidOp)
1451 HandleOverflow(Info, E, Value, DestType);
1455 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1456 QualType SrcType, QualType DestType,
1458 APFloat Value = Result;
1460 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1461 APFloat::rmNearestTiesToEven, &ignored)
1462 & APFloat::opOverflow)
1463 HandleOverflow(Info, E, Value, DestType);
1467 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1468 QualType DestType, QualType SrcType,
1470 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1471 APSInt Result = Value;
1472 // Figure out if this is a truncate, extend or noop cast.
1473 // If the input is signed, do a sign extend, noop, or truncate.
1474 Result = Result.extOrTrunc(DestWidth);
1475 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1479 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1480 QualType SrcType, const APSInt &Value,
1481 QualType DestType, APFloat &Result) {
1482 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1483 if (Result.convertFromAPInt(Value, Value.isSigned(),
1484 APFloat::rmNearestTiesToEven)
1485 & APFloat::opOverflow)
1486 HandleOverflow(Info, E, Value, DestType);
1490 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1491 APValue &Value, const FieldDecl *FD) {
1492 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1494 if (!Value.isInt()) {
1495 // Trying to store a pointer-cast-to-integer into a bitfield.
1496 // FIXME: In this case, we should provide the diagnostic for casting
1497 // a pointer to an integer.
1498 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1503 APSInt &Int = Value.getInt();
1504 unsigned OldBitWidth = Int.getBitWidth();
1505 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1506 if (NewBitWidth < OldBitWidth)
1507 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1511 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1514 if (!Evaluate(SVal, Info, E))
1517 Res = SVal.getInt();
1520 if (SVal.isFloat()) {
1521 Res = SVal.getFloat().bitcastToAPInt();
1524 if (SVal.isVector()) {
1525 QualType VecTy = E->getType();
1526 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1527 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1528 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1529 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1530 Res = llvm::APInt::getNullValue(VecSize);
1531 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1532 APValue &Elt = SVal.getVectorElt(i);
1533 llvm::APInt EltAsInt;
1535 EltAsInt = Elt.getInt();
1536 } else if (Elt.isFloat()) {
1537 EltAsInt = Elt.getFloat().bitcastToAPInt();
1539 // Don't try to handle vectors of anything other than int or float
1540 // (not sure if it's possible to hit this case).
1541 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1544 unsigned BaseEltSize = EltAsInt.getBitWidth();
1546 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1548 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1552 // Give up if the input isn't an int, float, or vector. For example, we
1553 // reject "(v4i16)(intptr_t)&a".
1554 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1558 /// Perform the given integer operation, which is known to need at most BitWidth
1559 /// bits, and check for overflow in the original type (if that type was not an
1561 template<typename Operation>
1562 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1563 const APSInt &LHS, const APSInt &RHS,
1564 unsigned BitWidth, Operation Op) {
1565 if (LHS.isUnsigned())
1566 return Op(LHS, RHS);
1568 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1569 APSInt Result = Value.trunc(LHS.getBitWidth());
1570 if (Result.extend(BitWidth) != Value) {
1571 if (Info.checkingForOverflow())
1572 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1573 diag::warn_integer_constant_overflow)
1574 << Result.toString(10) << E->getType();
1576 HandleOverflow(Info, E, Value, E->getType());
1581 /// Perform the given binary integer operation.
1582 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1583 BinaryOperatorKind Opcode, APSInt RHS,
1590 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1591 std::multiplies<APSInt>());
1594 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1595 std::plus<APSInt>());
1598 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1599 std::minus<APSInt>());
1601 case BO_And: Result = LHS & RHS; return true;
1602 case BO_Xor: Result = LHS ^ RHS; return true;
1603 case BO_Or: Result = LHS | RHS; return true;
1607 Info.Diag(E, diag::note_expr_divide_by_zero);
1610 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1611 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1612 LHS.isSigned() && LHS.isMinSignedValue())
1613 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1614 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1617 if (Info.getLangOpts().OpenCL)
1618 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1619 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1620 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1622 else if (RHS.isSigned() && RHS.isNegative()) {
1623 // During constant-folding, a negative shift is an opposite shift. Such
1624 // a shift is not a constant expression.
1625 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1630 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1631 // the shifted type.
1632 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1634 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1635 << RHS << E->getType() << LHS.getBitWidth();
1636 } else if (LHS.isSigned()) {
1637 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1638 // operand, and must not overflow the corresponding unsigned type.
1639 if (LHS.isNegative())
1640 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1641 else if (LHS.countLeadingZeros() < SA)
1642 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1648 if (Info.getLangOpts().OpenCL)
1649 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1650 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1651 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1653 else if (RHS.isSigned() && RHS.isNegative()) {
1654 // During constant-folding, a negative shift is an opposite shift. Such a
1655 // shift is not a constant expression.
1656 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1661 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1663 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1665 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1666 << RHS << E->getType() << LHS.getBitWidth();
1671 case BO_LT: Result = LHS < RHS; return true;
1672 case BO_GT: Result = LHS > RHS; return true;
1673 case BO_LE: Result = LHS <= RHS; return true;
1674 case BO_GE: Result = LHS >= RHS; return true;
1675 case BO_EQ: Result = LHS == RHS; return true;
1676 case BO_NE: Result = LHS != RHS; return true;
1680 /// Perform the given binary floating-point operation, in-place, on LHS.
1681 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1682 APFloat &LHS, BinaryOperatorKind Opcode,
1683 const APFloat &RHS) {
1689 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1692 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1695 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1698 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1702 if (LHS.isInfinity() || LHS.isNaN())
1703 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1707 /// Cast an lvalue referring to a base subobject to a derived class, by
1708 /// truncating the lvalue's path to the given length.
1709 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1710 const RecordDecl *TruncatedType,
1711 unsigned TruncatedElements) {
1712 SubobjectDesignator &D = Result.Designator;
1714 // Check we actually point to a derived class object.
1715 if (TruncatedElements == D.Entries.size())
1717 assert(TruncatedElements >= D.MostDerivedPathLength &&
1718 "not casting to a derived class");
1719 if (!Result.checkSubobject(Info, E, CSK_Derived))
1722 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1723 const RecordDecl *RD = TruncatedType;
1724 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1725 if (RD->isInvalidDecl()) return false;
1726 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1727 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1728 if (isVirtualBaseClass(D.Entries[I]))
1729 Result.Offset -= Layout.getVBaseClassOffset(Base);
1731 Result.Offset -= Layout.getBaseClassOffset(Base);
1734 D.Entries.resize(TruncatedElements);
1738 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1739 const CXXRecordDecl *Derived,
1740 const CXXRecordDecl *Base,
1741 const ASTRecordLayout *RL = 0) {
1743 if (Derived->isInvalidDecl()) return false;
1744 RL = &Info.Ctx.getASTRecordLayout(Derived);
1747 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1748 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1752 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1753 const CXXRecordDecl *DerivedDecl,
1754 const CXXBaseSpecifier *Base) {
1755 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1757 if (!Base->isVirtual())
1758 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1760 SubobjectDesignator &D = Obj.Designator;
1764 // Extract most-derived object and corresponding type.
1765 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1766 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1769 // Find the virtual base class.
1770 if (DerivedDecl->isInvalidDecl()) return false;
1771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1772 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1773 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1777 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1778 QualType Type, LValue &Result) {
1779 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1780 PathE = E->path_end();
1781 PathI != PathE; ++PathI) {
1782 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1785 Type = (*PathI)->getType();
1790 /// Update LVal to refer to the given field, which must be a member of the type
1791 /// currently described by LVal.
1792 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1793 const FieldDecl *FD,
1794 const ASTRecordLayout *RL = 0) {
1796 if (FD->getParent()->isInvalidDecl()) return false;
1797 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1800 unsigned I = FD->getFieldIndex();
1801 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1802 LVal.addDecl(Info, E, FD);
1806 /// Update LVal to refer to the given indirect field.
1807 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1809 const IndirectFieldDecl *IFD) {
1810 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1811 CE = IFD->chain_end(); C != CE; ++C)
1812 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1817 /// Get the size of the given type in char units.
1818 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1819 QualType Type, CharUnits &Size) {
1820 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1822 if (Type->isVoidType() || Type->isFunctionType()) {
1823 Size = CharUnits::One();
1827 if (!Type->isConstantSizeType()) {
1828 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1829 // FIXME: Better diagnostic.
1834 Size = Info.Ctx.getTypeSizeInChars(Type);
1838 /// Update a pointer value to model pointer arithmetic.
1839 /// \param Info - Information about the ongoing evaluation.
1840 /// \param E - The expression being evaluated, for diagnostic purposes.
1841 /// \param LVal - The pointer value to be updated.
1842 /// \param EltTy - The pointee type represented by LVal.
1843 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1844 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1845 LValue &LVal, QualType EltTy,
1846 int64_t Adjustment) {
1847 CharUnits SizeOfPointee;
1848 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1851 // Compute the new offset in the appropriate width.
1852 LVal.Offset += Adjustment * SizeOfPointee;
1853 LVal.adjustIndex(Info, E, Adjustment);
1857 /// Update an lvalue to refer to a component of a complex number.
1858 /// \param Info - Information about the ongoing evaluation.
1859 /// \param LVal - The lvalue to be updated.
1860 /// \param EltTy - The complex number's component type.
1861 /// \param Imag - False for the real component, true for the imaginary.
1862 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1863 LValue &LVal, QualType EltTy,
1866 CharUnits SizeOfComponent;
1867 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1869 LVal.Offset += SizeOfComponent;
1871 LVal.addComplex(Info, E, EltTy, Imag);
1875 /// Try to evaluate the initializer for a variable declaration.
1877 /// \param Info Information about the ongoing evaluation.
1878 /// \param E An expression to be used when printing diagnostics.
1879 /// \param VD The variable whose initializer should be obtained.
1880 /// \param Frame The frame in which the variable was created. Must be null
1881 /// if this variable is not local to the evaluation.
1882 /// \param Result Filled in with a pointer to the value of the variable.
1883 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1884 const VarDecl *VD, CallStackFrame *Frame,
1886 // If this is a parameter to an active constexpr function call, perform
1887 // argument substitution.
1888 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1889 // Assume arguments of a potential constant expression are unknown
1890 // constant expressions.
1891 if (Info.checkingPotentialConstantExpression())
1893 if (!Frame || !Frame->Arguments) {
1894 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1897 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
1901 // If this is a local variable, dig out its value.
1903 Result = Frame->getTemporary(VD);
1904 assert(Result && "missing value for local variable");
1908 // Dig out the initializer, and use the declaration which it's attached to.
1909 const Expr *Init = VD->getAnyInitializer(VD);
1910 if (!Init || Init->isValueDependent()) {
1911 // If we're checking a potential constant expression, the variable could be
1912 // initialized later.
1913 if (!Info.checkingPotentialConstantExpression())
1914 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1918 // If we're currently evaluating the initializer of this declaration, use that
1920 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
1921 Result = Info.EvaluatingDeclValue;
1925 // Never evaluate the initializer of a weak variable. We can't be sure that
1926 // this is the definition which will be used.
1928 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1932 // Check that we can fold the initializer. In C++, we will have already done
1933 // this in the cases where it matters for conformance.
1934 SmallVector<PartialDiagnosticAt, 8> Notes;
1935 if (!VD->evaluateValue(Notes)) {
1936 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1937 Notes.size() + 1) << VD;
1938 Info.Note(VD->getLocation(), diag::note_declared_at);
1939 Info.addNotes(Notes);
1941 } else if (!VD->checkInitIsICE()) {
1942 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1943 Notes.size() + 1) << VD;
1944 Info.Note(VD->getLocation(), diag::note_declared_at);
1945 Info.addNotes(Notes);
1948 Result = VD->getEvaluatedValue();
1952 static bool IsConstNonVolatile(QualType T) {
1953 Qualifiers Quals = T.getQualifiers();
1954 return Quals.hasConst() && !Quals.hasVolatile();
1957 /// Get the base index of the given base class within an APValue representing
1958 /// the given derived class.
1959 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1960 const CXXRecordDecl *Base) {
1961 Base = Base->getCanonicalDecl();
1963 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1964 E = Derived->bases_end(); I != E; ++I, ++Index) {
1965 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1969 llvm_unreachable("base class missing from derived class's bases list");
1972 /// Extract the value of a character from a string literal.
1973 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1975 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1976 const StringLiteral *S = cast<StringLiteral>(Lit);
1977 const ConstantArrayType *CAT =
1978 Info.Ctx.getAsConstantArrayType(S->getType());
1979 assert(CAT && "string literal isn't an array");
1980 QualType CharType = CAT->getElementType();
1981 assert(CharType->isIntegerType() && "unexpected character type");
1983 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1984 CharType->isUnsignedIntegerType());
1985 if (Index < S->getLength())
1986 Value = S->getCodeUnit(Index);
1990 // Expand a string literal into an array of characters.
1991 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
1993 const StringLiteral *S = cast<StringLiteral>(Lit);
1994 const ConstantArrayType *CAT =
1995 Info.Ctx.getAsConstantArrayType(S->getType());
1996 assert(CAT && "string literal isn't an array");
1997 QualType CharType = CAT->getElementType();
1998 assert(CharType->isIntegerType() && "unexpected character type");
2000 unsigned Elts = CAT->getSize().getZExtValue();
2001 Result = APValue(APValue::UninitArray(),
2002 std::min(S->getLength(), Elts), Elts);
2003 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2004 CharType->isUnsignedIntegerType());
2005 if (Result.hasArrayFiller())
2006 Result.getArrayFiller() = APValue(Value);
2007 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2008 Value = S->getCodeUnit(I);
2009 Result.getArrayInitializedElt(I) = APValue(Value);
2013 // Expand an array so that it has more than Index filled elements.
2014 static void expandArray(APValue &Array, unsigned Index) {
2015 unsigned Size = Array.getArraySize();
2016 assert(Index < Size);
2018 // Always at least double the number of elements for which we store a value.
2019 unsigned OldElts = Array.getArrayInitializedElts();
2020 unsigned NewElts = std::max(Index+1, OldElts * 2);
2021 NewElts = std::min(Size, std::max(NewElts, 8u));
2023 // Copy the data across.
2024 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2025 for (unsigned I = 0; I != OldElts; ++I)
2026 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2027 for (unsigned I = OldElts; I != NewElts; ++I)
2028 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2029 if (NewValue.hasArrayFiller())
2030 NewValue.getArrayFiller() = Array.getArrayFiller();
2031 Array.swap(NewValue);
2034 /// Kinds of access we can perform on an object, for diagnostics.
2042 /// A handle to a complete object (an object that is not a subobject of
2043 /// another object).
2044 struct CompleteObject {
2045 /// The value of the complete object.
2047 /// The type of the complete object.
2050 CompleteObject() : Value(0) {}
2051 CompleteObject(APValue *Value, QualType Type)
2052 : Value(Value), Type(Type) {
2053 assert(Value && "missing value for complete object");
2056 LLVM_EXPLICIT operator bool() const { return Value; }
2059 /// Find the designated sub-object of an rvalue.
2060 template<typename SubobjectHandler>
2061 typename SubobjectHandler::result_type
2062 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2063 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2065 // A diagnostic will have already been produced.
2066 return handler.failed();
2067 if (Sub.isOnePastTheEnd()) {
2068 if (Info.getLangOpts().CPlusPlus11)
2069 Info.Diag(E, diag::note_constexpr_access_past_end)
2070 << handler.AccessKind;
2073 return handler.failed();
2076 APValue *O = Obj.Value;
2077 QualType ObjType = Obj.Type;
2078 const FieldDecl *LastField = 0;
2080 // Walk the designator's path to find the subobject.
2081 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2082 if (O->isUninit()) {
2083 if (!Info.checkingPotentialConstantExpression())
2084 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2085 return handler.failed();
2089 if (!handler.found(*O, ObjType))
2092 // If we modified a bit-field, truncate it to the right width.
2093 if (handler.AccessKind != AK_Read &&
2094 LastField && LastField->isBitField() &&
2095 !truncateBitfieldValue(Info, E, *O, LastField))
2102 if (ObjType->isArrayType()) {
2103 // Next subobject is an array element.
2104 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2105 assert(CAT && "vla in literal type?");
2106 uint64_t Index = Sub.Entries[I].ArrayIndex;
2107 if (CAT->getSize().ule(Index)) {
2108 // Note, it should not be possible to form a pointer with a valid
2109 // designator which points more than one past the end of the array.
2110 if (Info.getLangOpts().CPlusPlus11)
2111 Info.Diag(E, diag::note_constexpr_access_past_end)
2112 << handler.AccessKind;
2115 return handler.failed();
2118 ObjType = CAT->getElementType();
2120 // An array object is represented as either an Array APValue or as an
2121 // LValue which refers to a string literal.
2122 if (O->isLValue()) {
2123 assert(I == N - 1 && "extracting subobject of character?");
2124 assert(!O->hasLValuePath() || O->getLValuePath().empty());
2125 if (handler.AccessKind != AK_Read)
2126 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2129 return handler.foundString(*O, ObjType, Index);
2132 if (O->getArrayInitializedElts() > Index)
2133 O = &O->getArrayInitializedElt(Index);
2134 else if (handler.AccessKind != AK_Read) {
2135 expandArray(*O, Index);
2136 O = &O->getArrayInitializedElt(Index);
2138 O = &O->getArrayFiller();
2139 } else if (ObjType->isAnyComplexType()) {
2140 // Next subobject is a complex number.
2141 uint64_t Index = Sub.Entries[I].ArrayIndex;
2143 if (Info.getLangOpts().CPlusPlus11)
2144 Info.Diag(E, diag::note_constexpr_access_past_end)
2145 << handler.AccessKind;
2148 return handler.failed();
2151 bool WasConstQualified = ObjType.isConstQualified();
2152 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2153 if (WasConstQualified)
2156 assert(I == N - 1 && "extracting subobject of scalar?");
2157 if (O->isComplexInt()) {
2158 return handler.found(Index ? O->getComplexIntImag()
2159 : O->getComplexIntReal(), ObjType);
2161 assert(O->isComplexFloat());
2162 return handler.found(Index ? O->getComplexFloatImag()
2163 : O->getComplexFloatReal(), ObjType);
2165 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2166 if (Field->isMutable() && handler.AccessKind == AK_Read) {
2167 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
2169 Info.Note(Field->getLocation(), diag::note_declared_at);
2170 return handler.failed();
2173 // Next subobject is a class, struct or union field.
2174 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2175 if (RD->isUnion()) {
2176 const FieldDecl *UnionField = O->getUnionField();
2178 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2179 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2180 << handler.AccessKind << Field << !UnionField << UnionField;
2181 return handler.failed();
2183 O = &O->getUnionValue();
2185 O = &O->getStructField(Field->getFieldIndex());
2187 bool WasConstQualified = ObjType.isConstQualified();
2188 ObjType = Field->getType();
2189 if (WasConstQualified && !Field->isMutable())
2192 if (ObjType.isVolatileQualified()) {
2193 if (Info.getLangOpts().CPlusPlus) {
2194 // FIXME: Include a description of the path to the volatile subobject.
2195 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2196 << handler.AccessKind << 2 << Field;
2197 Info.Note(Field->getLocation(), diag::note_declared_at);
2199 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
2201 return handler.failed();
2206 // Next subobject is a base class.
2207 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2208 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2209 O = &O->getStructBase(getBaseIndex(Derived, Base));
2211 bool WasConstQualified = ObjType.isConstQualified();
2212 ObjType = Info.Ctx.getRecordType(Base);
2213 if (WasConstQualified)
2220 struct ExtractSubobjectHandler {
2224 static const AccessKinds AccessKind = AK_Read;
2226 typedef bool result_type;
2227 bool failed() { return false; }
2228 bool found(APValue &Subobj, QualType SubobjType) {
2232 bool found(APSInt &Value, QualType SubobjType) {
2233 Result = APValue(Value);
2236 bool found(APFloat &Value, QualType SubobjType) {
2237 Result = APValue(Value);
2240 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2241 Result = APValue(extractStringLiteralCharacter(
2242 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2246 } // end anonymous namespace
2248 const AccessKinds ExtractSubobjectHandler::AccessKind;
2250 /// Extract the designated sub-object of an rvalue.
2251 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2252 const CompleteObject &Obj,
2253 const SubobjectDesignator &Sub,
2255 ExtractSubobjectHandler Handler = { Info, Result };
2256 return findSubobject(Info, E, Obj, Sub, Handler);
2260 struct ModifySubobjectHandler {
2265 typedef bool result_type;
2266 static const AccessKinds AccessKind = AK_Assign;
2268 bool checkConst(QualType QT) {
2269 // Assigning to a const object has undefined behavior.
2270 if (QT.isConstQualified()) {
2271 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2277 bool failed() { return false; }
2278 bool found(APValue &Subobj, QualType SubobjType) {
2279 if (!checkConst(SubobjType))
2281 // We've been given ownership of NewVal, so just swap it in.
2282 Subobj.swap(NewVal);
2285 bool found(APSInt &Value, QualType SubobjType) {
2286 if (!checkConst(SubobjType))
2288 if (!NewVal.isInt()) {
2289 // Maybe trying to write a cast pointer value into a complex?
2293 Value = NewVal.getInt();
2296 bool found(APFloat &Value, QualType SubobjType) {
2297 if (!checkConst(SubobjType))
2299 Value = NewVal.getFloat();
2302 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2303 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2306 } // end anonymous namespace
2308 const AccessKinds ModifySubobjectHandler::AccessKind;
2310 /// Update the designated sub-object of an rvalue to the given value.
2311 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2312 const CompleteObject &Obj,
2313 const SubobjectDesignator &Sub,
2315 ModifySubobjectHandler Handler = { Info, NewVal, E };
2316 return findSubobject(Info, E, Obj, Sub, Handler);
2319 /// Find the position where two subobject designators diverge, or equivalently
2320 /// the length of the common initial subsequence.
2321 static unsigned FindDesignatorMismatch(QualType ObjType,
2322 const SubobjectDesignator &A,
2323 const SubobjectDesignator &B,
2324 bool &WasArrayIndex) {
2325 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2326 for (/**/; I != N; ++I) {
2327 if (!ObjType.isNull() &&
2328 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2329 // Next subobject is an array element.
2330 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2331 WasArrayIndex = true;
2334 if (ObjType->isAnyComplexType())
2335 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2337 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2339 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2340 WasArrayIndex = false;
2343 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2344 // Next subobject is a field.
2345 ObjType = FD->getType();
2347 // Next subobject is a base class.
2348 ObjType = QualType();
2351 WasArrayIndex = false;
2355 /// Determine whether the given subobject designators refer to elements of the
2356 /// same array object.
2357 static bool AreElementsOfSameArray(QualType ObjType,
2358 const SubobjectDesignator &A,
2359 const SubobjectDesignator &B) {
2360 if (A.Entries.size() != B.Entries.size())
2363 bool IsArray = A.MostDerivedArraySize != 0;
2364 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2365 // A is a subobject of the array element.
2368 // If A (and B) designates an array element, the last entry will be the array
2369 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2370 // of length 1' case, and the entire path must match.
2372 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2373 return CommonLength >= A.Entries.size() - IsArray;
2376 /// Find the complete object to which an LValue refers.
2377 CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2378 const LValue &LVal, QualType LValType) {
2380 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2381 return CompleteObject();
2384 CallStackFrame *Frame = 0;
2385 if (LVal.CallIndex) {
2386 Frame = Info.getCallFrame(LVal.CallIndex);
2388 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2389 << AK << LVal.Base.is<const ValueDecl*>();
2390 NoteLValueLocation(Info, LVal.Base);
2391 return CompleteObject();
2395 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2396 // is not a constant expression (even if the object is non-volatile). We also
2397 // apply this rule to C++98, in order to conform to the expected 'volatile'
2399 if (LValType.isVolatileQualified()) {
2400 if (Info.getLangOpts().CPlusPlus)
2401 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2405 return CompleteObject();
2408 // Compute value storage location and type of base object.
2409 APValue *BaseVal = 0;
2410 QualType BaseType = getType(LVal.Base);
2412 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2413 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2414 // In C++11, constexpr, non-volatile variables initialized with constant
2415 // expressions are constant expressions too. Inside constexpr functions,
2416 // parameters are constant expressions even if they're non-const.
2417 // In C++1y, objects local to a constant expression (those with a Frame) are
2418 // both readable and writable inside constant expressions.
2419 // In C, such things can also be folded, although they are not ICEs.
2420 const VarDecl *VD = dyn_cast<VarDecl>(D);
2422 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2425 if (!VD || VD->isInvalidDecl()) {
2427 return CompleteObject();
2430 // Accesses of volatile-qualified objects are not allowed.
2431 if (BaseType.isVolatileQualified()) {
2432 if (Info.getLangOpts().CPlusPlus) {
2433 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2435 Info.Note(VD->getLocation(), diag::note_declared_at);
2439 return CompleteObject();
2442 // Unless we're looking at a local variable or argument in a constexpr call,
2443 // the variable we're reading must be const.
2445 if (Info.getLangOpts().CPlusPlus1y &&
2446 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2447 // OK, we can read and modify an object if we're in the process of
2448 // evaluating its initializer, because its lifetime began in this
2450 } else if (AK != AK_Read) {
2451 // All the remaining cases only permit reading.
2452 Info.Diag(E, diag::note_constexpr_modify_global);
2453 return CompleteObject();
2454 } else if (VD->isConstexpr()) {
2455 // OK, we can read this variable.
2456 } else if (BaseType->isIntegralOrEnumerationType()) {
2457 if (!BaseType.isConstQualified()) {
2458 if (Info.getLangOpts().CPlusPlus) {
2459 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2460 Info.Note(VD->getLocation(), diag::note_declared_at);
2464 return CompleteObject();
2466 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2467 // We support folding of const floating-point types, in order to make
2468 // static const data members of such types (supported as an extension)
2470 if (Info.getLangOpts().CPlusPlus11) {
2471 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2472 Info.Note(VD->getLocation(), diag::note_declared_at);
2477 // FIXME: Allow folding of values of any literal type in all languages.
2478 if (Info.getLangOpts().CPlusPlus11) {
2479 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2480 Info.Note(VD->getLocation(), diag::note_declared_at);
2484 return CompleteObject();
2488 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2489 return CompleteObject();
2491 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2494 if (const MaterializeTemporaryExpr *MTE =
2495 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2496 assert(MTE->getStorageDuration() == SD_Static &&
2497 "should have a frame for a non-global materialized temporary");
2499 // Per C++1y [expr.const]p2:
2500 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2501 // - a [...] glvalue of integral or enumeration type that refers to
2502 // a non-volatile const object [...]
2504 // - a [...] glvalue of literal type that refers to a non-volatile
2505 // object whose lifetime began within the evaluation of e.
2507 // C++11 misses the 'began within the evaluation of e' check and
2508 // instead allows all temporaries, including things like:
2511 // constexpr int k = r;
2512 // Therefore we use the C++1y rules in C++11 too.
2513 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2514 const ValueDecl *ED = MTE->getExtendingDecl();
2515 if (!(BaseType.isConstQualified() &&
2516 BaseType->isIntegralOrEnumerationType()) &&
2517 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2518 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2519 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2520 return CompleteObject();
2523 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2524 assert(BaseVal && "got reference to unevaluated temporary");
2527 return CompleteObject();
2530 BaseVal = Frame->getTemporary(Base);
2531 assert(BaseVal && "missing value for temporary");
2534 // Volatile temporary objects cannot be accessed in constant expressions.
2535 if (BaseType.isVolatileQualified()) {
2536 if (Info.getLangOpts().CPlusPlus) {
2537 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2539 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2543 return CompleteObject();
2547 // During the construction of an object, it is not yet 'const'.
2548 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2549 // and this doesn't do quite the right thing for const subobjects of the
2550 // object under construction.
2551 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2552 BaseType = Info.Ctx.getCanonicalType(BaseType);
2553 BaseType.removeLocalConst();
2556 // In C++1y, we can't safely access any mutable state when we might be
2557 // evaluating after an unmodeled side effect or an evaluation failure.
2559 // FIXME: Not all local state is mutable. Allow local constant subobjects
2560 // to be read here (but take care with 'mutable' fields).
2561 if (Frame && Info.getLangOpts().CPlusPlus1y &&
2562 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
2563 return CompleteObject();
2565 return CompleteObject(BaseVal, BaseType);
2568 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2569 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2570 /// glvalue referred to by an entity of reference type.
2572 /// \param Info - Information about the ongoing evaluation.
2573 /// \param Conv - The expression for which we are performing the conversion.
2574 /// Used for diagnostics.
2575 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2576 /// case of a non-class type).
2577 /// \param LVal - The glvalue on which we are attempting to perform this action.
2578 /// \param RVal - The produced value will be placed here.
2579 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2581 const LValue &LVal, APValue &RVal) {
2582 if (LVal.Designator.Invalid)
2585 // Check for special cases where there is no existing APValue to look at.
2586 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2587 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2588 !Type.isVolatileQualified()) {
2589 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2590 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2591 // initializer until now for such expressions. Such an expression can't be
2592 // an ICE in C, so this only matters for fold.
2593 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2594 if (Type.isVolatileQualified()) {
2599 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2601 CompleteObject LitObj(&Lit, Base->getType());
2602 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2603 } else if (isa<StringLiteral>(Base)) {
2604 // We represent a string literal array as an lvalue pointing at the
2605 // corresponding expression, rather than building an array of chars.
2606 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2607 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2608 CompleteObject StrObj(&Str, Base->getType());
2609 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
2613 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2614 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
2617 /// Perform an assignment of Val to LVal. Takes ownership of Val.
2618 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
2619 QualType LValType, APValue &Val) {
2620 if (LVal.Designator.Invalid)
2623 if (!Info.getLangOpts().CPlusPlus1y) {
2628 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2629 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
2632 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2633 return T->isSignedIntegerType() &&
2634 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2638 struct CompoundAssignSubobjectHandler {
2641 QualType PromotedLHSType;
2642 BinaryOperatorKind Opcode;
2645 static const AccessKinds AccessKind = AK_Assign;
2647 typedef bool result_type;
2649 bool checkConst(QualType QT) {
2650 // Assigning to a const object has undefined behavior.
2651 if (QT.isConstQualified()) {
2652 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2658 bool failed() { return false; }
2659 bool found(APValue &Subobj, QualType SubobjType) {
2660 switch (Subobj.getKind()) {
2662 return found(Subobj.getInt(), SubobjType);
2663 case APValue::Float:
2664 return found(Subobj.getFloat(), SubobjType);
2665 case APValue::ComplexInt:
2666 case APValue::ComplexFloat:
2667 // FIXME: Implement complex compound assignment.
2670 case APValue::LValue:
2671 return foundPointer(Subobj, SubobjType);
2673 // FIXME: can this happen?
2678 bool found(APSInt &Value, QualType SubobjType) {
2679 if (!checkConst(SubobjType))
2682 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2683 // We don't support compound assignment on integer-cast-to-pointer
2689 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2691 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2693 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2696 bool found(APFloat &Value, QualType SubobjType) {
2697 return checkConst(SubobjType) &&
2698 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2700 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2701 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
2703 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2704 if (!checkConst(SubobjType))
2707 QualType PointeeType;
2708 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2709 PointeeType = PT->getPointeeType();
2711 if (PointeeType.isNull() || !RHS.isInt() ||
2712 (Opcode != BO_Add && Opcode != BO_Sub)) {
2717 int64_t Offset = getExtValue(RHS.getInt());
2718 if (Opcode == BO_Sub)
2722 LVal.setFrom(Info.Ctx, Subobj);
2723 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2725 LVal.moveInto(Subobj);
2728 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2729 llvm_unreachable("shouldn't encounter string elements here");
2732 } // end anonymous namespace
2734 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2736 /// Perform a compound assignment of LVal <op>= RVal.
2737 static bool handleCompoundAssignment(
2738 EvalInfo &Info, const Expr *E,
2739 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2740 BinaryOperatorKind Opcode, const APValue &RVal) {
2741 if (LVal.Designator.Invalid)
2744 if (!Info.getLangOpts().CPlusPlus1y) {
2749 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2750 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2752 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2756 struct IncDecSubobjectHandler {
2759 AccessKinds AccessKind;
2762 typedef bool result_type;
2764 bool checkConst(QualType QT) {
2765 // Assigning to a const object has undefined behavior.
2766 if (QT.isConstQualified()) {
2767 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2773 bool failed() { return false; }
2774 bool found(APValue &Subobj, QualType SubobjType) {
2775 // Stash the old value. Also clear Old, so we don't clobber it later
2776 // if we're post-incrementing a complex.
2782 switch (Subobj.getKind()) {
2784 return found(Subobj.getInt(), SubobjType);
2785 case APValue::Float:
2786 return found(Subobj.getFloat(), SubobjType);
2787 case APValue::ComplexInt:
2788 return found(Subobj.getComplexIntReal(),
2789 SubobjType->castAs<ComplexType>()->getElementType()
2790 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2791 case APValue::ComplexFloat:
2792 return found(Subobj.getComplexFloatReal(),
2793 SubobjType->castAs<ComplexType>()->getElementType()
2794 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2795 case APValue::LValue:
2796 return foundPointer(Subobj, SubobjType);
2798 // FIXME: can this happen?
2803 bool found(APSInt &Value, QualType SubobjType) {
2804 if (!checkConst(SubobjType))
2807 if (!SubobjType->isIntegerType()) {
2808 // We don't support increment / decrement on integer-cast-to-pointer
2814 if (Old) *Old = APValue(Value);
2816 // bool arithmetic promotes to int, and the conversion back to bool
2817 // doesn't reduce mod 2^n, so special-case it.
2818 if (SubobjType->isBooleanType()) {
2819 if (AccessKind == AK_Increment)
2826 bool WasNegative = Value.isNegative();
2827 if (AccessKind == AK_Increment) {
2830 if (!WasNegative && Value.isNegative() &&
2831 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2832 APSInt ActualValue(Value, /*IsUnsigned*/true);
2833 HandleOverflow(Info, E, ActualValue, SubobjType);
2838 if (WasNegative && !Value.isNegative() &&
2839 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2840 unsigned BitWidth = Value.getBitWidth();
2841 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2842 ActualValue.setBit(BitWidth);
2843 HandleOverflow(Info, E, ActualValue, SubobjType);
2848 bool found(APFloat &Value, QualType SubobjType) {
2849 if (!checkConst(SubobjType))
2852 if (Old) *Old = APValue(Value);
2854 APFloat One(Value.getSemantics(), 1);
2855 if (AccessKind == AK_Increment)
2856 Value.add(One, APFloat::rmNearestTiesToEven);
2858 Value.subtract(One, APFloat::rmNearestTiesToEven);
2861 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2862 if (!checkConst(SubobjType))
2865 QualType PointeeType;
2866 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2867 PointeeType = PT->getPointeeType();
2874 LVal.setFrom(Info.Ctx, Subobj);
2875 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2876 AccessKind == AK_Increment ? 1 : -1))
2878 LVal.moveInto(Subobj);
2881 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2882 llvm_unreachable("shouldn't encounter string elements here");
2885 } // end anonymous namespace
2887 /// Perform an increment or decrement on LVal.
2888 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
2889 QualType LValType, bool IsIncrement, APValue *Old) {
2890 if (LVal.Designator.Invalid)
2893 if (!Info.getLangOpts().CPlusPlus1y) {
2898 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
2899 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
2900 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
2901 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2904 /// Build an lvalue for the object argument of a member function call.
2905 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
2907 if (Object->getType()->isPointerType())
2908 return EvaluatePointer(Object, This, Info);
2910 if (Object->isGLValue())
2911 return EvaluateLValue(Object, This, Info);
2913 if (Object->getType()->isLiteralType(Info.Ctx))
2914 return EvaluateTemporary(Object, This, Info);
2919 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
2920 /// lvalue referring to the result.
2922 /// \param Info - Information about the ongoing evaluation.
2923 /// \param LV - An lvalue referring to the base of the member pointer.
2924 /// \param RHS - The member pointer expression.
2925 /// \param IncludeMember - Specifies whether the member itself is included in
2926 /// the resulting LValue subobject designator. This is not possible when
2927 /// creating a bound member function.
2928 /// \return The field or method declaration to which the member pointer refers,
2929 /// or 0 if evaluation fails.
2930 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
2934 bool IncludeMember = true) {
2936 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
2939 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
2940 // member value, the behavior is undefined.
2941 if (!MemPtr.getDecl()) {
2942 // FIXME: Specific diagnostic.
2947 if (MemPtr.isDerivedMember()) {
2948 // This is a member of some derived class. Truncate LV appropriately.
2949 // The end of the derived-to-base path for the base object must match the
2950 // derived-to-base path for the member pointer.
2951 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
2952 LV.Designator.Entries.size()) {
2956 unsigned PathLengthToMember =
2957 LV.Designator.Entries.size() - MemPtr.Path.size();
2958 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
2959 const CXXRecordDecl *LVDecl = getAsBaseClass(
2960 LV.Designator.Entries[PathLengthToMember + I]);
2961 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
2962 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
2968 // Truncate the lvalue to the appropriate derived class.
2969 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
2970 PathLengthToMember))
2972 } else if (!MemPtr.Path.empty()) {
2973 // Extend the LValue path with the member pointer's path.
2974 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
2975 MemPtr.Path.size() + IncludeMember);
2977 // Walk down to the appropriate base class.
2978 if (const PointerType *PT = LVType->getAs<PointerType>())
2979 LVType = PT->getPointeeType();
2980 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
2981 assert(RD && "member pointer access on non-class-type expression");
2982 // The first class in the path is that of the lvalue.
2983 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2984 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
2985 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
2989 // Finally cast to the class containing the member.
2990 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
2991 MemPtr.getContainingRecord()))
2995 // Add the member. Note that we cannot build bound member functions here.
2996 if (IncludeMember) {
2997 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2998 if (!HandleLValueMember(Info, RHS, LV, FD))
3000 } else if (const IndirectFieldDecl *IFD =
3001 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3002 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3005 llvm_unreachable("can't construct reference to bound member function");
3009 return MemPtr.getDecl();
3012 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3013 const BinaryOperator *BO,
3015 bool IncludeMember = true) {
3016 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3018 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3019 if (Info.keepEvaluatingAfterFailure()) {
3021 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3026 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3027 BO->getRHS(), IncludeMember);
3030 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3031 /// the provided lvalue, which currently refers to the base object.
3032 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3034 SubobjectDesignator &D = Result.Designator;
3035 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3038 QualType TargetQT = E->getType();
3039 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3040 TargetQT = PT->getPointeeType();
3042 // Check this cast lands within the final derived-to-base subobject path.
3043 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3044 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3045 << D.MostDerivedType << TargetQT;
3049 // Check the type of the final cast. We don't need to check the path,
3050 // since a cast can only be formed if the path is unique.
3051 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3052 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3053 const CXXRecordDecl *FinalType;
3054 if (NewEntriesSize == D.MostDerivedPathLength)
3055 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3057 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3058 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3059 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3060 << D.MostDerivedType << TargetQT;
3064 // Truncate the lvalue to the appropriate derived class.
3065 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3069 enum EvalStmtResult {
3070 /// Evaluation failed.
3072 /// Hit a 'return' statement.
3074 /// Evaluation succeeded.
3076 /// Hit a 'continue' statement.
3078 /// Hit a 'break' statement.
3080 /// Still scanning for 'case' or 'default' statement.
3085 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3086 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3087 // We don't need to evaluate the initializer for a static local.
3088 if (!VD->hasLocalStorage())
3092 Result.set(VD, Info.CurrentCall->Index);
3093 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3095 if (!VD->getInit()) {
3096 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3097 << false << VD->getType();
3102 if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
3103 // Wipe out any partially-computed value, to allow tracking that this
3104 // evaluation failed.
3113 /// Evaluate a condition (either a variable declaration or an expression).
3114 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3115 const Expr *Cond, bool &Result) {
3116 FullExpressionRAII Scope(Info);
3117 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3119 return EvaluateAsBooleanCondition(Cond, Result, Info);
3122 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3123 const Stmt *S, const SwitchCase *SC = 0);
3125 /// Evaluate the body of a loop, and translate the result as appropriate.
3126 static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
3128 const SwitchCase *Case = 0) {
3129 BlockScopeRAII Scope(Info);
3130 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3132 return ESR_Succeeded;
3135 return ESR_Continue;
3138 case ESR_CaseNotFound:
3141 llvm_unreachable("Invalid EvalStmtResult!");
3144 /// Evaluate a switch statement.
3145 static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3146 const SwitchStmt *SS) {
3147 BlockScopeRAII Scope(Info);
3149 // Evaluate the switch condition.
3152 FullExpressionRAII Scope(Info);
3153 if (SS->getConditionVariable() &&
3154 !EvaluateDecl(Info, SS->getConditionVariable()))
3156 if (!EvaluateInteger(SS->getCond(), Value, Info))
3160 // Find the switch case corresponding to the value of the condition.
3161 // FIXME: Cache this lookup.
3162 const SwitchCase *Found = 0;
3163 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3164 SC = SC->getNextSwitchCase()) {
3165 if (isa<DefaultStmt>(SC)) {
3170 const CaseStmt *CS = cast<CaseStmt>(SC);
3171 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3172 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3174 if (LHS <= Value && Value <= RHS) {
3181 return ESR_Succeeded;
3183 // Search the switch body for the switch case and evaluate it from there.
3184 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3186 return ESR_Succeeded;
3192 case ESR_CaseNotFound:
3193 // This can only happen if the switch case is nested within a statement
3194 // expression. We have no intention of supporting that.
3195 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3198 llvm_unreachable("Invalid EvalStmtResult!");
3201 // Evaluate a statement.
3202 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
3203 const Stmt *S, const SwitchCase *Case) {
3204 if (!Info.nextStep(S))
3207 // If we're hunting down a 'case' or 'default' label, recurse through
3208 // substatements until we hit the label.
3210 // FIXME: We don't start the lifetime of objects whose initialization we
3211 // jump over. However, such objects must be of class type with a trivial
3212 // default constructor that initialize all subobjects, so must be empty,
3213 // so this almost never matters.
3214 switch (S->getStmtClass()) {
3215 case Stmt::CompoundStmtClass:
3216 // FIXME: Precompute which substatement of a compound statement we
3217 // would jump to, and go straight there rather than performing a
3218 // linear scan each time.
3219 case Stmt::LabelStmtClass:
3220 case Stmt::AttributedStmtClass:
3221 case Stmt::DoStmtClass:
3224 case Stmt::CaseStmtClass:
3225 case Stmt::DefaultStmtClass:
3230 case Stmt::IfStmtClass: {
3231 // FIXME: Precompute which side of an 'if' we would jump to, and go
3232 // straight there rather than scanning both sides.
3233 const IfStmt *IS = cast<IfStmt>(S);
3235 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3236 // preceded by our switch label.
3237 BlockScopeRAII Scope(Info);
3239 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3240 if (ESR != ESR_CaseNotFound || !IS->getElse())
3242 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3245 case Stmt::WhileStmtClass: {
3246 EvalStmtResult ESR =
3247 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3248 if (ESR != ESR_Continue)
3253 case Stmt::ForStmtClass: {
3254 const ForStmt *FS = cast<ForStmt>(S);
3255 EvalStmtResult ESR =
3256 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3257 if (ESR != ESR_Continue)
3260 FullExpressionRAII IncScope(Info);
3261 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3267 case Stmt::DeclStmtClass:
3268 // FIXME: If the variable has initialization that can't be jumped over,
3269 // bail out of any immediately-surrounding compound-statement too.
3271 return ESR_CaseNotFound;
3275 switch (S->getStmtClass()) {
3277 if (const Expr *E = dyn_cast<Expr>(S)) {
3278 // Don't bother evaluating beyond an expression-statement which couldn't
3280 FullExpressionRAII Scope(Info);
3281 if (!EvaluateIgnoredValue(Info, E))
3283 return ESR_Succeeded;
3286 Info.Diag(S->getLocStart());
3289 case Stmt::NullStmtClass:
3290 return ESR_Succeeded;
3292 case Stmt::DeclStmtClass: {
3293 const DeclStmt *DS = cast<DeclStmt>(S);
3294 for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
3295 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
3296 // Each declaration initialization is its own full-expression.
3297 // FIXME: This isn't quite right; if we're performing aggregate
3298 // initialization, each braced subexpression is its own full-expression.
3299 FullExpressionRAII Scope(Info);
3300 if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
3303 return ESR_Succeeded;
3306 case Stmt::ReturnStmtClass: {
3307 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3308 FullExpressionRAII Scope(Info);
3309 if (RetExpr && !Evaluate(Result, Info, RetExpr))
3311 return ESR_Returned;
3314 case Stmt::CompoundStmtClass: {
3315 BlockScopeRAII Scope(Info);
3317 const CompoundStmt *CS = cast<CompoundStmt>(S);
3318 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
3319 BE = CS->body_end(); BI != BE; ++BI) {
3320 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI, Case);
3321 if (ESR == ESR_Succeeded)
3323 else if (ESR != ESR_CaseNotFound)
3326 return Case ? ESR_CaseNotFound : ESR_Succeeded;
3329 case Stmt::IfStmtClass: {
3330 const IfStmt *IS = cast<IfStmt>(S);
3332 // Evaluate the condition, as either a var decl or as an expression.
3333 BlockScopeRAII Scope(Info);
3335 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3338 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3339 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3340 if (ESR != ESR_Succeeded)
3343 return ESR_Succeeded;
3346 case Stmt::WhileStmtClass: {
3347 const WhileStmt *WS = cast<WhileStmt>(S);
3349 BlockScopeRAII Scope(Info);
3351 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3357 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3358 if (ESR != ESR_Continue)
3361 return ESR_Succeeded;
3364 case Stmt::DoStmtClass: {
3365 const DoStmt *DS = cast<DoStmt>(S);
3368 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3369 if (ESR != ESR_Continue)
3373 FullExpressionRAII CondScope(Info);
3374 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3377 return ESR_Succeeded;
3380 case Stmt::ForStmtClass: {
3381 const ForStmt *FS = cast<ForStmt>(S);
3382 BlockScopeRAII Scope(Info);
3383 if (FS->getInit()) {
3384 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3385 if (ESR != ESR_Succeeded)
3389 BlockScopeRAII Scope(Info);
3390 bool Continue = true;
3391 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3392 FS->getCond(), Continue))
3397 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3398 if (ESR != ESR_Continue)
3402 FullExpressionRAII IncScope(Info);
3403 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3407 return ESR_Succeeded;
3410 case Stmt::CXXForRangeStmtClass: {
3411 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
3412 BlockScopeRAII Scope(Info);
3414 // Initialize the __range variable.
3415 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3416 if (ESR != ESR_Succeeded)
3419 // Create the __begin and __end iterators.
3420 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3421 if (ESR != ESR_Succeeded)
3425 // Condition: __begin != __end.
3427 bool Continue = true;
3428 FullExpressionRAII CondExpr(Info);
3429 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3435 // User's variable declaration, initialized by *__begin.
3436 BlockScopeRAII InnerScope(Info);
3437 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3438 if (ESR != ESR_Succeeded)
3442 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3443 if (ESR != ESR_Continue)
3446 // Increment: ++__begin
3447 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3451 return ESR_Succeeded;
3454 case Stmt::SwitchStmtClass:
3455 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3457 case Stmt::ContinueStmtClass:
3458 return ESR_Continue;
3460 case Stmt::BreakStmtClass:
3463 case Stmt::LabelStmtClass:
3464 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3466 case Stmt::AttributedStmtClass:
3467 // As a general principle, C++11 attributes can be ignored without
3468 // any semantic impact.
3469 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3472 case Stmt::CaseStmtClass:
3473 case Stmt::DefaultStmtClass:
3474 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
3478 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3479 /// default constructor. If so, we'll fold it whether or not it's marked as
3480 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
3481 /// so we need special handling.
3482 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
3483 const CXXConstructorDecl *CD,
3484 bool IsValueInitialization) {
3485 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3488 // Value-initialization does not call a trivial default constructor, so such a
3489 // call is a core constant expression whether or not the constructor is
3491 if (!CD->isConstexpr() && !IsValueInitialization) {
3492 if (Info.getLangOpts().CPlusPlus11) {
3493 // FIXME: If DiagDecl is an implicitly-declared special member function,
3494 // we should be much more explicit about why it's not constexpr.
3495 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3496 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3497 Info.Note(CD->getLocation(), diag::note_declared_at);
3499 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3505 /// CheckConstexprFunction - Check that a function can be called in a constant
3507 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3508 const FunctionDecl *Declaration,
3509 const FunctionDecl *Definition) {
3510 // Potential constant expressions can contain calls to declared, but not yet
3511 // defined, constexpr functions.
3512 if (Info.checkingPotentialConstantExpression() && !Definition &&
3513 Declaration->isConstexpr())
3516 // Bail out with no diagnostic if the function declaration itself is invalid.
3517 // We will have produced a relevant diagnostic while parsing it.
3518 if (Declaration->isInvalidDecl())
3521 // Can we evaluate this function call?
3522 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3525 if (Info.getLangOpts().CPlusPlus11) {
3526 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
3527 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3528 // should be much more explicit about why it's not constexpr.
3529 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3530 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3532 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3534 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3540 typedef SmallVector<APValue, 8> ArgVector;
3543 /// EvaluateArgs - Evaluate the arguments to a function call.
3544 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3546 bool Success = true;
3547 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
3549 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3550 // If we're checking for a potential constant expression, evaluate all
3551 // initializers even if some of them fail.
3552 if (!Info.keepEvaluatingAfterFailure())
3560 /// Evaluate a function call.
3561 static bool HandleFunctionCall(SourceLocation CallLoc,
3562 const FunctionDecl *Callee, const LValue *This,
3563 ArrayRef<const Expr*> Args, const Stmt *Body,
3564 EvalInfo &Info, APValue &Result) {
3565 ArgVector ArgValues(Args.size());
3566 if (!EvaluateArgs(Args, ArgValues, Info))
3569 if (!Info.CheckCallLimit(CallLoc))
3572 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
3574 // For a trivial copy or move assignment, perform an APValue copy. This is
3575 // essential for unions, where the operations performed by the assignment
3576 // operator cannot be represented as statements.
3577 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3578 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3580 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3582 RHS.setFrom(Info.Ctx, ArgValues[0]);
3584 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3587 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3590 This->moveInto(Result);
3594 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
3595 if (ESR == ESR_Succeeded) {
3596 if (Callee->getResultType()->isVoidType())
3598 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
3600 return ESR == ESR_Returned;
3603 /// Evaluate a constructor call.
3604 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
3605 ArrayRef<const Expr*> Args,
3606 const CXXConstructorDecl *Definition,
3607 EvalInfo &Info, APValue &Result) {
3608 ArgVector ArgValues(Args.size());
3609 if (!EvaluateArgs(Args, ArgValues, Info))
3612 if (!Info.CheckCallLimit(CallLoc))
3615 const CXXRecordDecl *RD = Definition->getParent();
3616 if (RD->getNumVBases()) {
3617 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3621 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
3623 // If it's a delegating constructor, just delegate.
3624 if (Definition->isDelegatingConstructor()) {
3625 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
3627 FullExpressionRAII InitScope(Info);
3628 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3631 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3634 // For a trivial copy or move constructor, perform an APValue copy. This is
3635 // essential for unions, where the operations performed by the constructor
3636 // cannot be represented by ctor-initializers.
3637 if (Definition->isDefaulted() &&
3638 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3639 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
3641 RHS.setFrom(Info.Ctx, ArgValues[0]);
3642 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3646 // Reserve space for the struct members.
3647 if (!RD->isUnion() && Result.isUninit())
3648 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3649 std::distance(RD->field_begin(), RD->field_end()));
3651 if (RD->isInvalidDecl()) return false;
3652 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3654 // A scope for temporaries lifetime-extended by reference members.
3655 BlockScopeRAII LifetimeExtendedScope(Info);
3657 bool Success = true;
3658 unsigned BasesSeen = 0;
3660 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3662 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
3663 E = Definition->init_end(); I != E; ++I) {
3664 LValue Subobject = This;
3665 APValue *Value = &Result;
3667 // Determine the subobject to initialize.
3669 if ((*I)->isBaseInitializer()) {
3670 QualType BaseType((*I)->getBaseClass(), 0);
3672 // Non-virtual base classes are initialized in the order in the class
3673 // definition. We have already checked for virtual base classes.
3674 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3675 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3676 "base class initializers not in expected order");
3679 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
3680 BaseType->getAsCXXRecordDecl(), &Layout))
3682 Value = &Result.getStructBase(BasesSeen++);
3683 } else if ((FD = (*I)->getMember())) {
3684 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
3686 if (RD->isUnion()) {
3687 Result = APValue(FD);
3688 Value = &Result.getUnionValue();
3690 Value = &Result.getStructField(FD->getFieldIndex());
3692 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
3693 // Walk the indirect field decl's chain to find the object to initialize,
3694 // and make sure we've initialized every step along it.
3695 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
3696 CE = IFD->chain_end();
3698 FD = cast<FieldDecl>(*C);
3699 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3700 // Switch the union field if it differs. This happens if we had
3701 // preceding zero-initialization, and we're now initializing a union
3702 // subobject other than the first.
3703 // FIXME: In this case, the values of the other subobjects are
3704 // specified, since zero-initialization sets all padding bits to zero.
3705 if (Value->isUninit() ||
3706 (Value->isUnion() && Value->getUnionField() != FD)) {
3708 *Value = APValue(FD);
3710 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
3711 std::distance(CD->field_begin(), CD->field_end()));
3713 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
3716 Value = &Value->getUnionValue();
3718 Value = &Value->getStructField(FD->getFieldIndex());
3721 llvm_unreachable("unknown base initializer kind");
3724 FullExpressionRAII InitScope(Info);
3725 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit()) ||
3726 (FD && FD->isBitField() && !truncateBitfieldValue(Info, (*I)->getInit(),
3728 // If we're checking for a potential constant expression, evaluate all
3729 // initializers even if some of them fail.
3730 if (!Info.keepEvaluatingAfterFailure())
3737 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
3740 //===----------------------------------------------------------------------===//
3741 // Generic Evaluation
3742 //===----------------------------------------------------------------------===//
3745 // FIXME: RetTy is always bool. Remove it.
3746 template <class Derived, typename RetTy=bool>
3747 class ExprEvaluatorBase
3748 : public ConstStmtVisitor<Derived, RetTy> {
3750 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
3751 return static_cast<Derived*>(this)->Success(V, E);
3753 RetTy DerivedZeroInitialization(const Expr *E) {
3754 return static_cast<Derived*>(this)->ZeroInitialization(E);
3757 // Check whether a conditional operator with a non-constant condition is a
3758 // potential constant expression. If neither arm is a potential constant
3759 // expression, then the conditional operator is not either.
3760 template<typename ConditionalOperator>
3761 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
3762 assert(Info.checkingPotentialConstantExpression());
3764 // Speculatively evaluate both arms.
3766 SmallVector<PartialDiagnosticAt, 8> Diag;
3767 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3769 StmtVisitorTy::Visit(E->getFalseExpr());
3774 StmtVisitorTy::Visit(E->getTrueExpr());
3779 Error(E, diag::note_constexpr_conditional_never_const);
3783 template<typename ConditionalOperator>
3784 bool HandleConditionalOperator(const ConditionalOperator *E) {
3786 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
3787 if (Info.checkingPotentialConstantExpression())
3788 CheckPotentialConstantConditional(E);
3792 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3793 return StmtVisitorTy::Visit(EvalExpr);
3798 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
3799 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3801 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
3802 return Info.CCEDiag(E, D);
3805 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
3808 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3810 EvalInfo &getEvalInfo() { return Info; }
3812 /// Report an evaluation error. This should only be called when an error is
3813 /// first discovered. When propagating an error, just return false.
3814 bool Error(const Expr *E, diag::kind D) {
3818 bool Error(const Expr *E) {
3819 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3822 RetTy VisitStmt(const Stmt *) {
3823 llvm_unreachable("Expression evaluator should not be called on stmts");
3825 RetTy VisitExpr(const Expr *E) {
3829 RetTy VisitParenExpr(const ParenExpr *E)
3830 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3831 RetTy VisitUnaryExtension(const UnaryOperator *E)
3832 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3833 RetTy VisitUnaryPlus(const UnaryOperator *E)
3834 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3835 RetTy VisitChooseExpr(const ChooseExpr *E)
3836 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
3837 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
3838 { return StmtVisitorTy::Visit(E->getResultExpr()); }
3839 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
3840 { return StmtVisitorTy::Visit(E->getReplacement()); }
3841 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
3842 { return StmtVisitorTy::Visit(E->getExpr()); }
3843 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
3844 // The initializer may not have been parsed yet, or might be erroneous.
3847 return StmtVisitorTy::Visit(E->getExpr());
3849 // We cannot create any objects for which cleanups are required, so there is
3850 // nothing to do here; all cleanups must come from unevaluated subexpressions.
3851 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
3852 { return StmtVisitorTy::Visit(E->getSubExpr()); }
3854 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
3855 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3856 return static_cast<Derived*>(this)->VisitCastExpr(E);
3858 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
3859 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3860 return static_cast<Derived*>(this)->VisitCastExpr(E);
3863 RetTy VisitBinaryOperator(const BinaryOperator *E) {
3864 switch (E->getOpcode()) {
3869 VisitIgnoredValue(E->getLHS());
3870 return StmtVisitorTy::Visit(E->getRHS());
3875 if (!HandleMemberPointerAccess(Info, E, Obj))
3878 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
3880 return DerivedSuccess(Result, E);
3885 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
3886 // Evaluate and cache the common expression. We treat it as a temporary,
3887 // even though it's not quite the same thing.
3888 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
3889 Info, E->getCommon()))
3892 return HandleConditionalOperator(E);
3895 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
3896 bool IsBcpCall = false;
3897 // If the condition (ignoring parens) is a __builtin_constant_p call,
3898 // the result is a constant expression if it can be folded without
3899 // side-effects. This is an important GNU extension. See GCC PR38377
3901 if (const CallExpr *CallCE =
3902 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
3903 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
3906 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
3907 // constant expression; we can't check whether it's potentially foldable.
3908 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
3911 FoldConstant Fold(Info, IsBcpCall);
3912 if (!HandleConditionalOperator(E)) {
3913 Fold.keepDiagnostics();
3920 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
3921 if (APValue *Value = Info.CurrentCall->getTemporary(E))
3922 return DerivedSuccess(*Value, E);
3924 const Expr *Source = E->getSourceExpr();
3927 if (Source == E) { // sanity checking.
3928 assert(0 && "OpaqueValueExpr recursively refers to itself");
3931 return StmtVisitorTy::Visit(Source);
3934 RetTy VisitCallExpr(const CallExpr *E) {
3935 const Expr *Callee = E->getCallee()->IgnoreParens();
3936 QualType CalleeType = Callee->getType();
3938 const FunctionDecl *FD = 0;
3939 LValue *This = 0, ThisVal;
3940 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
3941 bool HasQualifier = false;
3943 // Extract function decl and 'this' pointer from the callee.
3944 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
3945 const ValueDecl *Member = 0;
3946 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
3947 // Explicit bound member calls, such as x.f() or p->g();
3948 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
3950 Member = ME->getMemberDecl();
3952 HasQualifier = ME->hasQualifier();
3953 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
3954 // Indirect bound member calls ('.*' or '->*').
3955 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
3956 if (!Member) return false;
3959 return Error(Callee);
3961 FD = dyn_cast<FunctionDecl>(Member);
3963 return Error(Callee);
3964 } else if (CalleeType->isFunctionPointerType()) {
3966 if (!EvaluatePointer(Callee, Call, Info))
3969 if (!Call.getLValueOffset().isZero())
3970 return Error(Callee);
3971 FD = dyn_cast_or_null<FunctionDecl>(
3972 Call.getLValueBase().dyn_cast<const ValueDecl*>());
3974 return Error(Callee);
3976 // Overloaded operator calls to member functions are represented as normal
3977 // calls with '*this' as the first argument.
3978 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
3979 if (MD && !MD->isStatic()) {
3980 // FIXME: When selecting an implicit conversion for an overloaded
3981 // operator delete, we sometimes try to evaluate calls to conversion
3982 // operators without a 'this' parameter!
3986 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
3989 Args = Args.slice(1);
3992 // Don't call function pointers which have been cast to some other type.
3993 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
3998 if (This && !This->checkSubobject(Info, E, CSK_This))
4001 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4002 // calls to such functions in constant expressions.
4003 if (This && !HasQualifier &&
4004 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4005 return Error(E, diag::note_constexpr_virtual_call);
4007 const FunctionDecl *Definition = 0;
4008 Stmt *Body = FD->getBody(Definition);
4011 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
4012 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4016 return DerivedSuccess(Result, E);
4019 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4020 return StmtVisitorTy::Visit(E->getInitializer());
4022 RetTy VisitInitListExpr(const InitListExpr *E) {
4023 if (E->getNumInits() == 0)
4024 return DerivedZeroInitialization(E);
4025 if (E->getNumInits() == 1)
4026 return StmtVisitorTy::Visit(E->getInit(0));
4029 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4030 return DerivedZeroInitialization(E);
4032 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4033 return DerivedZeroInitialization(E);
4035 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4036 return DerivedZeroInitialization(E);
4039 /// A member expression where the object is a prvalue is itself a prvalue.
4040 RetTy VisitMemberExpr(const MemberExpr *E) {
4041 assert(!E->isArrow() && "missing call to bound member function?");
4044 if (!Evaluate(Val, Info, E->getBase()))
4047 QualType BaseTy = E->getBase()->getType();
4049 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4050 if (!FD) return Error(E);
4051 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4052 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4053 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4055 CompleteObject Obj(&Val, BaseTy);
4056 SubobjectDesignator Designator(BaseTy);
4057 Designator.addDeclUnchecked(FD);
4060 return extractSubobject(Info, E, Obj, Designator, Result) &&
4061 DerivedSuccess(Result, E);
4064 RetTy VisitCastExpr(const CastExpr *E) {
4065 switch (E->getCastKind()) {
4069 case CK_AtomicToNonAtomic: {
4071 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4073 return DerivedSuccess(AtomicVal, E);
4077 case CK_UserDefinedConversion:
4078 return StmtVisitorTy::Visit(E->getSubExpr());
4080 case CK_LValueToRValue: {
4082 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4085 // Note, we use the subexpression's type in order to retain cv-qualifiers.
4086 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4089 return DerivedSuccess(RVal, E);
4096 RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
4097 return VisitUnaryPostIncDec(UO);
4099 RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
4100 return VisitUnaryPostIncDec(UO);
4102 RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
4103 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4107 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4110 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4111 UO->isIncrementOp(), &RVal))
4113 return DerivedSuccess(RVal, UO);
4116 RetTy VisitStmtExpr(const StmtExpr *E) {
4117 // We will have checked the full-expressions inside the statement expression
4118 // when they were completed, and don't need to check them again now.
4119 if (Info.checkingForOverflow())
4122 BlockScopeRAII Scope(Info);
4123 const CompoundStmt *CS = E->getSubStmt();
4124 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4125 BE = CS->body_end();
4128 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4130 Info.Diag((*BI)->getLocStart(),
4131 diag::note_constexpr_stmt_expr_unsupported);
4134 return this->Visit(FinalExpr);
4137 APValue ReturnValue;
4138 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4139 if (ESR != ESR_Succeeded) {
4140 // FIXME: If the statement-expression terminated due to 'return',
4141 // 'break', or 'continue', it would be nice to propagate that to
4142 // the outer statement evaluation rather than bailing out.
4143 if (ESR != ESR_Failed)
4144 Info.Diag((*BI)->getLocStart(),
4145 diag::note_constexpr_stmt_expr_unsupported);
4151 /// Visit a value which is evaluated, but whose value is ignored.
4152 void VisitIgnoredValue(const Expr *E) {
4153 EvaluateIgnoredValue(Info, E);
4159 //===----------------------------------------------------------------------===//
4160 // Common base class for lvalue and temporary evaluation.
4161 //===----------------------------------------------------------------------===//
4163 template<class Derived>
4164 class LValueExprEvaluatorBase
4165 : public ExprEvaluatorBase<Derived, bool> {
4168 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4169 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
4171 bool Success(APValue::LValueBase B) {
4177 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4178 ExprEvaluatorBaseTy(Info), Result(Result) {}
4180 bool Success(const APValue &V, const Expr *E) {
4181 Result.setFrom(this->Info.Ctx, V);
4185 bool VisitMemberExpr(const MemberExpr *E) {
4186 // Handle non-static data members.
4189 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4191 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4192 } else if (E->getBase()->isRValue()) {
4193 assert(E->getBase()->getType()->isRecordType());
4194 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4196 BaseTy = E->getBase()->getType();
4198 if (!this->Visit(E->getBase()))
4200 BaseTy = E->getBase()->getType();
4203 const ValueDecl *MD = E->getMemberDecl();
4204 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4205 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4206 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4208 if (!HandleLValueMember(this->Info, E, Result, FD))
4210 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4211 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4214 return this->Error(E);
4216 if (MD->getType()->isReferenceType()) {
4218 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4221 return Success(RefValue, E);
4226 bool VisitBinaryOperator(const BinaryOperator *E) {
4227 switch (E->getOpcode()) {
4229 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4233 return HandleMemberPointerAccess(this->Info, E, Result);
4237 bool VisitCastExpr(const CastExpr *E) {
4238 switch (E->getCastKind()) {
4240 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4242 case CK_DerivedToBase:
4243 case CK_UncheckedDerivedToBase:
4244 if (!this->Visit(E->getSubExpr()))
4247 // Now figure out the necessary offset to add to the base LV to get from
4248 // the derived class to the base class.
4249 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4256 //===----------------------------------------------------------------------===//
4257 // LValue Evaluation
4259 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4260 // function designators (in C), decl references to void objects (in C), and
4261 // temporaries (if building with -Wno-address-of-temporary).
4263 // LValue evaluation produces values comprising a base expression of one of the
4269 // * CompoundLiteralExpr in C
4273 // * ObjCStringLiteralExpr
4277 // * CallExpr for a MakeStringConstant builtin
4278 // - Locals and temporaries
4279 // * MaterializeTemporaryExpr
4280 // * Any Expr, with a CallIndex indicating the function in which the temporary
4281 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
4282 // from the AST (FIXME).
4283 // * A MaterializeTemporaryExpr that has static storage duration, with no
4284 // CallIndex, for a lifetime-extended temporary.
4285 // plus an offset in bytes.
4286 //===----------------------------------------------------------------------===//
4288 class LValueExprEvaluator
4289 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
4291 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4292 LValueExprEvaluatorBaseTy(Info, Result) {}
4294 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
4295 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
4297 bool VisitDeclRefExpr(const DeclRefExpr *E);
4298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
4299 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
4300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4301 bool VisitMemberExpr(const MemberExpr *E);
4302 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4303 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
4304 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
4305 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
4306 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4307 bool VisitUnaryDeref(const UnaryOperator *E);
4308 bool VisitUnaryReal(const UnaryOperator *E);
4309 bool VisitUnaryImag(const UnaryOperator *E);
4310 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4311 return VisitUnaryPreIncDec(UO);
4313 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4314 return VisitUnaryPreIncDec(UO);
4316 bool VisitBinAssign(const BinaryOperator *BO);
4317 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
4319 bool VisitCastExpr(const CastExpr *E) {
4320 switch (E->getCastKind()) {
4322 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
4324 case CK_LValueBitCast:
4325 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4326 if (!Visit(E->getSubExpr()))
4328 Result.Designator.setInvalid();
4331 case CK_BaseToDerived:
4332 if (!Visit(E->getSubExpr()))
4334 return HandleBaseToDerivedCast(Info, E, Result);
4338 } // end anonymous namespace
4340 /// Evaluate an expression as an lvalue. This can be legitimately called on
4341 /// expressions which are not glvalues, in two cases:
4342 /// * function designators in C, and
4343 /// * "extern void" objects
4344 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4345 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4346 E->getType()->isVoidType());
4347 return LValueExprEvaluator(Info, Result).Visit(E);
4350 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
4351 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
4353 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
4354 return VisitVarDecl(E, VD);
4358 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
4359 CallStackFrame *Frame = 0;
4360 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4361 Frame = Info.CurrentCall;
4363 if (!VD->getType()->isReferenceType()) {
4365 Result.set(VD, Frame->Index);
4372 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
4374 if (V->isUninit()) {
4375 if (!Info.checkingPotentialConstantExpression())
4376 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4379 return Success(*V, E);
4382 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4383 const MaterializeTemporaryExpr *E) {
4384 // Walk through the expression to find the materialized temporary itself.
4385 SmallVector<const Expr *, 2> CommaLHSs;
4386 SmallVector<SubobjectAdjustment, 2> Adjustments;
4387 const Expr *Inner = E->GetTemporaryExpr()->
4388 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
4390 // If we passed any comma operators, evaluate their LHSs.
4391 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4392 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4395 // A materialized temporary with static storage duration can appear within the
4396 // result of a constant expression evaluation, so we need to preserve its
4397 // value for use outside this evaluation.
4399 if (E->getStorageDuration() == SD_Static) {
4400 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
4404 Value = &Info.CurrentCall->
4405 createTemporary(E, E->getStorageDuration() == SD_Automatic);
4406 Result.set(E, Info.CurrentCall->Index);
4409 QualType Type = Inner->getType();
4411 // Materialize the temporary itself.
4412 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4413 (E->getStorageDuration() == SD_Static &&
4414 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4419 // Adjust our lvalue to refer to the desired subobject.
4420 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4422 switch (Adjustments[I].Kind) {
4423 case SubobjectAdjustment::DerivedToBaseAdjustment:
4424 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4427 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4430 case SubobjectAdjustment::FieldAdjustment:
4431 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4433 Type = Adjustments[I].Field->getType();
4436 case SubobjectAdjustment::MemberPointerAdjustment:
4437 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4438 Adjustments[I].Ptr.RHS))
4440 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4449 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4450 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4451 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4452 // only see this when folding in C, so there's no standard to follow here.
4456 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
4457 if (!E->isPotentiallyEvaluated())
4460 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4461 << E->getExprOperand()->getType()
4462 << E->getExprOperand()->getSourceRange();
4466 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4470 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
4471 // Handle static data members.
4472 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4473 VisitIgnoredValue(E->getBase());
4474 return VisitVarDecl(E, VD);
4477 // Handle static member functions.
4478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4479 if (MD->isStatic()) {
4480 VisitIgnoredValue(E->getBase());
4485 // Handle non-static data members.
4486 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
4489 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
4490 // FIXME: Deal with vectors as array subscript bases.
4491 if (E->getBase()->getType()->isVectorType())
4494 if (!EvaluatePointer(E->getBase(), Result, Info))
4498 if (!EvaluateInteger(E->getIdx(), Index, Info))
4501 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4502 getExtValue(Index));
4505 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
4506 return EvaluatePointer(E->getSubExpr(), Result, Info);
4509 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4510 if (!Visit(E->getSubExpr()))
4512 // __real is a no-op on scalar lvalues.
4513 if (E->getSubExpr()->getType()->isAnyComplexType())
4514 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4518 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4519 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4520 "lvalue __imag__ on scalar?");
4521 if (!Visit(E->getSubExpr()))
4523 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4527 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
4528 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4531 if (!this->Visit(UO->getSubExpr()))
4534 return handleIncDec(
4535 this->Info, UO, Result, UO->getSubExpr()->getType(),
4536 UO->isIncrementOp(), 0);
4539 bool LValueExprEvaluator::VisitCompoundAssignOperator(
4540 const CompoundAssignOperator *CAO) {
4541 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4546 // The overall lvalue result is the result of evaluating the LHS.
4547 if (!this->Visit(CAO->getLHS())) {
4548 if (Info.keepEvaluatingAfterFailure())
4549 Evaluate(RHS, this->Info, CAO->getRHS());
4553 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4556 return handleCompoundAssignment(
4558 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4559 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
4562 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
4563 if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
4568 if (!this->Visit(E->getLHS())) {
4569 if (Info.keepEvaluatingAfterFailure())
4570 Evaluate(NewVal, this->Info, E->getRHS());
4574 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4577 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
4581 //===----------------------------------------------------------------------===//
4582 // Pointer Evaluation
4583 //===----------------------------------------------------------------------===//
4586 class PointerExprEvaluator
4587 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
4590 bool Success(const Expr *E) {
4596 PointerExprEvaluator(EvalInfo &info, LValue &Result)
4597 : ExprEvaluatorBaseTy(info), Result(Result) {}
4599 bool Success(const APValue &V, const Expr *E) {
4600 Result.setFrom(Info.Ctx, V);
4603 bool ZeroInitialization(const Expr *E) {
4604 return Success((Expr*)0);
4607 bool VisitBinaryOperator(const BinaryOperator *E);
4608 bool VisitCastExpr(const CastExpr* E);
4609 bool VisitUnaryAddrOf(const UnaryOperator *E);
4610 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
4611 { return Success(E); }
4612 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
4613 { return Success(E); }
4614 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
4615 { return Success(E); }
4616 bool VisitCallExpr(const CallExpr *E);
4617 bool VisitBlockExpr(const BlockExpr *E) {
4618 if (!E->getBlockDecl()->hasCaptures())
4622 bool VisitCXXThisExpr(const CXXThisExpr *E) {
4623 // Can't look at 'this' when checking a potential constant expression.
4624 if (Info.checkingPotentialConstantExpression())
4626 if (!Info.CurrentCall->This)
4628 Result = *Info.CurrentCall->This;
4632 // FIXME: Missing: @protocol, @selector
4634 } // end anonymous namespace
4636 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
4637 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
4638 return PointerExprEvaluator(Info, Result).Visit(E);
4641 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4642 if (E->getOpcode() != BO_Add &&
4643 E->getOpcode() != BO_Sub)
4644 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4646 const Expr *PExp = E->getLHS();
4647 const Expr *IExp = E->getRHS();
4648 if (IExp->getType()->isPointerType())
4649 std::swap(PExp, IExp);
4651 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4652 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
4655 llvm::APSInt Offset;
4656 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
4659 int64_t AdditionalOffset = getExtValue(Offset);
4660 if (E->getOpcode() == BO_Sub)
4661 AdditionalOffset = -AdditionalOffset;
4663 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
4664 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4668 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4669 return EvaluateLValue(E->getSubExpr(), Result, Info);
4672 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4673 const Expr* SubExpr = E->getSubExpr();
4675 switch (E->getCastKind()) {
4680 case CK_CPointerToObjCPointerCast:
4681 case CK_BlockPointerToObjCPointerCast:
4682 case CK_AnyPointerToBlockPointerCast:
4683 if (!Visit(SubExpr))
4685 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4686 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4687 // also static_casts, but we disallow them as a resolution to DR1312.
4688 if (!E->getType()->isVoidPointerType()) {
4689 Result.Designator.setInvalid();
4690 if (SubExpr->getType()->isVoidPointerType())
4691 CCEDiag(E, diag::note_constexpr_invalid_cast)
4692 << 3 << SubExpr->getType();
4694 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4698 case CK_DerivedToBase:
4699 case CK_UncheckedDerivedToBase:
4700 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
4702 if (!Result.Base && Result.Offset.isZero())
4705 // Now figure out the necessary offset to add to the base LV to get from
4706 // the derived class to the base class.
4707 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4708 castAs<PointerType>()->getPointeeType(),
4711 case CK_BaseToDerived:
4712 if (!Visit(E->getSubExpr()))
4714 if (!Result.Base && Result.Offset.isZero())
4716 return HandleBaseToDerivedCast(Info, E, Result);
4718 case CK_NullToPointer:
4719 VisitIgnoredValue(E->getSubExpr());
4720 return ZeroInitialization(E);
4722 case CK_IntegralToPointer: {
4723 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4726 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
4729 if (Value.isInt()) {
4730 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4731 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
4732 Result.Base = (Expr*)0;
4733 Result.Offset = CharUnits::fromQuantity(N);
4734 Result.CallIndex = 0;
4735 Result.Designator.setInvalid();
4738 // Cast is of an lvalue, no need to change value.
4739 Result.setFrom(Info.Ctx, Value);
4743 case CK_ArrayToPointerDecay:
4744 if (SubExpr->isGLValue()) {
4745 if (!EvaluateLValue(SubExpr, Result, Info))
4748 Result.set(SubExpr, Info.CurrentCall->Index);
4749 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
4750 Info, Result, SubExpr))
4753 // The result is a pointer to the first element of the array.
4754 if (const ConstantArrayType *CAT
4755 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4756 Result.addArray(Info, E, CAT);
4758 Result.Designator.setInvalid();
4761 case CK_FunctionToPointerDecay:
4762 return EvaluateLValue(SubExpr, Result, Info);
4765 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4768 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
4769 if (IsStringLiteralCall(E))
4772 switch (E->isBuiltinCall()) {
4773 case Builtin::BI__builtin_addressof:
4774 return EvaluateLValue(E->getArg(0), Result, Info);
4777 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4781 //===----------------------------------------------------------------------===//
4782 // Member Pointer Evaluation
4783 //===----------------------------------------------------------------------===//
4786 class MemberPointerExprEvaluator
4787 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
4790 bool Success(const ValueDecl *D) {
4791 Result = MemberPtr(D);
4796 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4797 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4799 bool Success(const APValue &V, const Expr *E) {
4803 bool ZeroInitialization(const Expr *E) {
4804 return Success((const ValueDecl*)0);
4807 bool VisitCastExpr(const CastExpr *E);
4808 bool VisitUnaryAddrOf(const UnaryOperator *E);
4810 } // end anonymous namespace
4812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4814 assert(E->isRValue() && E->getType()->isMemberPointerType());
4815 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4818 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4819 switch (E->getCastKind()) {
4821 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4823 case CK_NullToMemberPointer:
4824 VisitIgnoredValue(E->getSubExpr());
4825 return ZeroInitialization(E);
4827 case CK_BaseToDerivedMemberPointer: {
4828 if (!Visit(E->getSubExpr()))
4830 if (E->path_empty())
4832 // Base-to-derived member pointer casts store the path in derived-to-base
4833 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4834 // the wrong end of the derived->base arc, so stagger the path by one class.
4835 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4836 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4837 PathI != PathE; ++PathI) {
4838 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4839 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4840 if (!Result.castToDerived(Derived))
4843 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4844 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
4849 case CK_DerivedToBaseMemberPointer:
4850 if (!Visit(E->getSubExpr()))
4852 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4853 PathE = E->path_end(); PathI != PathE; ++PathI) {
4854 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4855 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4856 if (!Result.castToBase(Base))
4863 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4864 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4865 // member can be formed.
4866 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4869 //===----------------------------------------------------------------------===//
4870 // Record Evaluation
4871 //===----------------------------------------------------------------------===//
4874 class RecordExprEvaluator
4875 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
4880 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
4881 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
4883 bool Success(const APValue &V, const Expr *E) {
4887 bool ZeroInitialization(const Expr *E);
4889 bool VisitCastExpr(const CastExpr *E);
4890 bool VisitInitListExpr(const InitListExpr *E);
4891 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
4892 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
4896 /// Perform zero-initialization on an object of non-union class type.
4897 /// C++11 [dcl.init]p5:
4898 /// To zero-initialize an object or reference of type T means:
4900 /// -- if T is a (possibly cv-qualified) non-union class type,
4901 /// each non-static data member and each base-class subobject is
4902 /// zero-initialized
4903 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
4904 const RecordDecl *RD,
4905 const LValue &This, APValue &Result) {
4906 assert(!RD->isUnion() && "Expected non-union class type");
4907 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
4908 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
4909 std::distance(RD->field_begin(), RD->field_end()));
4911 if (RD->isInvalidDecl()) return false;
4912 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4916 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
4917 End = CD->bases_end(); I != End; ++I, ++Index) {
4918 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
4919 LValue Subobject = This;
4920 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
4922 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
4923 Result.getStructBase(Index)))
4928 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
4930 // -- if T is a reference type, no initialization is performed.
4931 if (I->getType()->isReferenceType())
4934 LValue Subobject = This;
4935 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
4938 ImplicitValueInitExpr VIE(I->getType());
4939 if (!EvaluateInPlace(
4940 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
4947 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
4948 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
4949 if (RD->isInvalidDecl()) return false;
4950 if (RD->isUnion()) {
4951 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4952 // object's first non-static named data member is zero-initialized
4953 RecordDecl::field_iterator I = RD->field_begin();
4954 if (I == RD->field_end()) {
4955 Result = APValue((const FieldDecl*)0);
4959 LValue Subobject = This;
4960 if (!HandleLValueMember(Info, E, Subobject, *I))
4962 Result = APValue(*I);
4963 ImplicitValueInitExpr VIE(I->getType());
4964 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
4967 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
4968 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
4972 return HandleClassZeroInitialization(Info, E, RD, This, Result);
4975 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
4976 switch (E->getCastKind()) {
4978 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4980 case CK_ConstructorConversion:
4981 return Visit(E->getSubExpr());
4983 case CK_DerivedToBase:
4984 case CK_UncheckedDerivedToBase: {
4985 APValue DerivedObject;
4986 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
4988 if (!DerivedObject.isStruct())
4989 return Error(E->getSubExpr());
4991 // Derived-to-base rvalue conversion: just slice off the derived part.
4992 APValue *Value = &DerivedObject;
4993 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
4994 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4995 PathE = E->path_end(); PathI != PathE; ++PathI) {
4996 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
4997 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4998 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5007 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5008 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
5009 if (RD->isInvalidDecl()) return false;
5010 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5012 if (RD->isUnion()) {
5013 const FieldDecl *Field = E->getInitializedFieldInUnion();
5014 Result = APValue(Field);
5018 // If the initializer list for a union does not contain any elements, the
5019 // first element of the union is value-initialized.
5020 // FIXME: The element should be initialized from an initializer list.
5021 // Is this difference ever observable for initializer lists which
5023 ImplicitValueInitExpr VIE(Field->getType());
5024 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5026 LValue Subobject = This;
5027 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5030 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5031 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5032 isa<CXXDefaultInitExpr>(InitExpr));
5034 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
5037 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5038 "initializer list for class with base classes");
5039 Result = APValue(APValue::UninitStruct(), 0,
5040 std::distance(RD->field_begin(), RD->field_end()));
5041 unsigned ElementNo = 0;
5042 bool Success = true;
5043 for (RecordDecl::field_iterator Field = RD->field_begin(),
5044 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
5045 // Anonymous bit-fields are not considered members of the class for
5046 // purposes of aggregate initialization.
5047 if (Field->isUnnamedBitfield())
5050 LValue Subobject = This;
5052 bool HaveInit = ElementNo < E->getNumInits();
5054 // FIXME: Diagnostics here should point to the end of the initializer
5055 // list, not the start.
5056 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
5057 Subobject, *Field, &Layout))
5060 // Perform an implicit value-initialization for members beyond the end of
5061 // the initializer list.
5062 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
5063 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
5065 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5066 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5067 isa<CXXDefaultInitExpr>(Init));
5069 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5070 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5071 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
5072 FieldVal, *Field))) {
5073 if (!Info.keepEvaluatingAfterFailure())
5082 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5083 const CXXConstructorDecl *FD = E->getConstructor();
5084 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5086 bool ZeroInit = E->requiresZeroInitialization();
5087 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5088 // If we've already performed zero-initialization, we're already done.
5089 if (!Result.isUninit())
5092 // We can get here in two different ways:
5093 // 1) We're performing value-initialization, and should zero-initialize
5095 // 2) We're performing default-initialization of an object with a trivial
5096 // constexpr default constructor, in which case we should start the
5097 // lifetimes of all the base subobjects (there can be no data member
5098 // subobjects in this case) per [basic.life]p1.
5099 // Either way, ZeroInitialization is appropriate.
5100 return ZeroInitialization(E);
5103 const FunctionDecl *Definition = 0;
5104 FD->getBody(Definition);
5106 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5109 // Avoid materializing a temporary for an elidable copy/move constructor.
5110 if (E->isElidable() && !ZeroInit)
5111 if (const MaterializeTemporaryExpr *ME
5112 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5113 return Visit(ME->GetTemporaryExpr());
5115 if (ZeroInit && !ZeroInitialization(E))
5118 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5119 return HandleConstructorCall(E->getExprLoc(), This, Args,
5120 cast<CXXConstructorDecl>(Definition), Info,
5124 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5125 const CXXStdInitializerListExpr *E) {
5126 const ConstantArrayType *ArrayType =
5127 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5130 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5133 // Get a pointer to the first element of the array.
5134 Array.addArray(Info, E, ArrayType);
5136 // FIXME: Perform the checks on the field types in SemaInit.
5137 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5138 RecordDecl::field_iterator Field = Record->field_begin();
5139 if (Field == Record->field_end())
5143 if (!Field->getType()->isPointerType() ||
5144 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5145 ArrayType->getElementType()))
5148 // FIXME: What if the initializer_list type has base classes, etc?
5149 Result = APValue(APValue::UninitStruct(), 0, 2);
5150 Array.moveInto(Result.getStructField(0));
5152 if (++Field == Record->field_end())
5155 if (Field->getType()->isPointerType() &&
5156 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5157 ArrayType->getElementType())) {
5159 if (!HandleLValueArrayAdjustment(Info, E, Array,
5160 ArrayType->getElementType(),
5161 ArrayType->getSize().getZExtValue()))
5163 Array.moveInto(Result.getStructField(1));
5164 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5166 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5170 if (++Field != Record->field_end())
5176 static bool EvaluateRecord(const Expr *E, const LValue &This,
5177 APValue &Result, EvalInfo &Info) {
5178 assert(E->isRValue() && E->getType()->isRecordType() &&
5179 "can't evaluate expression as a record rvalue");
5180 return RecordExprEvaluator(Info, This, Result).Visit(E);
5183 //===----------------------------------------------------------------------===//
5184 // Temporary Evaluation
5186 // Temporaries are represented in the AST as rvalues, but generally behave like
5187 // lvalues. The full-object of which the temporary is a subobject is implicitly
5188 // materialized so that a reference can bind to it.
5189 //===----------------------------------------------------------------------===//
5191 class TemporaryExprEvaluator
5192 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5194 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5195 LValueExprEvaluatorBaseTy(Info, Result) {}
5197 /// Visit an expression which constructs the value of this temporary.
5198 bool VisitConstructExpr(const Expr *E) {
5199 Result.set(E, Info.CurrentCall->Index);
5200 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5204 bool VisitCastExpr(const CastExpr *E) {
5205 switch (E->getCastKind()) {
5207 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5209 case CK_ConstructorConversion:
5210 return VisitConstructExpr(E->getSubExpr());
5213 bool VisitInitListExpr(const InitListExpr *E) {
5214 return VisitConstructExpr(E);
5216 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5217 return VisitConstructExpr(E);
5219 bool VisitCallExpr(const CallExpr *E) {
5220 return VisitConstructExpr(E);
5223 } // end anonymous namespace
5225 /// Evaluate an expression of record type as a temporary.
5226 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
5227 assert(E->isRValue() && E->getType()->isRecordType());
5228 return TemporaryExprEvaluator(Info, Result).Visit(E);
5231 //===----------------------------------------------------------------------===//
5232 // Vector Evaluation
5233 //===----------------------------------------------------------------------===//
5236 class VectorExprEvaluator
5237 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
5241 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5242 : ExprEvaluatorBaseTy(info), Result(Result) {}
5244 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5245 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5246 // FIXME: remove this APValue copy.
5247 Result = APValue(V.data(), V.size());
5250 bool Success(const APValue &V, const Expr *E) {
5251 assert(V.isVector());
5255 bool ZeroInitialization(const Expr *E);
5257 bool VisitUnaryReal(const UnaryOperator *E)
5258 { return Visit(E->getSubExpr()); }
5259 bool VisitCastExpr(const CastExpr* E);
5260 bool VisitInitListExpr(const InitListExpr *E);
5261 bool VisitUnaryImag(const UnaryOperator *E);
5262 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
5263 // binary comparisons, binary and/or/xor,
5264 // shufflevector, ExtVectorElementExpr
5266 } // end anonymous namespace
5268 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
5269 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
5270 return VectorExprEvaluator(Info, Result).Visit(E);
5273 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5274 const VectorType *VTy = E->getType()->castAs<VectorType>();
5275 unsigned NElts = VTy->getNumElements();
5277 const Expr *SE = E->getSubExpr();
5278 QualType SETy = SE->getType();
5280 switch (E->getCastKind()) {
5281 case CK_VectorSplat: {
5282 APValue Val = APValue();
5283 if (SETy->isIntegerType()) {
5285 if (!EvaluateInteger(SE, IntResult, Info))
5287 Val = APValue(IntResult);
5288 } else if (SETy->isRealFloatingType()) {
5290 if (!EvaluateFloat(SE, F, Info))
5297 // Splat and create vector APValue.
5298 SmallVector<APValue, 4> Elts(NElts, Val);
5299 return Success(Elts, E);
5302 // Evaluate the operand into an APInt we can extract from.
5303 llvm::APInt SValInt;
5304 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5306 // Extract the elements
5307 QualType EltTy = VTy->getElementType();
5308 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5309 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5310 SmallVector<APValue, 4> Elts;
5311 if (EltTy->isRealFloatingType()) {
5312 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
5313 unsigned FloatEltSize = EltSize;
5314 if (&Sem == &APFloat::x87DoubleExtended)
5316 for (unsigned i = 0; i < NElts; i++) {
5319 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5321 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
5322 Elts.push_back(APValue(APFloat(Sem, Elt)));
5324 } else if (EltTy->isIntegerType()) {
5325 for (unsigned i = 0; i < NElts; i++) {
5328 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5330 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5331 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5336 return Success(Elts, E);
5339 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5344 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5345 const VectorType *VT = E->getType()->castAs<VectorType>();
5346 unsigned NumInits = E->getNumInits();
5347 unsigned NumElements = VT->getNumElements();
5349 QualType EltTy = VT->getElementType();
5350 SmallVector<APValue, 4> Elements;
5352 // The number of initializers can be less than the number of
5353 // vector elements. For OpenCL, this can be due to nested vector
5354 // initialization. For GCC compatibility, missing trailing elements
5355 // should be initialized with zeroes.
5356 unsigned CountInits = 0, CountElts = 0;
5357 while (CountElts < NumElements) {
5358 // Handle nested vector initialization.
5359 if (CountInits < NumInits
5360 && E->getInit(CountInits)->getType()->isVectorType()) {
5362 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5364 unsigned vlen = v.getVectorLength();
5365 for (unsigned j = 0; j < vlen; j++)
5366 Elements.push_back(v.getVectorElt(j));
5368 } else if (EltTy->isIntegerType()) {
5369 llvm::APSInt sInt(32);
5370 if (CountInits < NumInits) {
5371 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
5373 } else // trailing integer zero.
5374 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5375 Elements.push_back(APValue(sInt));
5378 llvm::APFloat f(0.0);
5379 if (CountInits < NumInits) {
5380 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
5382 } else // trailing float zero.
5383 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5384 Elements.push_back(APValue(f));
5389 return Success(Elements, E);
5393 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
5394 const VectorType *VT = E->getType()->getAs<VectorType>();
5395 QualType EltTy = VT->getElementType();
5396 APValue ZeroElement;
5397 if (EltTy->isIntegerType())
5398 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5401 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5403 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
5404 return Success(Elements, E);
5407 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5408 VisitIgnoredValue(E->getSubExpr());
5409 return ZeroInitialization(E);
5412 //===----------------------------------------------------------------------===//
5414 //===----------------------------------------------------------------------===//
5417 class ArrayExprEvaluator
5418 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
5423 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5424 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
5426 bool Success(const APValue &V, const Expr *E) {
5427 assert((V.isArray() || V.isLValue()) &&
5428 "expected array or string literal");
5433 bool ZeroInitialization(const Expr *E) {
5434 const ConstantArrayType *CAT =
5435 Info.Ctx.getAsConstantArrayType(E->getType());
5439 Result = APValue(APValue::UninitArray(), 0,
5440 CAT->getSize().getZExtValue());
5441 if (!Result.hasArrayFiller()) return true;
5443 // Zero-initialize all elements.
5444 LValue Subobject = This;
5445 Subobject.addArray(Info, E, CAT);
5446 ImplicitValueInitExpr VIE(CAT->getElementType());
5447 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
5450 bool VisitInitListExpr(const InitListExpr *E);
5451 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
5452 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5453 const LValue &Subobject,
5454 APValue *Value, QualType Type);
5456 } // end anonymous namespace
5458 static bool EvaluateArray(const Expr *E, const LValue &This,
5459 APValue &Result, EvalInfo &Info) {
5460 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
5461 return ArrayExprEvaluator(Info, This, Result).Visit(E);
5464 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5465 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5469 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5470 // an appropriately-typed string literal enclosed in braces.
5471 if (E->isStringLiteralInit()) {
5473 if (!EvaluateLValue(E->getInit(0), LV, Info))
5477 return Success(Val, E);
5480 bool Success = true;
5482 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5483 "zero-initialized array shouldn't have any initialized elts");
5485 if (Result.isArray() && Result.hasArrayFiller())
5486 Filler = Result.getArrayFiller();
5488 unsigned NumEltsToInit = E->getNumInits();
5489 unsigned NumElts = CAT->getSize().getZExtValue();
5490 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
5492 // If the initializer might depend on the array index, run it for each
5493 // array element. For now, just whitelist non-class value-initialization.
5494 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5495 NumEltsToInit = NumElts;
5497 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
5499 // If the array was previously zero-initialized, preserve the
5500 // zero-initialized values.
5501 if (!Filler.isUninit()) {
5502 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5503 Result.getArrayInitializedElt(I) = Filler;
5504 if (Result.hasArrayFiller())
5505 Result.getArrayFiller() = Filler;
5508 LValue Subobject = This;
5509 Subobject.addArray(Info, E, CAT);
5510 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5512 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
5513 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
5514 Info, Subobject, Init) ||
5515 !HandleLValueArrayAdjustment(Info, Init, Subobject,
5516 CAT->getElementType(), 1)) {
5517 if (!Info.keepEvaluatingAfterFailure())
5523 if (!Result.hasArrayFiller())
5526 // If we get here, we have a trivial filler, which we can just evaluate
5527 // once and splat over the rest of the array elements.
5528 assert(FillerExpr && "no array filler for incomplete init list");
5529 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5530 FillerExpr) && Success;
5533 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5534 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5537 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5538 const LValue &Subobject,
5541 bool HadZeroInit = !Value->isUninit();
5543 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5544 unsigned N = CAT->getSize().getZExtValue();
5546 // Preserve the array filler if we had prior zero-initialization.
5548 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5551 *Value = APValue(APValue::UninitArray(), N, N);
5554 for (unsigned I = 0; I != N; ++I)
5555 Value->getArrayInitializedElt(I) = Filler;
5557 // Initialize the elements.
5558 LValue ArrayElt = Subobject;
5559 ArrayElt.addArray(Info, E, CAT);
5560 for (unsigned I = 0; I != N; ++I)
5561 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5562 CAT->getElementType()) ||
5563 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5564 CAT->getElementType(), 1))
5570 if (!Type->isRecordType())
5573 const CXXConstructorDecl *FD = E->getConstructor();
5575 bool ZeroInit = E->requiresZeroInitialization();
5576 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
5580 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5581 ImplicitValueInitExpr VIE(Type);
5582 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
5585 const FunctionDecl *Definition = 0;
5586 FD->getBody(Definition);
5588 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5591 if (ZeroInit && !HadZeroInit) {
5592 ImplicitValueInitExpr VIE(Type);
5593 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
5597 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
5598 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
5599 cast<CXXConstructorDecl>(Definition),
5603 //===----------------------------------------------------------------------===//
5604 // Integer Evaluation
5606 // As a GNU extension, we support casting pointers to sufficiently-wide integer
5607 // types and back in constant folding. Integer values are thus represented
5608 // either as an integer-valued APValue, or as an lvalue-valued APValue.
5609 //===----------------------------------------------------------------------===//
5612 class IntExprEvaluator
5613 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
5616 IntExprEvaluator(EvalInfo &info, APValue &result)
5617 : ExprEvaluatorBaseTy(info), Result(result) {}
5619 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
5620 assert(E->getType()->isIntegralOrEnumerationType() &&
5621 "Invalid evaluation result.");
5622 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
5623 "Invalid evaluation result.");
5624 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5625 "Invalid evaluation result.");
5626 Result = APValue(SI);
5629 bool Success(const llvm::APSInt &SI, const Expr *E) {
5630 return Success(SI, E, Result);
5633 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
5634 assert(E->getType()->isIntegralOrEnumerationType() &&
5635 "Invalid evaluation result.");
5636 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
5637 "Invalid evaluation result.");
5638 Result = APValue(APSInt(I));
5639 Result.getInt().setIsUnsigned(
5640 E->getType()->isUnsignedIntegerOrEnumerationType());
5643 bool Success(const llvm::APInt &I, const Expr *E) {
5644 return Success(I, E, Result);
5647 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
5648 assert(E->getType()->isIntegralOrEnumerationType() &&
5649 "Invalid evaluation result.");
5650 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
5653 bool Success(uint64_t Value, const Expr *E) {
5654 return Success(Value, E, Result);
5657 bool Success(CharUnits Size, const Expr *E) {
5658 return Success(Size.getQuantity(), E);
5661 bool Success(const APValue &V, const Expr *E) {
5662 if (V.isLValue() || V.isAddrLabelDiff()) {
5666 return Success(V.getInt(), E);
5669 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
5671 //===--------------------------------------------------------------------===//
5673 //===--------------------------------------------------------------------===//
5675 bool VisitIntegerLiteral(const IntegerLiteral *E) {
5676 return Success(E->getValue(), E);
5678 bool VisitCharacterLiteral(const CharacterLiteral *E) {
5679 return Success(E->getValue(), E);
5682 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5683 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5684 if (CheckReferencedDecl(E, E->getDecl()))
5687 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
5689 bool VisitMemberExpr(const MemberExpr *E) {
5690 if (CheckReferencedDecl(E, E->getMemberDecl())) {
5691 VisitIgnoredValue(E->getBase());
5695 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
5698 bool VisitCallExpr(const CallExpr *E);
5699 bool VisitBinaryOperator(const BinaryOperator *E);
5700 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
5701 bool VisitUnaryOperator(const UnaryOperator *E);
5703 bool VisitCastExpr(const CastExpr* E);
5704 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
5706 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
5707 return Success(E->getValue(), E);
5710 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5711 return Success(E->getValue(), E);
5714 // Note, GNU defines __null as an integer, not a pointer.
5715 bool VisitGNUNullExpr(const GNUNullExpr *E) {
5716 return ZeroInitialization(E);
5719 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
5720 return Success(E->getValue(), E);
5723 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
5724 return Success(E->getValue(), E);
5727 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5728 return Success(E->getValue(), E);
5731 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5732 return Success(E->getValue(), E);
5735 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5736 return Success(E->getValue(), E);
5739 bool VisitUnaryReal(const UnaryOperator *E);
5740 bool VisitUnaryImag(const UnaryOperator *E);
5742 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
5743 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
5746 CharUnits GetAlignOfExpr(const Expr *E);
5747 CharUnits GetAlignOfType(QualType T);
5748 static QualType GetObjectType(APValue::LValueBase B);
5749 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
5750 // FIXME: Missing: array subscript of vector, member of vector
5752 } // end anonymous namespace
5754 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5755 /// produce either the integer value or a pointer.
5757 /// GCC has a heinous extension which folds casts between pointer types and
5758 /// pointer-sized integral types. We support this by allowing the evaluation of
5759 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5760 /// Some simple arithmetic on such values is supported (they are treated much
5762 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
5764 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
5765 return IntExprEvaluator(Info, Result).Visit(E);
5768 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
5770 if (!EvaluateIntegerOrLValue(E, Val, Info))
5773 // FIXME: It would be better to produce the diagnostic for casting
5774 // a pointer to an integer.
5775 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
5778 Result = Val.getInt();
5782 /// Check whether the given declaration can be directly converted to an integral
5783 /// rvalue. If not, no diagnostic is produced; there are other things we can
5785 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
5786 // Enums are integer constant exprs.
5787 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
5788 // Check for signedness/width mismatches between E type and ECD value.
5789 bool SameSign = (ECD->getInitVal().isSigned()
5790 == E->getType()->isSignedIntegerOrEnumerationType());
5791 bool SameWidth = (ECD->getInitVal().getBitWidth()
5792 == Info.Ctx.getIntWidth(E->getType()));
5793 if (SameSign && SameWidth)
5794 return Success(ECD->getInitVal(), E);
5796 // Get rid of mismatch (otherwise Success assertions will fail)
5797 // by computing a new value matching the type of E.
5798 llvm::APSInt Val = ECD->getInitVal();
5800 Val.setIsSigned(!ECD->getInitVal().isSigned());
5802 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5803 return Success(Val, E);
5809 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5811 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5812 // The following enum mimics the values returned by GCC.
5813 // FIXME: Does GCC differ between lvalue and rvalue references here?
5814 enum gcc_type_class {
5816 void_type_class, integer_type_class, char_type_class,
5817 enumeral_type_class, boolean_type_class,
5818 pointer_type_class, reference_type_class, offset_type_class,
5819 real_type_class, complex_type_class,
5820 function_type_class, method_type_class,
5821 record_type_class, union_type_class,
5822 array_type_class, string_type_class,
5826 // If no argument was supplied, default to "no_type_class". This isn't
5827 // ideal, however it is what gcc does.
5828 if (E->getNumArgs() == 0)
5829 return no_type_class;
5831 QualType ArgTy = E->getArg(0)->getType();
5832 if (ArgTy->isVoidType())
5833 return void_type_class;
5834 else if (ArgTy->isEnumeralType())
5835 return enumeral_type_class;
5836 else if (ArgTy->isBooleanType())
5837 return boolean_type_class;
5838 else if (ArgTy->isCharType())
5839 return string_type_class; // gcc doesn't appear to use char_type_class
5840 else if (ArgTy->isIntegerType())
5841 return integer_type_class;
5842 else if (ArgTy->isPointerType())
5843 return pointer_type_class;
5844 else if (ArgTy->isReferenceType())
5845 return reference_type_class;
5846 else if (ArgTy->isRealType())
5847 return real_type_class;
5848 else if (ArgTy->isComplexType())
5849 return complex_type_class;
5850 else if (ArgTy->isFunctionType())
5851 return function_type_class;
5852 else if (ArgTy->isStructureOrClassType())
5853 return record_type_class;
5854 else if (ArgTy->isUnionType())
5855 return union_type_class;
5856 else if (ArgTy->isArrayType())
5857 return array_type_class;
5858 else if (ArgTy->isUnionType())
5859 return union_type_class;
5860 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
5861 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
5864 /// EvaluateBuiltinConstantPForLValue - Determine the result of
5865 /// __builtin_constant_p when applied to the given lvalue.
5867 /// An lvalue is only "constant" if it is a pointer or reference to the first
5868 /// character of a string literal.
5869 template<typename LValue>
5870 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
5871 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
5872 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5875 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5876 /// GCC as we can manage.
5877 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5878 QualType ArgType = Arg->getType();
5880 // __builtin_constant_p always has one operand. The rules which gcc follows
5881 // are not precisely documented, but are as follows:
5883 // - If the operand is of integral, floating, complex or enumeration type,
5884 // and can be folded to a known value of that type, it returns 1.
5885 // - If the operand and can be folded to a pointer to the first character
5886 // of a string literal (or such a pointer cast to an integral type), it
5889 // Otherwise, it returns 0.
5891 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
5892 // its support for this does not currently work.
5893 if (ArgType->isIntegralOrEnumerationType()) {
5894 Expr::EvalResult Result;
5895 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
5898 APValue &V = Result.Val;
5899 if (V.getKind() == APValue::Int)
5902 return EvaluateBuiltinConstantPForLValue(V);
5903 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
5904 return Arg->isEvaluatable(Ctx);
5905 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
5907 Expr::EvalStatus Status;
5908 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
5909 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
5910 : EvaluatePointer(Arg, LV, Info)) &&
5911 !Status.HasSideEffects)
5912 return EvaluateBuiltinConstantPForLValue(LV);
5915 // Anything else isn't considered to be sufficiently constant.
5919 /// Retrieves the "underlying object type" of the given expression,
5920 /// as used by __builtin_object_size.
5921 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
5922 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
5923 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
5924 return VD->getType();
5925 } else if (const Expr *E = B.get<const Expr*>()) {
5926 if (isa<CompoundLiteralExpr>(E))
5927 return E->getType();
5933 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
5937 // The operand of __builtin_object_size is never evaluated for side-effects.
5938 // If there are any, but we can determine the pointed-to object anyway, then
5939 // ignore the side-effects.
5940 SpeculativeEvaluationRAII SpeculativeEval(Info);
5941 if (!EvaluatePointer(E->getArg(0), Base, Info))
5945 // If we can prove the base is null, lower to zero now.
5946 if (!Base.getLValueBase()) return Success(0, E);
5948 QualType T = GetObjectType(Base.getLValueBase());
5950 T->isIncompleteType() ||
5951 T->isFunctionType() ||
5952 T->isVariablyModifiedType() ||
5953 T->isDependentType())
5956 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
5957 CharUnits Offset = Base.getLValueOffset();
5959 if (!Offset.isNegative() && Offset <= Size)
5962 Size = CharUnits::Zero();
5963 return Success(Size, E);
5966 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
5967 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
5969 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5971 case Builtin::BI__builtin_object_size: {
5972 if (TryEvaluateBuiltinObjectSize(E))
5975 // If evaluating the argument has side-effects, we can't determine the size
5976 // of the object, and so we lower it to unknown now. CodeGen relies on us to
5977 // handle all cases where the expression has side-effects.
5978 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
5979 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
5980 return Success(-1ULL, E);
5981 return Success(0, E);
5984 // Expression had no side effects, but we couldn't statically determine the
5985 // size of the referenced object.
5989 case Builtin::BI__builtin_bswap16:
5990 case Builtin::BI__builtin_bswap32:
5991 case Builtin::BI__builtin_bswap64: {
5993 if (!EvaluateInteger(E->getArg(0), Val, Info))
5996 return Success(Val.byteSwap(), E);
5999 case Builtin::BI__builtin_classify_type:
6000 return Success(EvaluateBuiltinClassifyType(E), E);
6002 // FIXME: BI__builtin_clrsb
6003 // FIXME: BI__builtin_clrsbl
6004 // FIXME: BI__builtin_clrsbll
6006 case Builtin::BI__builtin_clz:
6007 case Builtin::BI__builtin_clzl:
6008 case Builtin::BI__builtin_clzll: {
6010 if (!EvaluateInteger(E->getArg(0), Val, Info))
6015 return Success(Val.countLeadingZeros(), E);
6018 case Builtin::BI__builtin_constant_p:
6019 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6021 case Builtin::BI__builtin_ctz:
6022 case Builtin::BI__builtin_ctzl:
6023 case Builtin::BI__builtin_ctzll: {
6025 if (!EvaluateInteger(E->getArg(0), Val, Info))
6030 return Success(Val.countTrailingZeros(), E);
6033 case Builtin::BI__builtin_eh_return_data_regno: {
6034 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6035 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6036 return Success(Operand, E);
6039 case Builtin::BI__builtin_expect:
6040 return Visit(E->getArg(0));
6042 case Builtin::BI__builtin_ffs:
6043 case Builtin::BI__builtin_ffsl:
6044 case Builtin::BI__builtin_ffsll: {
6046 if (!EvaluateInteger(E->getArg(0), Val, Info))
6049 unsigned N = Val.countTrailingZeros();
6050 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6053 case Builtin::BI__builtin_fpclassify: {
6055 if (!EvaluateFloat(E->getArg(5), Val, Info))
6058 switch (Val.getCategory()) {
6059 case APFloat::fcNaN: Arg = 0; break;
6060 case APFloat::fcInfinity: Arg = 1; break;
6061 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6062 case APFloat::fcZero: Arg = 4; break;
6064 return Visit(E->getArg(Arg));
6067 case Builtin::BI__builtin_isinf_sign: {
6069 return EvaluateFloat(E->getArg(0), Val, Info) &&
6070 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6073 case Builtin::BI__builtin_isinf: {
6075 return EvaluateFloat(E->getArg(0), Val, Info) &&
6076 Success(Val.isInfinity() ? 1 : 0, E);
6079 case Builtin::BI__builtin_isfinite: {
6081 return EvaluateFloat(E->getArg(0), Val, Info) &&
6082 Success(Val.isFinite() ? 1 : 0, E);
6085 case Builtin::BI__builtin_isnan: {
6087 return EvaluateFloat(E->getArg(0), Val, Info) &&
6088 Success(Val.isNaN() ? 1 : 0, E);
6091 case Builtin::BI__builtin_isnormal: {
6093 return EvaluateFloat(E->getArg(0), Val, Info) &&
6094 Success(Val.isNormal() ? 1 : 0, E);
6097 case Builtin::BI__builtin_parity:
6098 case Builtin::BI__builtin_parityl:
6099 case Builtin::BI__builtin_parityll: {
6101 if (!EvaluateInteger(E->getArg(0), Val, Info))
6104 return Success(Val.countPopulation() % 2, E);
6107 case Builtin::BI__builtin_popcount:
6108 case Builtin::BI__builtin_popcountl:
6109 case Builtin::BI__builtin_popcountll: {
6111 if (!EvaluateInteger(E->getArg(0), Val, Info))
6114 return Success(Val.countPopulation(), E);
6117 case Builtin::BIstrlen:
6118 // A call to strlen is not a constant expression.
6119 if (Info.getLangOpts().CPlusPlus11)
6120 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6121 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6123 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6125 case Builtin::BI__builtin_strlen: {
6126 // As an extension, we support __builtin_strlen() as a constant expression,
6127 // and support folding strlen() to a constant.
6129 if (!EvaluatePointer(E->getArg(0), String, Info))
6132 // Fast path: if it's a string literal, search the string value.
6133 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6134 String.getLValueBase().dyn_cast<const Expr *>())) {
6135 // The string literal may have embedded null characters. Find the first
6136 // one and truncate there.
6137 StringRef Str = S->getBytes();
6138 int64_t Off = String.Offset.getQuantity();
6139 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6140 S->getCharByteWidth() == 1) {
6141 Str = Str.substr(Off);
6143 StringRef::size_type Pos = Str.find(0);
6144 if (Pos != StringRef::npos)
6145 Str = Str.substr(0, Pos);
6147 return Success(Str.size(), E);
6150 // Fall through to slow path to issue appropriate diagnostic.
6153 // Slow path: scan the bytes of the string looking for the terminating 0.
6154 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6155 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6157 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6161 return Success(Strlen, E);
6162 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6167 case Builtin::BI__atomic_always_lock_free:
6168 case Builtin::BI__atomic_is_lock_free:
6169 case Builtin::BI__c11_atomic_is_lock_free: {
6171 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6174 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6175 // of two less than the maximum inline atomic width, we know it is
6176 // lock-free. If the size isn't a power of two, or greater than the
6177 // maximum alignment where we promote atomics, we know it is not lock-free
6178 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6179 // the answer can only be determined at runtime; for example, 16-byte
6180 // atomics have lock-free implementations on some, but not all,
6181 // x86-64 processors.
6183 // Check power-of-two.
6184 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
6185 if (Size.isPowerOfTwo()) {
6186 // Check against inlining width.
6187 unsigned InlineWidthBits =
6188 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6189 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6190 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6191 Size == CharUnits::One() ||
6192 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6193 Expr::NPC_NeverValueDependent))
6194 // OK, we will inline appropriately-aligned operations of this size,
6195 // and _Atomic(T) is appropriately-aligned.
6196 return Success(1, E);
6198 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6199 castAs<PointerType>()->getPointeeType();
6200 if (!PointeeType->isIncompleteType() &&
6201 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6202 // OK, we will inline operations on this object.
6203 return Success(1, E);
6208 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6209 Success(0, E) : Error(E);
6214 static bool HasSameBase(const LValue &A, const LValue &B) {
6215 if (!A.getLValueBase())
6216 return !B.getLValueBase();
6217 if (!B.getLValueBase())
6220 if (A.getLValueBase().getOpaqueValue() !=
6221 B.getLValueBase().getOpaqueValue()) {
6222 const Decl *ADecl = GetLValueBaseDecl(A);
6225 const Decl *BDecl = GetLValueBaseDecl(B);
6226 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
6230 return IsGlobalLValue(A.getLValueBase()) ||
6231 A.getLValueCallIndex() == B.getLValueCallIndex();
6236 /// \brief Data recursive integer evaluator of certain binary operators.
6238 /// We use a data recursive algorithm for binary operators so that we are able
6239 /// to handle extreme cases of chained binary operators without causing stack
6241 class DataRecursiveIntBinOpEvaluator {
6246 EvalResult() : Failed(false) { }
6248 void swap(EvalResult &RHS) {
6250 Failed = RHS.Failed;
6257 EvalResult LHSResult; // meaningful only for binary operator expression.
6258 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
6260 Job() : StoredInfo(0) { }
6261 void startSpeculativeEval(EvalInfo &Info) {
6262 OldEvalStatus = Info.EvalStatus;
6263 Info.EvalStatus.Diag = 0;
6268 StoredInfo->EvalStatus = OldEvalStatus;
6272 EvalInfo *StoredInfo; // non-null if status changed.
6273 Expr::EvalStatus OldEvalStatus;
6276 SmallVector<Job, 16> Queue;
6278 IntExprEvaluator &IntEval;
6280 APValue &FinalResult;
6283 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6284 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6286 /// \brief True if \param E is a binary operator that we are going to handle
6287 /// data recursively.
6288 /// We handle binary operators that are comma, logical, or that have operands
6289 /// with integral or enumeration type.
6290 static bool shouldEnqueue(const BinaryOperator *E) {
6291 return E->getOpcode() == BO_Comma ||
6293 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6294 E->getRHS()->getType()->isIntegralOrEnumerationType());
6297 bool Traverse(const BinaryOperator *E) {
6299 EvalResult PrevResult;
6300 while (!Queue.empty())
6301 process(PrevResult);
6303 if (PrevResult.Failed) return false;
6305 FinalResult.swap(PrevResult.Val);
6310 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6311 return IntEval.Success(Value, E, Result);
6313 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6314 return IntEval.Success(Value, E, Result);
6316 bool Error(const Expr *E) {
6317 return IntEval.Error(E);
6319 bool Error(const Expr *E, diag::kind D) {
6320 return IntEval.Error(E, D);
6323 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6324 return Info.CCEDiag(E, D);
6327 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6328 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6329 bool &SuppressRHSDiags);
6331 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6332 const BinaryOperator *E, APValue &Result);
6334 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6335 Result.Failed = !Evaluate(Result.Val, Info, E);
6337 Result.Val = APValue();
6340 void process(EvalResult &Result);
6342 void enqueue(const Expr *E) {
6343 E = E->IgnoreParens();
6344 Queue.resize(Queue.size()+1);
6346 Queue.back().Kind = Job::AnyExprKind;
6352 bool DataRecursiveIntBinOpEvaluator::
6353 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
6354 bool &SuppressRHSDiags) {
6355 if (E->getOpcode() == BO_Comma) {
6356 // Ignore LHS but note if we could not evaluate it.
6357 if (LHSResult.Failed)
6358 return Info.noteSideEffect();
6362 if (E->isLogicalOp()) {
6364 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
6365 // We were able to evaluate the LHS, see if we can get away with not
6366 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
6367 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6368 Success(LHSAsBool, E, LHSResult.Val);
6369 return false; // Ignore RHS
6372 LHSResult.Failed = true;
6374 // Since we weren't able to evaluate the left hand side, it
6375 // must have had side effects.
6376 if (!Info.noteSideEffect())
6379 // We can't evaluate the LHS; however, sometimes the result
6380 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6381 // Don't ignore RHS and suppress diagnostics from this arm.
6382 SuppressRHSDiags = true;
6388 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6389 E->getRHS()->getType()->isIntegralOrEnumerationType());
6391 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
6392 return false; // Ignore RHS;
6397 bool DataRecursiveIntBinOpEvaluator::
6398 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6399 const BinaryOperator *E, APValue &Result) {
6400 if (E->getOpcode() == BO_Comma) {
6401 if (RHSResult.Failed)
6403 Result = RHSResult.Val;
6407 if (E->isLogicalOp()) {
6408 bool lhsResult, rhsResult;
6409 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6410 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6414 if (E->getOpcode() == BO_LOr)
6415 return Success(lhsResult || rhsResult, E, Result);
6417 return Success(lhsResult && rhsResult, E, Result);
6421 // We can't evaluate the LHS; however, sometimes the result
6422 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6423 if (rhsResult == (E->getOpcode() == BO_LOr))
6424 return Success(rhsResult, E, Result);
6431 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6432 E->getRHS()->getType()->isIntegralOrEnumerationType());
6434 if (LHSResult.Failed || RHSResult.Failed)
6437 const APValue &LHSVal = LHSResult.Val;
6438 const APValue &RHSVal = RHSResult.Val;
6440 // Handle cases like (unsigned long)&a + 4.
6441 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6443 CharUnits AdditionalOffset =
6444 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
6445 if (E->getOpcode() == BO_Add)
6446 Result.getLValueOffset() += AdditionalOffset;
6448 Result.getLValueOffset() -= AdditionalOffset;
6452 // Handle cases like 4 + (unsigned long)&a
6453 if (E->getOpcode() == BO_Add &&
6454 RHSVal.isLValue() && LHSVal.isInt()) {
6456 Result.getLValueOffset() +=
6457 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
6461 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6462 // Handle (intptr_t)&&A - (intptr_t)&&B.
6463 if (!LHSVal.getLValueOffset().isZero() ||
6464 !RHSVal.getLValueOffset().isZero())
6466 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6467 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6468 if (!LHSExpr || !RHSExpr)
6470 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6471 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6472 if (!LHSAddrExpr || !RHSAddrExpr)
6474 // Make sure both labels come from the same function.
6475 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6476 RHSAddrExpr->getLabel()->getDeclContext())
6478 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6482 // All the remaining cases expect both operands to be an integer
6483 if (!LHSVal.isInt() || !RHSVal.isInt())
6486 // Set up the width and signedness manually, in case it can't be deduced
6487 // from the operation we're performing.
6488 // FIXME: Don't do this in the cases where we can deduce it.
6489 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6490 E->getType()->isUnsignedIntegerOrEnumerationType());
6491 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6492 RHSVal.getInt(), Value))
6494 return Success(Value, E, Result);
6497 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
6498 Job &job = Queue.back();
6501 case Job::AnyExprKind: {
6502 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6503 if (shouldEnqueue(Bop)) {
6504 job.Kind = Job::BinOpKind;
6505 enqueue(Bop->getLHS());
6510 EvaluateExpr(job.E, Result);
6515 case Job::BinOpKind: {
6516 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6517 bool SuppressRHSDiags = false;
6518 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
6522 if (SuppressRHSDiags)
6523 job.startSpeculativeEval(Info);
6524 job.LHSResult.swap(Result);
6525 job.Kind = Job::BinOpVisitedLHSKind;
6526 enqueue(Bop->getRHS());
6530 case Job::BinOpVisitedLHSKind: {
6531 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6534 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
6540 llvm_unreachable("Invalid Job::Kind!");
6543 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6544 if (E->isAssignmentOp())
6547 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6548 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
6550 QualType LHSTy = E->getLHS()->getType();
6551 QualType RHSTy = E->getRHS()->getType();
6553 if (LHSTy->isAnyComplexType()) {
6554 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
6555 ComplexValue LHS, RHS;
6557 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6558 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6561 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
6564 if (LHS.isComplexFloat()) {
6565 APFloat::cmpResult CR_r =
6566 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
6567 APFloat::cmpResult CR_i =
6568 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6570 if (E->getOpcode() == BO_EQ)
6571 return Success((CR_r == APFloat::cmpEqual &&
6572 CR_i == APFloat::cmpEqual), E);
6574 assert(E->getOpcode() == BO_NE &&
6575 "Invalid complex comparison.");
6576 return Success(((CR_r == APFloat::cmpGreaterThan ||
6577 CR_r == APFloat::cmpLessThan ||
6578 CR_r == APFloat::cmpUnordered) ||
6579 (CR_i == APFloat::cmpGreaterThan ||
6580 CR_i == APFloat::cmpLessThan ||
6581 CR_i == APFloat::cmpUnordered)), E);
6584 if (E->getOpcode() == BO_EQ)
6585 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6586 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6588 assert(E->getOpcode() == BO_NE &&
6589 "Invalid compex comparison.");
6590 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6591 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6596 if (LHSTy->isRealFloatingType() &&
6597 RHSTy->isRealFloatingType()) {
6598 APFloat RHS(0.0), LHS(0.0);
6600 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6601 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
6604 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
6607 APFloat::cmpResult CR = LHS.compare(RHS);
6609 switch (E->getOpcode()) {
6611 llvm_unreachable("Invalid binary operator!");
6613 return Success(CR == APFloat::cmpLessThan, E);
6615 return Success(CR == APFloat::cmpGreaterThan, E);
6617 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
6619 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
6622 return Success(CR == APFloat::cmpEqual, E);
6624 return Success(CR == APFloat::cmpGreaterThan
6625 || CR == APFloat::cmpLessThan
6626 || CR == APFloat::cmpUnordered, E);
6630 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
6631 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
6632 LValue LHSValue, RHSValue;
6634 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6635 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6638 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6641 // Reject differing bases from the normal codepath; we special-case
6642 // comparisons to null.
6643 if (!HasSameBase(LHSValue, RHSValue)) {
6644 if (E->getOpcode() == BO_Sub) {
6645 // Handle &&A - &&B.
6646 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6648 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
6649 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
6650 if (!LHSExpr || !RHSExpr)
6652 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6653 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6654 if (!LHSAddrExpr || !RHSAddrExpr)
6656 // Make sure both labels come from the same function.
6657 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6658 RHSAddrExpr->getLabel()->getDeclContext())
6660 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6663 // Inequalities and subtractions between unrelated pointers have
6664 // unspecified or undefined behavior.
6665 if (!E->isEqualityOp())
6667 // A constant address may compare equal to the address of a symbol.
6668 // The one exception is that address of an object cannot compare equal
6669 // to a null pointer constant.
6670 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6671 (!RHSValue.Base && !RHSValue.Offset.isZero()))
6673 // It's implementation-defined whether distinct literals will have
6674 // distinct addresses. In clang, the result of such a comparison is
6675 // unspecified, so it is not a constant expression. However, we do know
6676 // that the address of a literal will be non-null.
6677 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6678 LHSValue.Base && RHSValue.Base)
6680 // We can't tell whether weak symbols will end up pointing to the same
6682 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
6684 // Pointers with different bases cannot represent the same object.
6685 // (Note that clang defaults to -fmerge-all-constants, which can
6686 // lead to inconsistent results for comparisons involving the address
6687 // of a constant; this generally doesn't matter in practice.)
6688 return Success(E->getOpcode() == BO_NE, E);
6691 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6692 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6694 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6695 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6697 if (E->getOpcode() == BO_Sub) {
6698 // C++11 [expr.add]p6:
6699 // Unless both pointers point to elements of the same array object, or
6700 // one past the last element of the array object, the behavior is
6702 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6703 !AreElementsOfSameArray(getType(LHSValue.Base),
6704 LHSDesignator, RHSDesignator))
6705 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6707 QualType Type = E->getLHS()->getType();
6708 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
6710 CharUnits ElementSize;
6711 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
6714 // As an extension, a type may have zero size (empty struct or union in
6715 // C, array of zero length). Pointer subtraction in such cases has
6716 // undefined behavior, so is not constant.
6717 if (ElementSize.isZero()) {
6718 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6723 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6724 // and produce incorrect results when it overflows. Such behavior
6725 // appears to be non-conforming, but is common, so perhaps we should
6726 // assume the standard intended for such cases to be undefined behavior
6727 // and check for them.
6729 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6730 // overflow in the final conversion to ptrdiff_t.
6732 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6734 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6736 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6737 APSInt TrueResult = (LHS - RHS) / ElemSize;
6738 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6740 if (Result.extend(65) != TrueResult)
6741 HandleOverflow(Info, E, TrueResult, E->getType());
6742 return Success(Result, E);
6745 // C++11 [expr.rel]p3:
6746 // Pointers to void (after pointer conversions) can be compared, with a
6747 // result defined as follows: If both pointers represent the same
6748 // address or are both the null pointer value, the result is true if the
6749 // operator is <= or >= and false otherwise; otherwise the result is
6751 // We interpret this as applying to pointers to *cv* void.
6752 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
6753 E->isRelationalOp())
6754 CCEDiag(E, diag::note_constexpr_void_comparison);
6756 // C++11 [expr.rel]p2:
6757 // - If two pointers point to non-static data members of the same object,
6758 // or to subobjects or array elements fo such members, recursively, the
6759 // pointer to the later declared member compares greater provided the
6760 // two members have the same access control and provided their class is
6763 // - Otherwise pointer comparisons are unspecified.
6764 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6765 E->isRelationalOp()) {
6768 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6769 RHSDesignator, WasArrayIndex);
6770 // At the point where the designators diverge, the comparison has a
6771 // specified value if:
6772 // - we are comparing array indices
6773 // - we are comparing fields of a union, or fields with the same access
6774 // Otherwise, the result is unspecified and thus the comparison is not a
6775 // constant expression.
6776 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6777 Mismatch < RHSDesignator.Entries.size()) {
6778 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6779 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6781 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6783 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6784 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6785 << RF->getParent() << RF;
6787 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6788 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6789 << LF->getParent() << LF;
6790 else if (!LF->getParent()->isUnion() &&
6791 LF->getAccess() != RF->getAccess())
6792 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6793 << LF << LF->getAccess() << RF << RF->getAccess()
6798 // The comparison here must be unsigned, and performed with the same
6799 // width as the pointer.
6800 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6801 uint64_t CompareLHS = LHSOffset.getQuantity();
6802 uint64_t CompareRHS = RHSOffset.getQuantity();
6803 assert(PtrSize <= 64 && "Unexpected pointer width");
6804 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6808 // If there is a base and this is a relational operator, we can only
6809 // compare pointers within the object in question; otherwise, the result
6810 // depends on where the object is located in memory.
6811 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6812 QualType BaseTy = getType(LHSValue.Base);
6813 if (BaseTy->isIncompleteType())
6815 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6816 uint64_t OffsetLimit = Size.getQuantity();
6817 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6821 switch (E->getOpcode()) {
6822 default: llvm_unreachable("missing comparison operator");
6823 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6824 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6825 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6826 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6827 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6828 case BO_NE: return Success(CompareLHS != CompareRHS, E);
6833 if (LHSTy->isMemberPointerType()) {
6834 assert(E->isEqualityOp() && "unexpected member pointer operation");
6835 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6837 MemberPtr LHSValue, RHSValue;
6839 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6840 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6843 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6846 // C++11 [expr.eq]p2:
6847 // If both operands are null, they compare equal. Otherwise if only one is
6848 // null, they compare unequal.
6849 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6850 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6851 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6854 // Otherwise if either is a pointer to a virtual member function, the
6855 // result is unspecified.
6856 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6857 if (MD->isVirtual())
6858 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6859 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6860 if (MD->isVirtual())
6861 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6863 // Otherwise they compare equal if and only if they would refer to the
6864 // same member of the same most derived object or the same subobject if
6865 // they were dereferenced with a hypothetical object of the associated
6867 bool Equal = LHSValue == RHSValue;
6868 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6871 if (LHSTy->isNullPtrType()) {
6872 assert(E->isComparisonOp() && "unexpected nullptr operation");
6873 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
6874 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
6875 // are compared, the result is true of the operator is <=, >= or ==, and
6877 BinaryOperator::Opcode Opcode = E->getOpcode();
6878 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
6881 assert((!LHSTy->isIntegralOrEnumerationType() ||
6882 !RHSTy->isIntegralOrEnumerationType()) &&
6883 "DataRecursiveIntBinOpEvaluator should have handled integral types");
6884 // We can't continue from here for non-integral types.
6885 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6888 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
6889 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
6890 // result shall be the alignment of the referenced type."
6891 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6892 T = Ref->getPointeeType();
6894 // __alignof is defined to return the preferred alignment.
6895 return Info.Ctx.toCharUnitsFromBits(
6896 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
6899 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
6900 E = E->IgnoreParens();
6902 // The kinds of expressions that we have special-case logic here for
6903 // should be kept up to date with the special checks for those
6904 // expressions in Sema.
6906 // alignof decl is always accepted, even if it doesn't make sense: we default
6907 // to 1 in those cases.
6908 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6909 return Info.Ctx.getDeclAlign(DRE->getDecl(),
6910 /*RefAsPointee*/true);
6912 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
6913 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
6914 /*RefAsPointee*/true);
6916 return GetAlignOfType(E->getType());
6920 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
6921 /// a result as the expression's type.
6922 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
6923 const UnaryExprOrTypeTraitExpr *E) {
6924 switch(E->getKind()) {
6925 case UETT_AlignOf: {
6926 if (E->isArgumentType())
6927 return Success(GetAlignOfType(E->getArgumentType()), E);
6929 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
6932 case UETT_VecStep: {
6933 QualType Ty = E->getTypeOfArgument();
6935 if (Ty->isVectorType()) {
6936 unsigned n = Ty->castAs<VectorType>()->getNumElements();
6938 // The vec_step built-in functions that take a 3-component
6939 // vector return 4. (OpenCL 1.1 spec 6.11.12)
6943 return Success(n, E);
6945 return Success(1, E);
6949 QualType SrcTy = E->getTypeOfArgument();
6950 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
6951 // the result is the size of the referenced type."
6952 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
6953 SrcTy = Ref->getPointeeType();
6956 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
6958 return Success(Sizeof, E);
6962 llvm_unreachable("unknown expr/type trait");
6965 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
6967 unsigned n = OOE->getNumComponents();
6970 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
6971 for (unsigned i = 0; i != n; ++i) {
6972 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
6973 switch (ON.getKind()) {
6974 case OffsetOfExpr::OffsetOfNode::Array: {
6975 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
6977 if (!EvaluateInteger(Idx, IdxResult, Info))
6979 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
6982 CurrentType = AT->getElementType();
6983 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
6984 Result += IdxResult.getSExtValue() * ElementSize;
6988 case OffsetOfExpr::OffsetOfNode::Field: {
6989 FieldDecl *MemberDecl = ON.getField();
6990 const RecordType *RT = CurrentType->getAs<RecordType>();
6993 RecordDecl *RD = RT->getDecl();
6994 if (RD->isInvalidDecl()) return false;
6995 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
6996 unsigned i = MemberDecl->getFieldIndex();
6997 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
6998 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
6999 CurrentType = MemberDecl->getType().getNonReferenceType();
7003 case OffsetOfExpr::OffsetOfNode::Identifier:
7004 llvm_unreachable("dependent __builtin_offsetof");
7006 case OffsetOfExpr::OffsetOfNode::Base: {
7007 CXXBaseSpecifier *BaseSpec = ON.getBase();
7008 if (BaseSpec->isVirtual())
7011 // Find the layout of the class whose base we are looking into.
7012 const RecordType *RT = CurrentType->getAs<RecordType>();
7015 RecordDecl *RD = RT->getDecl();
7016 if (RD->isInvalidDecl()) return false;
7017 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7019 // Find the base class itself.
7020 CurrentType = BaseSpec->getType();
7021 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7025 // Add the offset to the base.
7026 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
7031 return Success(Result, OOE);
7034 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7035 switch (E->getOpcode()) {
7037 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7041 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7042 // If so, we could clear the diagnostic ID.
7043 return Visit(E->getSubExpr());
7045 // The result is just the value.
7046 return Visit(E->getSubExpr());
7048 if (!Visit(E->getSubExpr()))
7050 if (!Result.isInt()) return Error(E);
7051 const APSInt &Value = Result.getInt();
7052 if (Value.isSigned() && Value.isMinSignedValue())
7053 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7055 return Success(-Value, E);
7058 if (!Visit(E->getSubExpr()))
7060 if (!Result.isInt()) return Error(E);
7061 return Success(~Result.getInt(), E);
7065 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
7067 return Success(!bres, E);
7072 /// HandleCast - This is used to evaluate implicit or explicit casts where the
7073 /// result type is integer.
7074 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7075 const Expr *SubExpr = E->getSubExpr();
7076 QualType DestType = E->getType();
7077 QualType SrcType = SubExpr->getType();
7079 switch (E->getCastKind()) {
7080 case CK_BaseToDerived:
7081 case CK_DerivedToBase:
7082 case CK_UncheckedDerivedToBase:
7085 case CK_ArrayToPointerDecay:
7086 case CK_FunctionToPointerDecay:
7087 case CK_NullToPointer:
7088 case CK_NullToMemberPointer:
7089 case CK_BaseToDerivedMemberPointer:
7090 case CK_DerivedToBaseMemberPointer:
7091 case CK_ReinterpretMemberPointer:
7092 case CK_ConstructorConversion:
7093 case CK_IntegralToPointer:
7095 case CK_VectorSplat:
7096 case CK_IntegralToFloating:
7097 case CK_FloatingCast:
7098 case CK_CPointerToObjCPointerCast:
7099 case CK_BlockPointerToObjCPointerCast:
7100 case CK_AnyPointerToBlockPointerCast:
7101 case CK_ObjCObjectLValueCast:
7102 case CK_FloatingRealToComplex:
7103 case CK_FloatingComplexToReal:
7104 case CK_FloatingComplexCast:
7105 case CK_FloatingComplexToIntegralComplex:
7106 case CK_IntegralRealToComplex:
7107 case CK_IntegralComplexCast:
7108 case CK_IntegralComplexToFloatingComplex:
7109 case CK_BuiltinFnToFnPtr:
7110 case CK_ZeroToOCLEvent:
7111 case CK_NonAtomicToAtomic:
7112 llvm_unreachable("invalid cast kind for integral value");
7116 case CK_LValueBitCast:
7117 case CK_ARCProduceObject:
7118 case CK_ARCConsumeObject:
7119 case CK_ARCReclaimReturnedObject:
7120 case CK_ARCExtendBlockObject:
7121 case CK_CopyAndAutoreleaseBlockObject:
7124 case CK_UserDefinedConversion:
7125 case CK_LValueToRValue:
7126 case CK_AtomicToNonAtomic:
7128 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7130 case CK_MemberPointerToBoolean:
7131 case CK_PointerToBoolean:
7132 case CK_IntegralToBoolean:
7133 case CK_FloatingToBoolean:
7134 case CK_FloatingComplexToBoolean:
7135 case CK_IntegralComplexToBoolean: {
7137 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
7139 return Success(BoolResult, E);
7142 case CK_IntegralCast: {
7143 if (!Visit(SubExpr))
7146 if (!Result.isInt()) {
7147 // Allow casts of address-of-label differences if they are no-ops
7148 // or narrowing. (The narrowing case isn't actually guaranteed to
7149 // be constant-evaluatable except in some narrow cases which are hard
7150 // to detect here. We let it through on the assumption the user knows
7151 // what they are doing.)
7152 if (Result.isAddrLabelDiff())
7153 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
7154 // Only allow casts of lvalues if they are lossless.
7155 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7158 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7159 Result.getInt()), E);
7162 case CK_PointerToIntegral: {
7163 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7166 if (!EvaluatePointer(SubExpr, LV, Info))
7169 if (LV.getLValueBase()) {
7170 // Only allow based lvalue casts if they are lossless.
7171 // FIXME: Allow a larger integer size than the pointer size, and allow
7172 // narrowing back down to pointer width in subsequent integral casts.
7173 // FIXME: Check integer type's active bits, not its type size.
7174 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
7177 LV.Designator.setInvalid();
7178 LV.moveInto(Result);
7182 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7184 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
7187 case CK_IntegralComplexToReal: {
7189 if (!EvaluateComplex(SubExpr, C, Info))
7191 return Success(C.getComplexIntReal(), E);
7194 case CK_FloatingToIntegral: {
7196 if (!EvaluateFloat(SubExpr, F, Info))
7200 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7202 return Success(Value, E);
7206 llvm_unreachable("unknown cast resulting in integral value");
7209 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7210 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7212 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7214 if (!LV.isComplexInt())
7216 return Success(LV.getComplexIntReal(), E);
7219 return Visit(E->getSubExpr());
7222 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7223 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
7225 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7227 if (!LV.isComplexInt())
7229 return Success(LV.getComplexIntImag(), E);
7232 VisitIgnoredValue(E->getSubExpr());
7233 return Success(0, E);
7236 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7237 return Success(E->getPackLength(), E);
7240 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7241 return Success(E->getValue(), E);
7244 //===----------------------------------------------------------------------===//
7246 //===----------------------------------------------------------------------===//
7249 class FloatExprEvaluator
7250 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
7253 FloatExprEvaluator(EvalInfo &info, APFloat &result)
7254 : ExprEvaluatorBaseTy(info), Result(result) {}
7256 bool Success(const APValue &V, const Expr *e) {
7257 Result = V.getFloat();
7261 bool ZeroInitialization(const Expr *E) {
7262 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7266 bool VisitCallExpr(const CallExpr *E);
7268 bool VisitUnaryOperator(const UnaryOperator *E);
7269 bool VisitBinaryOperator(const BinaryOperator *E);
7270 bool VisitFloatingLiteral(const FloatingLiteral *E);
7271 bool VisitCastExpr(const CastExpr *E);
7273 bool VisitUnaryReal(const UnaryOperator *E);
7274 bool VisitUnaryImag(const UnaryOperator *E);
7276 // FIXME: Missing: array subscript of vector, member of vector
7278 } // end anonymous namespace
7280 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
7281 assert(E->isRValue() && E->getType()->isRealFloatingType());
7282 return FloatExprEvaluator(Info, Result).Visit(E);
7285 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
7289 llvm::APFloat &Result) {
7290 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7291 if (!S) return false;
7293 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7297 // Treat empty strings as if they were zero.
7298 if (S->getString().empty())
7299 fill = llvm::APInt(32, 0);
7300 else if (S->getString().getAsInteger(0, fill))
7304 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7306 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7310 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
7311 switch (E->isBuiltinCall()) {
7313 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7315 case Builtin::BI__builtin_huge_val:
7316 case Builtin::BI__builtin_huge_valf:
7317 case Builtin::BI__builtin_huge_vall:
7318 case Builtin::BI__builtin_inf:
7319 case Builtin::BI__builtin_inff:
7320 case Builtin::BI__builtin_infl: {
7321 const llvm::fltSemantics &Sem =
7322 Info.Ctx.getFloatTypeSemantics(E->getType());
7323 Result = llvm::APFloat::getInf(Sem);
7327 case Builtin::BI__builtin_nans:
7328 case Builtin::BI__builtin_nansf:
7329 case Builtin::BI__builtin_nansl:
7330 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7335 case Builtin::BI__builtin_nan:
7336 case Builtin::BI__builtin_nanf:
7337 case Builtin::BI__builtin_nanl:
7338 // If this is __builtin_nan() turn this into a nan, otherwise we
7339 // can't constant fold it.
7340 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7345 case Builtin::BI__builtin_fabs:
7346 case Builtin::BI__builtin_fabsf:
7347 case Builtin::BI__builtin_fabsl:
7348 if (!EvaluateFloat(E->getArg(0), Result, Info))
7351 if (Result.isNegative())
7352 Result.changeSign();
7355 // FIXME: Builtin::BI__builtin_powi
7356 // FIXME: Builtin::BI__builtin_powif
7357 // FIXME: Builtin::BI__builtin_powil
7359 case Builtin::BI__builtin_copysign:
7360 case Builtin::BI__builtin_copysignf:
7361 case Builtin::BI__builtin_copysignl: {
7363 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7364 !EvaluateFloat(E->getArg(1), RHS, Info))
7366 Result.copySign(RHS);
7372 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7373 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7375 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7377 Result = CV.FloatReal;
7381 return Visit(E->getSubExpr());
7384 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7385 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7387 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7389 Result = CV.FloatImag;
7393 VisitIgnoredValue(E->getSubExpr());
7394 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7395 Result = llvm::APFloat::getZero(Sem);
7399 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7400 switch (E->getOpcode()) {
7401 default: return Error(E);
7403 return EvaluateFloat(E->getSubExpr(), Result, Info);
7405 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7407 Result.changeSign();
7412 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7413 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7414 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7417 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7418 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7420 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7421 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
7424 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7425 Result = E->getValue();
7429 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7430 const Expr* SubExpr = E->getSubExpr();
7432 switch (E->getCastKind()) {
7434 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7436 case CK_IntegralToFloating: {
7438 return EvaluateInteger(SubExpr, IntResult, Info) &&
7439 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7440 E->getType(), Result);
7443 case CK_FloatingCast: {
7444 if (!Visit(SubExpr))
7446 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7450 case CK_FloatingComplexToReal: {
7452 if (!EvaluateComplex(SubExpr, V, Info))
7454 Result = V.getComplexFloatReal();
7460 //===----------------------------------------------------------------------===//
7461 // Complex Evaluation (for float and integer)
7462 //===----------------------------------------------------------------------===//
7465 class ComplexExprEvaluator
7466 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
7467 ComplexValue &Result;
7470 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
7471 : ExprEvaluatorBaseTy(info), Result(Result) {}
7473 bool Success(const APValue &V, const Expr *e) {
7478 bool ZeroInitialization(const Expr *E);
7480 //===--------------------------------------------------------------------===//
7482 //===--------------------------------------------------------------------===//
7484 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
7485 bool VisitCastExpr(const CastExpr *E);
7486 bool VisitBinaryOperator(const BinaryOperator *E);
7487 bool VisitUnaryOperator(const UnaryOperator *E);
7488 bool VisitInitListExpr(const InitListExpr *E);
7490 } // end anonymous namespace
7492 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7494 assert(E->isRValue() && E->getType()->isAnyComplexType());
7495 return ComplexExprEvaluator(Info, Result).Visit(E);
7498 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
7499 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
7500 if (ElemTy->isRealFloatingType()) {
7501 Result.makeComplexFloat();
7502 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7503 Result.FloatReal = Zero;
7504 Result.FloatImag = Zero;
7506 Result.makeComplexInt();
7507 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7508 Result.IntReal = Zero;
7509 Result.IntImag = Zero;
7514 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7515 const Expr* SubExpr = E->getSubExpr();
7517 if (SubExpr->getType()->isRealFloatingType()) {
7518 Result.makeComplexFloat();
7519 APFloat &Imag = Result.FloatImag;
7520 if (!EvaluateFloat(SubExpr, Imag, Info))
7523 Result.FloatReal = APFloat(Imag.getSemantics());
7526 assert(SubExpr->getType()->isIntegerType() &&
7527 "Unexpected imaginary literal.");
7529 Result.makeComplexInt();
7530 APSInt &Imag = Result.IntImag;
7531 if (!EvaluateInteger(SubExpr, Imag, Info))
7534 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7539 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
7541 switch (E->getCastKind()) {
7543 case CK_BaseToDerived:
7544 case CK_DerivedToBase:
7545 case CK_UncheckedDerivedToBase:
7548 case CK_ArrayToPointerDecay:
7549 case CK_FunctionToPointerDecay:
7550 case CK_NullToPointer:
7551 case CK_NullToMemberPointer:
7552 case CK_BaseToDerivedMemberPointer:
7553 case CK_DerivedToBaseMemberPointer:
7554 case CK_MemberPointerToBoolean:
7555 case CK_ReinterpretMemberPointer:
7556 case CK_ConstructorConversion:
7557 case CK_IntegralToPointer:
7558 case CK_PointerToIntegral:
7559 case CK_PointerToBoolean:
7561 case CK_VectorSplat:
7562 case CK_IntegralCast:
7563 case CK_IntegralToBoolean:
7564 case CK_IntegralToFloating:
7565 case CK_FloatingToIntegral:
7566 case CK_FloatingToBoolean:
7567 case CK_FloatingCast:
7568 case CK_CPointerToObjCPointerCast:
7569 case CK_BlockPointerToObjCPointerCast:
7570 case CK_AnyPointerToBlockPointerCast:
7571 case CK_ObjCObjectLValueCast:
7572 case CK_FloatingComplexToReal:
7573 case CK_FloatingComplexToBoolean:
7574 case CK_IntegralComplexToReal:
7575 case CK_IntegralComplexToBoolean:
7576 case CK_ARCProduceObject:
7577 case CK_ARCConsumeObject:
7578 case CK_ARCReclaimReturnedObject:
7579 case CK_ARCExtendBlockObject:
7580 case CK_CopyAndAutoreleaseBlockObject:
7581 case CK_BuiltinFnToFnPtr:
7582 case CK_ZeroToOCLEvent:
7583 case CK_NonAtomicToAtomic:
7584 llvm_unreachable("invalid cast kind for complex value");
7586 case CK_LValueToRValue:
7587 case CK_AtomicToNonAtomic:
7589 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7592 case CK_LValueBitCast:
7593 case CK_UserDefinedConversion:
7596 case CK_FloatingRealToComplex: {
7597 APFloat &Real = Result.FloatReal;
7598 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
7601 Result.makeComplexFloat();
7602 Result.FloatImag = APFloat(Real.getSemantics());
7606 case CK_FloatingComplexCast: {
7607 if (!Visit(E->getSubExpr()))
7610 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7612 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7614 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7615 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
7618 case CK_FloatingComplexToIntegralComplex: {
7619 if (!Visit(E->getSubExpr()))
7622 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7624 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7625 Result.makeComplexInt();
7626 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7627 To, Result.IntReal) &&
7628 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7629 To, Result.IntImag);
7632 case CK_IntegralRealToComplex: {
7633 APSInt &Real = Result.IntReal;
7634 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7637 Result.makeComplexInt();
7638 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7642 case CK_IntegralComplexCast: {
7643 if (!Visit(E->getSubExpr()))
7646 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7648 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7650 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7651 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
7655 case CK_IntegralComplexToFloatingComplex: {
7656 if (!Visit(E->getSubExpr()))
7659 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
7661 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
7662 Result.makeComplexFloat();
7663 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7664 To, Result.FloatReal) &&
7665 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7666 To, Result.FloatImag);
7670 llvm_unreachable("unknown cast resulting in complex value");
7673 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7674 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7675 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7677 bool LHSOK = Visit(E->getLHS());
7678 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
7682 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
7685 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7686 "Invalid operands to binary operator.");
7687 switch (E->getOpcode()) {
7688 default: return Error(E);
7690 if (Result.isComplexFloat()) {
7691 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7692 APFloat::rmNearestTiesToEven);
7693 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7694 APFloat::rmNearestTiesToEven);
7696 Result.getComplexIntReal() += RHS.getComplexIntReal();
7697 Result.getComplexIntImag() += RHS.getComplexIntImag();
7701 if (Result.isComplexFloat()) {
7702 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7703 APFloat::rmNearestTiesToEven);
7704 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7705 APFloat::rmNearestTiesToEven);
7707 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7708 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7712 if (Result.isComplexFloat()) {
7713 ComplexValue LHS = Result;
7714 APFloat &LHS_r = LHS.getComplexFloatReal();
7715 APFloat &LHS_i = LHS.getComplexFloatImag();
7716 APFloat &RHS_r = RHS.getComplexFloatReal();
7717 APFloat &RHS_i = RHS.getComplexFloatImag();
7719 APFloat Tmp = LHS_r;
7720 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7721 Result.getComplexFloatReal() = Tmp;
7723 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7724 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7727 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7728 Result.getComplexFloatImag() = Tmp;
7730 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7731 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7733 ComplexValue LHS = Result;
7734 Result.getComplexIntReal() =
7735 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7736 LHS.getComplexIntImag() * RHS.getComplexIntImag());
7737 Result.getComplexIntImag() =
7738 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7739 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7743 if (Result.isComplexFloat()) {
7744 ComplexValue LHS = Result;
7745 APFloat &LHS_r = LHS.getComplexFloatReal();
7746 APFloat &LHS_i = LHS.getComplexFloatImag();
7747 APFloat &RHS_r = RHS.getComplexFloatReal();
7748 APFloat &RHS_i = RHS.getComplexFloatImag();
7749 APFloat &Res_r = Result.getComplexFloatReal();
7750 APFloat &Res_i = Result.getComplexFloatImag();
7752 APFloat Den = RHS_r;
7753 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7754 APFloat Tmp = RHS_i;
7755 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7756 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7759 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7761 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7762 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7763 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7766 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7768 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7769 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7770 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7772 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7773 return Error(E, diag::note_expr_divide_by_zero);
7775 ComplexValue LHS = Result;
7776 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7777 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7778 Result.getComplexIntReal() =
7779 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7780 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7781 Result.getComplexIntImag() =
7782 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7783 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7791 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7792 // Get the operand value into 'Result'.
7793 if (!Visit(E->getSubExpr()))
7796 switch (E->getOpcode()) {
7802 // The result is always just the subexpr.
7805 if (Result.isComplexFloat()) {
7806 Result.getComplexFloatReal().changeSign();
7807 Result.getComplexFloatImag().changeSign();
7810 Result.getComplexIntReal() = -Result.getComplexIntReal();
7811 Result.getComplexIntImag() = -Result.getComplexIntImag();
7815 if (Result.isComplexFloat())
7816 Result.getComplexFloatImag().changeSign();
7818 Result.getComplexIntImag() = -Result.getComplexIntImag();
7823 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7824 if (E->getNumInits() == 2) {
7825 if (E->getType()->isComplexType()) {
7826 Result.makeComplexFloat();
7827 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7829 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7832 Result.makeComplexInt();
7833 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7835 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7840 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7843 //===----------------------------------------------------------------------===//
7844 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7845 // implicit conversion.
7846 //===----------------------------------------------------------------------===//
7849 class AtomicExprEvaluator :
7850 public ExprEvaluatorBase<AtomicExprEvaluator, bool> {
7853 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7854 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7856 bool Success(const APValue &V, const Expr *E) {
7861 bool ZeroInitialization(const Expr *E) {
7862 ImplicitValueInitExpr VIE(
7863 E->getType()->castAs<AtomicType>()->getValueType());
7864 return Evaluate(Result, Info, &VIE);
7867 bool VisitCastExpr(const CastExpr *E) {
7868 switch (E->getCastKind()) {
7870 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7871 case CK_NonAtomicToAtomic:
7872 return Evaluate(Result, Info, E->getSubExpr());
7876 } // end anonymous namespace
7878 static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
7879 assert(E->isRValue() && E->getType()->isAtomicType());
7880 return AtomicExprEvaluator(Info, Result).Visit(E);
7883 //===----------------------------------------------------------------------===//
7884 // Void expression evaluation, primarily for a cast to void on the LHS of a
7886 //===----------------------------------------------------------------------===//
7889 class VoidExprEvaluator
7890 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
7892 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
7894 bool Success(const APValue &V, const Expr *e) { return true; }
7896 bool VisitCastExpr(const CastExpr *E) {
7897 switch (E->getCastKind()) {
7899 return ExprEvaluatorBaseTy::VisitCastExpr(E);
7901 VisitIgnoredValue(E->getSubExpr());
7906 } // end anonymous namespace
7908 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
7909 assert(E->isRValue() && E->getType()->isVoidType());
7910 return VoidExprEvaluator(Info).Visit(E);
7913 //===----------------------------------------------------------------------===//
7914 // Top level Expr::EvaluateAsRValue method.
7915 //===----------------------------------------------------------------------===//
7917 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
7918 // In C, function designators are not lvalues, but we evaluate them as if they
7920 QualType T = E->getType();
7921 if (E->isGLValue() || T->isFunctionType()) {
7923 if (!EvaluateLValue(E, LV, Info))
7925 LV.moveInto(Result);
7926 } else if (T->isVectorType()) {
7927 if (!EvaluateVector(E, Result, Info))
7929 } else if (T->isIntegralOrEnumerationType()) {
7930 if (!IntExprEvaluator(Info, Result).Visit(E))
7932 } else if (T->hasPointerRepresentation()) {
7934 if (!EvaluatePointer(E, LV, Info))
7936 LV.moveInto(Result);
7937 } else if (T->isRealFloatingType()) {
7938 llvm::APFloat F(0.0);
7939 if (!EvaluateFloat(E, F, Info))
7941 Result = APValue(F);
7942 } else if (T->isAnyComplexType()) {
7944 if (!EvaluateComplex(E, C, Info))
7947 } else if (T->isMemberPointerType()) {
7949 if (!EvaluateMemberPointer(E, P, Info))
7953 } else if (T->isArrayType()) {
7955 LV.set(E, Info.CurrentCall->Index);
7956 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7957 if (!EvaluateArray(E, LV, Value, Info))
7960 } else if (T->isRecordType()) {
7962 LV.set(E, Info.CurrentCall->Index);
7963 APValue &Value = Info.CurrentCall->createTemporary(E, false);
7964 if (!EvaluateRecord(E, LV, Value, Info))
7967 } else if (T->isVoidType()) {
7968 if (!Info.getLangOpts().CPlusPlus11)
7969 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
7971 if (!EvaluateVoid(E, Info))
7973 } else if (T->isAtomicType()) {
7974 if (!EvaluateAtomic(E, Result, Info))
7976 } else if (Info.getLangOpts().CPlusPlus11) {
7977 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
7980 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
7987 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
7988 /// cases, the in-place evaluation is essential, since later initializers for
7989 /// an object can indirectly refer to subobjects which were initialized earlier.
7990 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
7991 const Expr *E, bool AllowNonLiteralTypes) {
7992 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
7995 if (E->isRValue()) {
7996 // Evaluate arrays and record types in-place, so that later initializers can
7997 // refer to earlier-initialized members of the object.
7998 if (E->getType()->isArrayType())
7999 return EvaluateArray(E, This, Result, Info);
8000 else if (E->getType()->isRecordType())
8001 return EvaluateRecord(E, This, Result, Info);
8004 // For any other type, in-place evaluation is unimportant.
8005 return Evaluate(Result, Info, E);
8008 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8009 /// lvalue-to-rvalue cast if it is an lvalue.
8010 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
8011 if (!CheckLiteralType(Info, E))
8014 if (!::Evaluate(Result, Info, E))
8017 if (E->isGLValue()) {
8019 LV.setFrom(Info.Ctx, Result);
8020 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
8024 // Check this core constant expression is a constant expression.
8025 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
8028 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8029 const ASTContext &Ctx, bool &IsConst) {
8030 // Fast-path evaluations of integer literals, since we sometimes see files
8031 // containing vast quantities of these.
8032 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8033 Result.Val = APValue(APSInt(L->getValue(),
8034 L->getType()->isUnsignedIntegerType()));
8039 // FIXME: Evaluating values of large array and record types can cause
8040 // performance problems. Only do so in C++11 for now.
8041 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8042 Exp->getType()->isRecordType()) &&
8043 !Ctx.getLangOpts().CPlusPlus11) {
8051 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
8052 /// any crazy technique (that has nothing to do with language standards) that
8053 /// we want to. If this function returns true, it returns the folded constant
8054 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8055 /// will be applied to the result.
8056 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
8058 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8061 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
8062 return ::EvaluateAsRValue(Info, this, Result.Val);
8065 bool Expr::EvaluateAsBooleanCondition(bool &Result,
8066 const ASTContext &Ctx) const {
8068 return EvaluateAsRValue(Scratch, Ctx) &&
8069 HandleConversionToBool(Scratch.Val, Result);
8072 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8073 SideEffectsKind AllowSideEffects) const {
8074 if (!getType()->isIntegralOrEnumerationType())
8077 EvalResult ExprResult;
8078 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8079 (!AllowSideEffects && ExprResult.HasSideEffects))
8082 Result = ExprResult.Val.getInt();
8086 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
8087 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
8090 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8091 !CheckLValueConstantExpression(Info, getExprLoc(),
8092 Ctx.getLValueReferenceType(getType()), LV))
8095 LV.moveInto(Result.Val);
8099 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8101 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
8102 // FIXME: Evaluating initializers for large array and record types can cause
8103 // performance problems. Only do so in C++11 for now.
8104 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
8105 !Ctx.getLangOpts().CPlusPlus11)
8108 Expr::EvalStatus EStatus;
8109 EStatus.Diag = &Notes;
8111 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
8112 InitInfo.setEvaluatingDecl(VD, Value);
8117 // C++11 [basic.start.init]p2:
8118 // Variables with static storage duration or thread storage duration shall be
8119 // zero-initialized before any other initialization takes place.
8120 // This behavior is not present in C.
8121 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
8122 !VD->getType()->isReferenceType()) {
8123 ImplicitValueInitExpr VIE(VD->getType());
8124 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
8125 /*AllowNonLiteralTypes=*/true))
8129 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8130 /*AllowNonLiteralTypes=*/true) ||
8131 EStatus.HasSideEffects)
8134 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8138 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8139 /// constant folded, but discard the result.
8140 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
8142 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
8145 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
8146 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
8147 EvalResult EvalResult;
8148 EvalResult.Diag = Diag;
8149 bool Result = EvaluateAsRValue(EvalResult, Ctx);
8151 assert(Result && "Could not evaluate expression");
8152 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
8154 return EvalResult.Val.getInt();
8157 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
8159 EvalResult EvalResult;
8160 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
8161 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
8162 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8166 bool Expr::EvalResult::isGlobalLValue() const {
8167 assert(Val.isLValue());
8168 return IsGlobalLValue(Val.getLValueBase());
8172 /// isIntegerConstantExpr - this recursive routine will test if an expression is
8173 /// an integer constant expression.
8175 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8178 // CheckICE - This function does the fundamental ICE checking: the returned
8179 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8180 // and a (possibly null) SourceLocation indicating the location of the problem.
8182 // Note that to reduce code duplication, this helper does no evaluation
8183 // itself; the caller checks whether the expression is evaluatable, and
8184 // in the rare cases where CheckICE actually cares about the evaluated
8185 // value, it calls into Evalute.
8190 /// This expression is an ICE.
8192 /// This expression is not an ICE, but if it isn't evaluated, it's
8193 /// a legal subexpression for an ICE. This return value is used to handle
8194 /// the comma operator in C99 mode, and non-constant subexpressions.
8195 IK_ICEIfUnevaluated,
8196 /// This expression is not an ICE, and is not a legal subexpression for one.
8204 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
8209 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8211 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
8213 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
8214 Expr::EvalResult EVResult;
8215 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
8216 !EVResult.Val.isInt())
8217 return ICEDiag(IK_NotICE, E->getLocStart());
8222 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
8223 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
8224 if (!E->getType()->isIntegralOrEnumerationType())
8225 return ICEDiag(IK_NotICE, E->getLocStart());
8227 switch (E->getStmtClass()) {
8228 #define ABSTRACT_STMT(Node)
8229 #define STMT(Node, Base) case Expr::Node##Class:
8230 #define EXPR(Node, Base)
8231 #include "clang/AST/StmtNodes.inc"
8232 case Expr::PredefinedExprClass:
8233 case Expr::FloatingLiteralClass:
8234 case Expr::ImaginaryLiteralClass:
8235 case Expr::StringLiteralClass:
8236 case Expr::ArraySubscriptExprClass:
8237 case Expr::MemberExprClass:
8238 case Expr::CompoundAssignOperatorClass:
8239 case Expr::CompoundLiteralExprClass:
8240 case Expr::ExtVectorElementExprClass:
8241 case Expr::DesignatedInitExprClass:
8242 case Expr::ImplicitValueInitExprClass:
8243 case Expr::ParenListExprClass:
8244 case Expr::VAArgExprClass:
8245 case Expr::AddrLabelExprClass:
8246 case Expr::StmtExprClass:
8247 case Expr::CXXMemberCallExprClass:
8248 case Expr::CUDAKernelCallExprClass:
8249 case Expr::CXXDynamicCastExprClass:
8250 case Expr::CXXTypeidExprClass:
8251 case Expr::CXXUuidofExprClass:
8252 case Expr::MSPropertyRefExprClass:
8253 case Expr::CXXNullPtrLiteralExprClass:
8254 case Expr::UserDefinedLiteralClass:
8255 case Expr::CXXThisExprClass:
8256 case Expr::CXXThrowExprClass:
8257 case Expr::CXXNewExprClass:
8258 case Expr::CXXDeleteExprClass:
8259 case Expr::CXXPseudoDestructorExprClass:
8260 case Expr::UnresolvedLookupExprClass:
8261 case Expr::DependentScopeDeclRefExprClass:
8262 case Expr::CXXConstructExprClass:
8263 case Expr::CXXStdInitializerListExprClass:
8264 case Expr::CXXBindTemporaryExprClass:
8265 case Expr::ExprWithCleanupsClass:
8266 case Expr::CXXTemporaryObjectExprClass:
8267 case Expr::CXXUnresolvedConstructExprClass:
8268 case Expr::CXXDependentScopeMemberExprClass:
8269 case Expr::UnresolvedMemberExprClass:
8270 case Expr::ObjCStringLiteralClass:
8271 case Expr::ObjCBoxedExprClass:
8272 case Expr::ObjCArrayLiteralClass:
8273 case Expr::ObjCDictionaryLiteralClass:
8274 case Expr::ObjCEncodeExprClass:
8275 case Expr::ObjCMessageExprClass:
8276 case Expr::ObjCSelectorExprClass:
8277 case Expr::ObjCProtocolExprClass:
8278 case Expr::ObjCIvarRefExprClass:
8279 case Expr::ObjCPropertyRefExprClass:
8280 case Expr::ObjCSubscriptRefExprClass:
8281 case Expr::ObjCIsaExprClass:
8282 case Expr::ShuffleVectorExprClass:
8283 case Expr::ConvertVectorExprClass:
8284 case Expr::BlockExprClass:
8285 case Expr::NoStmtClass:
8286 case Expr::OpaqueValueExprClass:
8287 case Expr::PackExpansionExprClass:
8288 case Expr::SubstNonTypeTemplateParmPackExprClass:
8289 case Expr::FunctionParmPackExprClass:
8290 case Expr::AsTypeExprClass:
8291 case Expr::ObjCIndirectCopyRestoreExprClass:
8292 case Expr::MaterializeTemporaryExprClass:
8293 case Expr::PseudoObjectExprClass:
8294 case Expr::AtomicExprClass:
8295 case Expr::InitListExprClass:
8296 case Expr::LambdaExprClass:
8297 return ICEDiag(IK_NotICE, E->getLocStart());
8299 case Expr::SizeOfPackExprClass:
8300 case Expr::GNUNullExprClass:
8301 // GCC considers the GNU __null value to be an integral constant expression.
8304 case Expr::SubstNonTypeTemplateParmExprClass:
8306 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8308 case Expr::ParenExprClass:
8309 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
8310 case Expr::GenericSelectionExprClass:
8311 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
8312 case Expr::IntegerLiteralClass:
8313 case Expr::CharacterLiteralClass:
8314 case Expr::ObjCBoolLiteralExprClass:
8315 case Expr::CXXBoolLiteralExprClass:
8316 case Expr::CXXScalarValueInitExprClass:
8317 case Expr::UnaryTypeTraitExprClass:
8318 case Expr::BinaryTypeTraitExprClass:
8319 case Expr::TypeTraitExprClass:
8320 case Expr::ArrayTypeTraitExprClass:
8321 case Expr::ExpressionTraitExprClass:
8322 case Expr::CXXNoexceptExprClass:
8324 case Expr::CallExprClass:
8325 case Expr::CXXOperatorCallExprClass: {
8326 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8327 // constant expressions, but they can never be ICEs because an ICE cannot
8328 // contain an operand of (pointer to) function type.
8329 const CallExpr *CE = cast<CallExpr>(E);
8330 if (CE->isBuiltinCall())
8331 return CheckEvalInICE(E, Ctx);
8332 return ICEDiag(IK_NotICE, E->getLocStart());
8334 case Expr::DeclRefExprClass: {
8335 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8337 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
8338 if (Ctx.getLangOpts().CPlusPlus &&
8339 D && IsConstNonVolatile(D->getType())) {
8340 // Parameter variables are never constants. Without this check,
8341 // getAnyInitializer() can find a default argument, which leads
8343 if (isa<ParmVarDecl>(D))
8344 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8347 // A variable of non-volatile const-qualified integral or enumeration
8348 // type initialized by an ICE can be used in ICEs.
8349 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
8350 if (!Dcl->getType()->isIntegralOrEnumerationType())
8351 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8354 // Look for a declaration of this variable that has an initializer, and
8355 // check whether it is an ICE.
8356 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8359 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
8362 return ICEDiag(IK_NotICE, E->getLocStart());
8364 case Expr::UnaryOperatorClass: {
8365 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8366 switch (Exp->getOpcode()) {
8373 // C99 6.6/3 allows increment and decrement within unevaluated
8374 // subexpressions of constant expressions, but they can never be ICEs
8375 // because an ICE cannot contain an lvalue operand.
8376 return ICEDiag(IK_NotICE, E->getLocStart());
8384 return CheckICE(Exp->getSubExpr(), Ctx);
8387 // OffsetOf falls through here.
8389 case Expr::OffsetOfExprClass: {
8390 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8391 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8392 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8393 // compliance: we should warn earlier for offsetof expressions with
8394 // array subscripts that aren't ICEs, and if the array subscripts
8395 // are ICEs, the value of the offsetof must be an integer constant.
8396 return CheckEvalInICE(E, Ctx);
8398 case Expr::UnaryExprOrTypeTraitExprClass: {
8399 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8400 if ((Exp->getKind() == UETT_SizeOf) &&
8401 Exp->getTypeOfArgument()->isVariableArrayType())
8402 return ICEDiag(IK_NotICE, E->getLocStart());
8405 case Expr::BinaryOperatorClass: {
8406 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8407 switch (Exp->getOpcode()) {
8421 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8422 // constant expressions, but they can never be ICEs because an ICE cannot
8423 // contain an lvalue operand.
8424 return ICEDiag(IK_NotICE, E->getLocStart());
8443 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8444 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8445 if (Exp->getOpcode() == BO_Div ||
8446 Exp->getOpcode() == BO_Rem) {
8447 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
8448 // we don't evaluate one.
8449 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
8450 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
8452 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8453 if (REval.isSigned() && REval.isAllOnesValue()) {
8454 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
8455 if (LEval.isMinSignedValue())
8456 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8460 if (Exp->getOpcode() == BO_Comma) {
8461 if (Ctx.getLangOpts().C99) {
8462 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8463 // if it isn't evaluated.
8464 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8465 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
8467 // In both C89 and C++, commas in ICEs are illegal.
8468 return ICEDiag(IK_NotICE, E->getLocStart());
8471 return Worst(LHSResult, RHSResult);
8475 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8476 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
8477 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
8478 // Rare case where the RHS has a comma "side-effect"; we need
8479 // to actually check the condition to see whether the side
8480 // with the comma is evaluated.
8481 if ((Exp->getOpcode() == BO_LAnd) !=
8482 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
8487 return Worst(LHSResult, RHSResult);
8491 case Expr::ImplicitCastExprClass:
8492 case Expr::CStyleCastExprClass:
8493 case Expr::CXXFunctionalCastExprClass:
8494 case Expr::CXXStaticCastExprClass:
8495 case Expr::CXXReinterpretCastExprClass:
8496 case Expr::CXXConstCastExprClass:
8497 case Expr::ObjCBridgedCastExprClass: {
8498 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
8499 if (isa<ExplicitCastExpr>(E)) {
8500 if (const FloatingLiteral *FL
8501 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8502 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8503 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8504 APSInt IgnoredVal(DestWidth, !DestSigned);
8506 // If the value does not fit in the destination type, the behavior is
8507 // undefined, so we are not required to treat it as a constant
8509 if (FL->getValue().convertToInteger(IgnoredVal,
8510 llvm::APFloat::rmTowardZero,
8511 &Ignored) & APFloat::opInvalidOp)
8512 return ICEDiag(IK_NotICE, E->getLocStart());
8516 switch (cast<CastExpr>(E)->getCastKind()) {
8517 case CK_LValueToRValue:
8518 case CK_AtomicToNonAtomic:
8519 case CK_NonAtomicToAtomic:
8521 case CK_IntegralToBoolean:
8522 case CK_IntegralCast:
8523 return CheckICE(SubExpr, Ctx);
8525 return ICEDiag(IK_NotICE, E->getLocStart());
8528 case Expr::BinaryConditionalOperatorClass: {
8529 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8530 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
8531 if (CommonResult.Kind == IK_NotICE) return CommonResult;
8532 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8533 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8534 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8535 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
8536 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
8539 case Expr::ConditionalOperatorClass: {
8540 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8541 // If the condition (ignoring parens) is a __builtin_constant_p call,
8542 // then only the true side is actually considered in an integer constant
8543 // expression, and it is fully evaluated. This is an important GNU
8544 // extension. See GCC PR38377 for discussion.
8545 if (const CallExpr *CallCE
8546 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
8547 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
8548 return CheckEvalInICE(E, Ctx);
8549 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
8550 if (CondResult.Kind == IK_NotICE)
8553 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8554 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
8556 if (TrueResult.Kind == IK_NotICE)
8558 if (FalseResult.Kind == IK_NotICE)
8560 if (CondResult.Kind == IK_ICEIfUnevaluated)
8562 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
8564 // Rare case where the diagnostics depend on which side is evaluated
8565 // Note that if we get here, CondResult is 0, and at least one of
8566 // TrueResult and FalseResult is non-zero.
8567 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
8571 case Expr::CXXDefaultArgExprClass:
8572 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
8573 case Expr::CXXDefaultInitExprClass:
8574 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
8575 case Expr::ChooseExprClass: {
8576 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
8580 llvm_unreachable("Invalid StmtClass!");
8583 /// Evaluate an expression as a C++11 integral constant expression.
8584 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
8586 llvm::APSInt *Value,
8587 SourceLocation *Loc) {
8588 if (!E->getType()->isIntegralOrEnumerationType()) {
8589 if (Loc) *Loc = E->getExprLoc();
8594 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
8597 assert(Result.isInt() && "pointer cast to int is not an ICE");
8598 if (Value) *Value = Result.getInt();
8602 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8603 SourceLocation *Loc) const {
8604 if (Ctx.getLangOpts().CPlusPlus11)
8605 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
8607 ICEDiag D = CheckICE(this, Ctx);
8608 if (D.Kind != IK_ICE) {
8609 if (Loc) *Loc = D.Loc;
8615 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
8616 SourceLocation *Loc, bool isEvaluated) const {
8617 if (Ctx.getLangOpts().CPlusPlus11)
8618 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8620 if (!isIntegerConstantExpr(Ctx, Loc))
8622 if (!EvaluateAsInt(Value, Ctx))
8623 llvm_unreachable("ICE cannot be evaluated!");
8627 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
8628 return CheckICE(this, Ctx).Kind == IK_ICE;
8631 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
8632 SourceLocation *Loc) const {
8633 // We support this checking in C++98 mode in order to diagnose compatibility
8635 assert(Ctx.getLangOpts().CPlusPlus);
8637 // Build evaluation settings.
8638 Expr::EvalStatus Status;
8639 SmallVector<PartialDiagnosticAt, 8> Diags;
8640 Status.Diag = &Diags;
8641 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
8644 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8646 if (!Diags.empty()) {
8647 IsConstExpr = false;
8648 if (Loc) *Loc = Diags[0].first;
8649 } else if (!IsConstExpr) {
8650 // FIXME: This shouldn't happen.
8651 if (Loc) *Loc = getExprLoc();
8657 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
8659 PartialDiagnosticAt> &Diags) {
8660 // FIXME: It would be useful to check constexpr function templates, but at the
8661 // moment the constant expression evaluator cannot cope with the non-rigorous
8662 // ASTs which we build for dependent expressions.
8663 if (FD->isDependentContext())
8666 Expr::EvalStatus Status;
8667 Status.Diag = &Diags;
8669 EvalInfo Info(FD->getASTContext(), Status,
8670 EvalInfo::EM_PotentialConstantExpression);
8672 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8673 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
8675 // Fabricate an arbitrary expression on the stack and pretend that it
8676 // is a temporary being used as the 'this' pointer.
8678 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
8679 This.set(&VIE, Info.CurrentCall->Index);
8681 ArrayRef<const Expr*> Args;
8683 SourceLocation Loc = FD->getLocation();
8686 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8687 // Evaluate the call as a constant initializer, to allow the construction
8688 // of objects of non-literal types.
8689 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
8690 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
8692 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
8693 Args, FD->getBody(), Info, Scratch);
8695 return Diags.empty();