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 rules only, at the moment), or, if folding failed too,
27 // 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/CharUnits.h"
39 #include "clang/AST/RecordLayout.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TypeLoc.h"
42 #include "clang/AST/ASTDiagnostic.h"
43 #include "clang/AST/Expr.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
50 using namespace clang;
54 static bool IsGlobalLValue(APValue::LValueBase B);
58 struct CallStackFrame;
61 static QualType getType(APValue::LValueBase B) {
62 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return B.get<const Expr*>()->getType();
68 /// Get an LValue path entry, which is known to not be an array index, as a
69 /// field or base class.
71 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
72 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
79 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
80 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
84 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
85 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
87 /// Determine whether this LValue path entry for a base class names a virtual
89 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
90 return getAsBaseOrMember(E).getInt();
93 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
112 MostDerivedLength = I + 1;
113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
116 MostDerivedLength = I + 1;
118 // Path[I] describes a base class.
122 return MostDerivedLength;
125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
128 CSK_This, CSK_Real, CSK_Imag
131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
141 /// The length of the path to the most-derived object of which this is a
143 unsigned MostDerivedPathLength : 30;
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
152 typedef APValue::LValuePathEntry PathEntry;
154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
157 SubobjectDesignator() : Invalid(true) {}
159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
197 return !isOnePastTheEnd();
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
206 Entry.ArrayIndex = 0;
207 Entries.push_back(Entry);
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
214 /// Update this designator to refer to the given base or member of this
216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
220 Entries.push_back(Entry);
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
242 /// Add N to the address of this subobject.
243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
246 Entries.back().ArrayIndex += N;
247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
271 /// Parent - The caller of this stack frame.
272 CallStackFrame *Caller;
274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
280 /// Index - The call index of this call.
283 /// This - The binding for the this pointer in this call, if any.
286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
288 const APValue *Arguments;
290 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
291 typedef MapTy::const_iterator temp_iterator;
292 /// Temporaries - Temporary lvalues materialized within this stack frame.
295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
296 const FunctionDecl *Callee, const LValue *This,
297 const APValue *Arguments);
301 /// A partial diagnostic which we might know in advance that we are not going
303 class OptionalDiagnostic {
304 PartialDiagnostic *Diag;
307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
310 OptionalDiagnostic &operator<<(const T &v) {
316 OptionalDiagnostic &operator<<(const APSInt &I) {
318 llvm::SmallVector<char, 32> Buffer;
320 *Diag << StringRef(Buffer.data(), Buffer.size());
325 OptionalDiagnostic &operator<<(const APFloat &F) {
327 llvm::SmallVector<char, 32> Buffer;
329 *Diag << StringRef(Buffer.data(), Buffer.size());
335 /// EvalInfo - This is a private struct used by the evaluator to capture
336 /// information about a subexpression as it is folded. It retains information
337 /// about the AST context, but also maintains information about the folded
340 /// If an expression could be evaluated, it is still possible it is not a C
341 /// "integer constant expression" or constant expression. If not, this struct
342 /// captures information about how and why not.
344 /// One bit of information passed *into* the request for constant folding
345 /// indicates whether the subexpression is "evaluated" or not according to C
346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
347 /// evaluate the expression regardless of what the RHS is, but C only allows
348 /// certain things in certain situations.
352 /// EvalStatus - Contains information about the evaluation.
353 Expr::EvalStatus &EvalStatus;
355 /// CurrentCall - The top of the constexpr call stack.
356 CallStackFrame *CurrentCall;
358 /// CallStackDepth - The number of calls in the call stack right now.
359 unsigned CallStackDepth;
361 /// NextCallIndex - The next call index to assign.
362 unsigned NextCallIndex;
364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
365 /// OpaqueValues - Values used as the common expression in a
366 /// BinaryConditionalOperator.
369 /// BottomFrame - The frame in which evaluation started. This must be
370 /// initialized after CurrentCall and CallStackDepth.
371 CallStackFrame BottomFrame;
373 /// EvaluatingDecl - This is the declaration whose initializer is being
374 /// evaluated, if any.
375 const VarDecl *EvaluatingDecl;
377 /// EvaluatingDeclValue - This is the value being constructed for the
378 /// declaration whose initializer is being evaluated, if any.
379 APValue *EvaluatingDeclValue;
381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
382 /// notes attached to it will also be stored, otherwise they will not be.
383 bool HasActiveDiagnostic;
385 /// CheckingPotentialConstantExpression - Are we checking whether the
386 /// expression is a potential constant expression? If so, some diagnostics
388 bool CheckingPotentialConstantExpression;
390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
392 CallStackDepth(0), NextCallIndex(1),
393 BottomFrame(*this, SourceLocation(), 0, 0, 0),
394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
395 CheckingPotentialConstantExpression(false) {}
397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
398 MapTy::const_iterator i = OpaqueValues.find(e);
399 if (i == OpaqueValues.end()) return 0;
403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
405 EvaluatingDeclValue = &Value;
408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
410 bool CheckCallLimit(SourceLocation Loc) {
411 // Don't perform any constexpr calls (other than the call we're checking)
412 // when checking a potential constant expression.
413 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
415 if (NextCallIndex == 0) {
416 // NextCallIndex has wrapped around.
417 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
423 << getLangOpts().ConstexprCallDepth;
427 CallStackFrame *getCallFrame(unsigned CallIndex) {
428 assert(CallIndex && "no call index in getCallFrame");
429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
430 // be null in this loop.
431 CallStackFrame *Frame = CurrentCall;
432 while (Frame->Index > CallIndex)
433 Frame = Frame->Caller;
434 return (Frame->Index == CallIndex) ? Frame : 0;
438 /// Add a diagnostic to the diagnostics list.
439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
442 return EvalStatus.Diag->back().second;
445 /// Add notes containing a call stack to the current point of evaluation.
446 void addCallStack(unsigned Limit);
449 /// Diagnose that the evaluation cannot be folded.
450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
451 = diag::note_invalid_subexpr_in_const_expr,
452 unsigned ExtraNotes = 0) {
453 // If we have a prior diagnostic, it will be noting that the expression
454 // isn't a constant expression. This diagnostic is more important.
455 // FIXME: We might want to show both diagnostics to the user.
456 if (EvalStatus.Diag) {
457 unsigned CallStackNotes = CallStackDepth - 1;
458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
460 CallStackNotes = std::min(CallStackNotes, Limit + 1);
461 if (CheckingPotentialConstantExpression)
464 HasActiveDiagnostic = true;
465 EvalStatus.Diag->clear();
466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
467 addDiag(Loc, DiagId);
468 if (!CheckingPotentialConstantExpression)
470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
477 = diag::note_invalid_subexpr_in_const_expr,
478 unsigned ExtraNotes = 0) {
480 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
481 HasActiveDiagnostic = false;
482 return OptionalDiagnostic();
485 /// Diagnose that the evaluation does not produce a C++11 core constant
487 template<typename LocArg>
488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 // Don't override a previous diagnostic.
492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
496 return Diag(Loc, DiagId, ExtraNotes);
499 /// Add a note to a prior diagnostic.
500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
501 if (!HasActiveDiagnostic)
502 return OptionalDiagnostic();
503 return OptionalDiagnostic(&addDiag(Loc, DiagId));
506 /// Add a stack of notes to a prior diagnostic.
507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
508 if (HasActiveDiagnostic) {
509 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
510 Diags.begin(), Diags.end());
514 /// Should we continue evaluation as much as possible after encountering a
515 /// construct which can't be folded?
516 bool keepEvaluatingAfterFailure() {
517 return CheckingPotentialConstantExpression &&
518 EvalStatus.Diag && EvalStatus.Diag->empty();
522 /// Object used to treat all foldable expressions as constant expressions.
523 struct FoldConstant {
526 explicit FoldConstant(EvalInfo &Info)
527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects) {
530 // Treat the value we've computed since this object was created as constant.
531 void Fold(EvalInfo &Info) {
532 if (Enabled && !Info.EvalStatus.Diag->empty() &&
533 !Info.EvalStatus.HasSideEffects)
534 Info.EvalStatus.Diag->clear();
538 /// RAII object used to suppress diagnostics and side-effects from a
539 /// speculative evaluation.
540 class SpeculativeEvaluationRAII {
542 Expr::EvalStatus Old;
545 SpeculativeEvaluationRAII(EvalInfo &Info,
546 llvm::SmallVectorImpl<PartialDiagnosticAt>
548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
557 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
561 if (isOnePastTheEnd()) {
562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
570 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
573 Info.CCEDiag(E, diag::note_constexpr_array_index)
574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
577 Info.CCEDiag(E, diag::note_constexpr_array_index)
578 << static_cast<int>(N) << /*non-array*/ 1;
582 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
584 const APValue *Arguments)
585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
591 CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
597 /// Produce a string describing the given constexpr call.
598 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
605 Out << *Frame->Callee << '(';
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
609 if (ArgIndex > (unsigned)IsMemberCall)
612 const ParmVarDecl *Param = *I;
613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
623 void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
646 llvm::SmallVector<char, 128> Buffer;
647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
654 struct ComplexValue {
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
674 void moveInto(APValue &v) const {
675 if (isComplexFloat())
676 v = APValue(FloatReal, FloatImag);
678 v = APValue(IntReal, IntImag);
680 void setFrom(const APValue &v) {
681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
695 APValue::LValueBase Base;
698 SubobjectDesignator Designator;
700 const APValue::LValueBase getLValueBase() const { return Base; }
701 CharUnits &getLValueOffset() { return Offset; }
702 const CharUnits &getLValueOffset() const { return Offset; }
703 unsigned getLValueCallIndex() const { return CallIndex; }
704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
714 void setFrom(ASTContext &Ctx, const APValue &V) {
715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
718 CallIndex = V.getLValueCallIndex();
719 Designator = SubobjectDesignator(Ctx, V);
722 void set(APValue::LValueBase B, unsigned I = 0) {
724 Offset = CharUnits::Zero();
726 Designator = SubobjectDesignator(getType(B));
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
738 Designator.setInvalid();
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
749 if (!Info.getLangOpts().CPlusPlus0x)
750 Designator.setInvalid();
751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
797 void setFrom(const APValue &V) {
798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
814 /// Perform a cast towards the class of the Decl (either up or down the
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
843 if (!castBack(Derived))
846 DeclAndIsDerivedMember.setInt(false);
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
859 return castBack(Base);
863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
869 return LHS.Path == RHS.Path;
872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
880 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
881 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
885 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
887 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
889 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
890 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
891 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
893 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
894 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
896 //===----------------------------------------------------------------------===//
898 //===----------------------------------------------------------------------===//
900 /// Should this call expression be treated as a string literal?
901 static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
907 static bool IsGlobalLValue(APValue::LValueBase B) {
908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
911 // ... a null pointer value, or a prvalue core constant expression of type
915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
923 const Expr *E = B.get<const Expr*>();
924 switch (E->getStmtClass()) {
927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
936 case Expr::CXXTypeidExprClass:
937 case Expr::CXXUuidofExprClass:
939 case Expr::CallExprClass:
940 return IsStringLiteralCall(cast<CallExpr>(E));
941 // For GCC compatibility, &&label has static storage duration.
942 case Expr::AddrLabelExprClass:
944 // A Block literal expression may be used as the initialization value for
945 // Block variables at global or local static scope.
946 case Expr::BlockExprClass:
947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
948 case Expr::ImplicitValueInitExprClass:
950 // We can never form an lvalue with an implicit value initialization as its
951 // base through expression evaluation, so these only appear in one case: the
952 // implicit variable declaration we invent when checking whether a constexpr
953 // constructor can produce a constant expression. We must assume that such
954 // an expression might be a global lvalue.
959 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
960 assert(Base && "no location for a null lvalue");
961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
963 Info.Note(VD->getLocation(), diag::note_declared_at);
965 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
966 diag::note_constexpr_temporary_here);
969 /// Check that this reference or pointer core constant expression is a valid
970 /// value for an address or reference constant expression. Return true if we
971 /// can fold this expression, whether or not it's a constant expression.
972 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
973 QualType Type, const LValue &LVal) {
974 bool IsReferenceType = Type->isReferenceType();
976 APValue::LValueBase Base = LVal.getLValueBase();
977 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
979 // Check that the object is a global. Note that the fake 'this' object we
980 // manufacture when checking potential constant expressions is conservatively
981 // assumed to be global here.
982 if (!IsGlobalLValue(Base)) {
983 if (Info.getLangOpts().CPlusPlus0x) {
984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
985 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
986 << IsReferenceType << !Designator.Entries.empty()
988 NoteLValueLocation(Info, Base);
992 // Don't allow references to temporaries to escape.
995 assert((Info.CheckingPotentialConstantExpression ||
996 LVal.getLValueCallIndex() == 0) &&
997 "have call index for global lvalue");
999 // Allow address constant expressions to be past-the-end pointers. This is
1000 // an extension: the standard requires them to point to an object.
1001 if (!IsReferenceType)
1004 // A reference constant expression must refer to an object.
1006 // FIXME: diagnostic
1011 // Does this refer one past the end of some object?
1012 if (Designator.isOnePastTheEnd()) {
1013 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1014 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1015 << !Designator.Entries.empty() << !!VD << VD;
1016 NoteLValueLocation(Info, Base);
1022 /// Check that this core constant expression is of literal type, and if not,
1023 /// produce an appropriate diagnostic.
1024 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1025 if (!E->isRValue() || E->getType()->isLiteralType())
1028 // Prvalue constant expressions must be of literal types.
1029 if (Info.getLangOpts().CPlusPlus0x)
1030 Info.Diag(E, diag::note_constexpr_nonliteral)
1033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1037 /// Check that this core constant expression value is a valid value for a
1038 /// constant expression. If not, report an appropriate diagnostic. Does not
1039 /// check that the expression is of literal type.
1040 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1041 QualType Type, const APValue &Value) {
1042 // Core issue 1454: For a literal constant expression of array or class type,
1043 // each subobject of its value shall have been initialized by a constant
1045 if (Value.isArray()) {
1046 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1047 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1048 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1049 Value.getArrayInitializedElt(I)))
1052 if (!Value.hasArrayFiller())
1054 return CheckConstantExpression(Info, DiagLoc, EltTy,
1055 Value.getArrayFiller());
1057 if (Value.isUnion() && Value.getUnionField()) {
1058 return CheckConstantExpression(Info, DiagLoc,
1059 Value.getUnionField()->getType(),
1060 Value.getUnionValue());
1062 if (Value.isStruct()) {
1063 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1064 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1065 unsigned BaseIndex = 0;
1066 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1067 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1068 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1069 Value.getStructBase(BaseIndex)))
1073 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1075 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1076 Value.getStructField((*I)->getFieldIndex())))
1081 if (Value.isLValue()) {
1083 LVal.setFrom(Info.Ctx, Value);
1084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1087 // Everything else is fine.
1091 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1092 return LVal.Base.dyn_cast<const ValueDecl*>();
1095 static bool IsLiteralLValue(const LValue &Value) {
1096 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
1099 static bool IsWeakLValue(const LValue &Value) {
1100 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1101 return Decl && Decl->isWeak();
1104 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1105 // A null base expression indicates a null pointer. These are always
1106 // evaluatable, and they are false unless the offset is zero.
1107 if (!Value.getLValueBase()) {
1108 Result = !Value.getLValueOffset().isZero();
1112 // We have a non-null base. These are generally known to be true, but if it's
1113 // a weak declaration it can be null at runtime.
1115 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1116 return !Decl || !Decl->isWeak();
1119 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1120 switch (Val.getKind()) {
1121 case APValue::Uninitialized:
1124 Result = Val.getInt().getBoolValue();
1126 case APValue::Float:
1127 Result = !Val.getFloat().isZero();
1129 case APValue::ComplexInt:
1130 Result = Val.getComplexIntReal().getBoolValue() ||
1131 Val.getComplexIntImag().getBoolValue();
1133 case APValue::ComplexFloat:
1134 Result = !Val.getComplexFloatReal().isZero() ||
1135 !Val.getComplexFloatImag().isZero();
1137 case APValue::LValue:
1138 return EvalPointerValueAsBool(Val, Result);
1139 case APValue::MemberPointer:
1140 Result = Val.getMemberPointerDecl();
1142 case APValue::Vector:
1143 case APValue::Array:
1144 case APValue::Struct:
1145 case APValue::Union:
1146 case APValue::AddrLabelDiff:
1150 llvm_unreachable("unknown APValue kind");
1153 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1155 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1157 if (!Evaluate(Val, Info, E))
1159 return HandleConversionToBool(Val, Result);
1162 template<typename T>
1163 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1164 const T &SrcValue, QualType DestType) {
1165 Info.Diag(E, diag::note_constexpr_overflow)
1166 << SrcValue << DestType;
1170 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1171 QualType SrcType, const APFloat &Value,
1172 QualType DestType, APSInt &Result) {
1173 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1174 // Determine whether we are converting to unsigned or signed.
1175 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1177 Result = APSInt(DestWidth, !DestSigned);
1179 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1180 & APFloat::opInvalidOp)
1181 return HandleOverflow(Info, E, Value, DestType);
1185 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1186 QualType SrcType, QualType DestType,
1188 APFloat Value = Result;
1190 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1191 APFloat::rmNearestTiesToEven, &ignored)
1192 & APFloat::opOverflow)
1193 return HandleOverflow(Info, E, Value, DestType);
1197 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1198 QualType DestType, QualType SrcType,
1200 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1201 APSInt Result = Value;
1202 // Figure out if this is a truncate, extend or noop cast.
1203 // If the input is signed, do a sign extend, noop, or truncate.
1204 Result = Result.extOrTrunc(DestWidth);
1205 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1209 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1210 QualType SrcType, const APSInt &Value,
1211 QualType DestType, APFloat &Result) {
1212 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1213 if (Result.convertFromAPInt(Value, Value.isSigned(),
1214 APFloat::rmNearestTiesToEven)
1215 & APFloat::opOverflow)
1216 return HandleOverflow(Info, E, Value, DestType);
1220 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1223 if (!Evaluate(SVal, Info, E))
1226 Res = SVal.getInt();
1229 if (SVal.isFloat()) {
1230 Res = SVal.getFloat().bitcastToAPInt();
1233 if (SVal.isVector()) {
1234 QualType VecTy = E->getType();
1235 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1236 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1237 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1238 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1239 Res = llvm::APInt::getNullValue(VecSize);
1240 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1241 APValue &Elt = SVal.getVectorElt(i);
1242 llvm::APInt EltAsInt;
1244 EltAsInt = Elt.getInt();
1245 } else if (Elt.isFloat()) {
1246 EltAsInt = Elt.getFloat().bitcastToAPInt();
1248 // Don't try to handle vectors of anything other than int or float
1249 // (not sure if it's possible to hit this case).
1250 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1253 unsigned BaseEltSize = EltAsInt.getBitWidth();
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1257 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1261 // Give up if the input isn't an int, float, or vector. For example, we
1262 // reject "(v4i16)(intptr_t)&a".
1263 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1267 /// Cast an lvalue referring to a base subobject to a derived class, by
1268 /// truncating the lvalue's path to the given length.
1269 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1270 const RecordDecl *TruncatedType,
1271 unsigned TruncatedElements) {
1272 SubobjectDesignator &D = Result.Designator;
1274 // Check we actually point to a derived class object.
1275 if (TruncatedElements == D.Entries.size())
1277 assert(TruncatedElements >= D.MostDerivedPathLength &&
1278 "not casting to a derived class");
1279 if (!Result.checkSubobject(Info, E, CSK_Derived))
1282 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1283 const RecordDecl *RD = TruncatedType;
1284 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1285 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1286 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1287 if (isVirtualBaseClass(D.Entries[I]))
1288 Result.Offset -= Layout.getVBaseClassOffset(Base);
1290 Result.Offset -= Layout.getBaseClassOffset(Base);
1293 D.Entries.resize(TruncatedElements);
1297 static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1298 const CXXRecordDecl *Derived,
1299 const CXXRecordDecl *Base,
1300 const ASTRecordLayout *RL = 0) {
1301 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1302 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1303 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1306 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1307 const CXXRecordDecl *DerivedDecl,
1308 const CXXBaseSpecifier *Base) {
1309 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1311 if (!Base->isVirtual()) {
1312 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1316 SubobjectDesignator &D = Obj.Designator;
1320 // Extract most-derived object and corresponding type.
1321 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1322 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1325 // Find the virtual base class.
1326 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1327 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1328 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1332 /// Update LVal to refer to the given field, which must be a member of the type
1333 /// currently described by LVal.
1334 static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1335 const FieldDecl *FD,
1336 const ASTRecordLayout *RL = 0) {
1338 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1340 unsigned I = FD->getFieldIndex();
1341 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1342 LVal.addDecl(Info, E, FD);
1345 /// Update LVal to refer to the given indirect field.
1346 static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1348 const IndirectFieldDecl *IFD) {
1349 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1350 CE = IFD->chain_end(); C != CE; ++C)
1351 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1354 /// Get the size of the given type in char units.
1355 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1356 QualType Type, CharUnits &Size) {
1357 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1359 if (Type->isVoidType() || Type->isFunctionType()) {
1360 Size = CharUnits::One();
1364 if (!Type->isConstantSizeType()) {
1365 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1366 // FIXME: Better diagnostic.
1371 Size = Info.Ctx.getTypeSizeInChars(Type);
1375 /// Update a pointer value to model pointer arithmetic.
1376 /// \param Info - Information about the ongoing evaluation.
1377 /// \param E - The expression being evaluated, for diagnostic purposes.
1378 /// \param LVal - The pointer value to be updated.
1379 /// \param EltTy - The pointee type represented by LVal.
1380 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1381 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1382 LValue &LVal, QualType EltTy,
1383 int64_t Adjustment) {
1384 CharUnits SizeOfPointee;
1385 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1388 // Compute the new offset in the appropriate width.
1389 LVal.Offset += Adjustment * SizeOfPointee;
1390 LVal.adjustIndex(Info, E, Adjustment);
1394 /// Update an lvalue to refer to a component of a complex number.
1395 /// \param Info - Information about the ongoing evaluation.
1396 /// \param LVal - The lvalue to be updated.
1397 /// \param EltTy - The complex number's component type.
1398 /// \param Imag - False for the real component, true for the imaginary.
1399 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1400 LValue &LVal, QualType EltTy,
1403 CharUnits SizeOfComponent;
1404 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1406 LVal.Offset += SizeOfComponent;
1408 LVal.addComplex(Info, E, EltTy, Imag);
1412 /// Try to evaluate the initializer for a variable declaration.
1413 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1415 CallStackFrame *Frame, APValue &Result) {
1416 // If this is a parameter to an active constexpr function call, perform
1417 // argument substitution.
1418 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1419 // Assume arguments of a potential constant expression are unknown
1420 // constant expressions.
1421 if (Info.CheckingPotentialConstantExpression)
1423 if (!Frame || !Frame->Arguments) {
1424 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1427 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1431 // Dig out the initializer, and use the declaration which it's attached to.
1432 const Expr *Init = VD->getAnyInitializer(VD);
1433 if (!Init || Init->isValueDependent()) {
1434 // If we're checking a potential constant expression, the variable could be
1435 // initialized later.
1436 if (!Info.CheckingPotentialConstantExpression)
1437 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1441 // If we're currently evaluating the initializer of this declaration, use that
1443 if (Info.EvaluatingDecl == VD) {
1444 Result = *Info.EvaluatingDeclValue;
1445 return !Result.isUninit();
1448 // Never evaluate the initializer of a weak variable. We can't be sure that
1449 // this is the definition which will be used.
1451 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1455 // Check that we can fold the initializer. In C++, we will have already done
1456 // this in the cases where it matters for conformance.
1457 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1458 if (!VD->evaluateValue(Notes)) {
1459 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1460 Notes.size() + 1) << VD;
1461 Info.Note(VD->getLocation(), diag::note_declared_at);
1462 Info.addNotes(Notes);
1464 } else if (!VD->checkInitIsICE()) {
1465 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1466 Notes.size() + 1) << VD;
1467 Info.Note(VD->getLocation(), diag::note_declared_at);
1468 Info.addNotes(Notes);
1471 Result = *VD->getEvaluatedValue();
1475 static bool IsConstNonVolatile(QualType T) {
1476 Qualifiers Quals = T.getQualifiers();
1477 return Quals.hasConst() && !Quals.hasVolatile();
1480 /// Get the base index of the given base class within an APValue representing
1481 /// the given derived class.
1482 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1483 const CXXRecordDecl *Base) {
1484 Base = Base->getCanonicalDecl();
1486 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1487 E = Derived->bases_end(); I != E; ++I, ++Index) {
1488 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1492 llvm_unreachable("base class missing from derived class's bases list");
1495 /// Extract the value of a character from a string literal. CharType is used to
1496 /// determine the expected signedness of the result -- a string literal used to
1497 /// initialize an array of 'signed char' or 'unsigned char' might contain chars
1498 /// of the wrong signedness.
1499 static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1500 uint64_t Index, QualType CharType) {
1501 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1502 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1503 assert(S && "unexpected string literal expression kind");
1504 assert(CharType->isIntegerType() && "unexpected character type");
1506 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1507 CharType->isUnsignedIntegerType());
1508 if (Index < S->getLength())
1509 Value = S->getCodeUnit(Index);
1513 /// Extract the designated sub-object of an rvalue.
1514 static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1515 APValue &Obj, QualType ObjType,
1516 const SubobjectDesignator &Sub, QualType SubType) {
1518 // A diagnostic will have already been produced.
1520 if (Sub.isOnePastTheEnd()) {
1521 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1522 (unsigned)diag::note_constexpr_read_past_end :
1523 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1526 if (Sub.Entries.empty())
1528 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1529 // This object might be initialized later.
1533 // Walk the designator's path to find the subobject.
1534 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1535 if (ObjType->isArrayType()) {
1536 // Next subobject is an array element.
1537 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1538 assert(CAT && "vla in literal type?");
1539 uint64_t Index = Sub.Entries[I].ArrayIndex;
1540 if (CAT->getSize().ule(Index)) {
1541 // Note, it should not be possible to form a pointer with a valid
1542 // designator which points more than one past the end of the array.
1543 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1544 (unsigned)diag::note_constexpr_read_past_end :
1545 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1548 // An array object is represented as either an Array APValue or as an
1549 // LValue which refers to a string literal.
1550 if (O->isLValue()) {
1551 assert(I == N - 1 && "extracting subobject of character?");
1552 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1553 Obj = APValue(ExtractStringLiteralCharacter(
1554 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
1556 } else if (O->getArrayInitializedElts() > Index)
1557 O = &O->getArrayInitializedElt(Index);
1559 O = &O->getArrayFiller();
1560 ObjType = CAT->getElementType();
1561 } else if (ObjType->isAnyComplexType()) {
1562 // Next subobject is a complex number.
1563 uint64_t Index = Sub.Entries[I].ArrayIndex;
1565 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1566 (unsigned)diag::note_constexpr_read_past_end :
1567 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1570 assert(I == N - 1 && "extracting subobject of scalar?");
1571 if (O->isComplexInt()) {
1572 Obj = APValue(Index ? O->getComplexIntImag()
1573 : O->getComplexIntReal());
1575 assert(O->isComplexFloat());
1576 Obj = APValue(Index ? O->getComplexFloatImag()
1577 : O->getComplexFloatReal());
1580 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1581 if (Field->isMutable()) {
1582 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
1584 Info.Note(Field->getLocation(), diag::note_declared_at);
1588 // Next subobject is a class, struct or union field.
1589 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1590 if (RD->isUnion()) {
1591 const FieldDecl *UnionField = O->getUnionField();
1593 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1594 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
1595 << Field << !UnionField << UnionField;
1598 O = &O->getUnionValue();
1600 O = &O->getStructField(Field->getFieldIndex());
1601 ObjType = Field->getType();
1603 if (ObjType.isVolatileQualified()) {
1604 if (Info.getLangOpts().CPlusPlus) {
1605 // FIXME: Include a description of the path to the volatile subobject.
1606 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
1608 Info.Note(Field->getLocation(), diag::note_declared_at);
1610 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1615 // Next subobject is a base class.
1616 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1617 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1618 O = &O->getStructBase(getBaseIndex(Derived, Base));
1619 ObjType = Info.Ctx.getRecordType(Base);
1622 if (O->isUninit()) {
1623 if (!Info.CheckingPotentialConstantExpression)
1624 Info.Diag(E, diag::note_constexpr_read_uninit);
1629 // This may look super-stupid, but it serves an important purpose: if we just
1630 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1631 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1632 // object, which is destroyed by Tmp's destructor.
1639 /// Find the position where two subobject designators diverge, or equivalently
1640 /// the length of the common initial subsequence.
1641 static unsigned FindDesignatorMismatch(QualType ObjType,
1642 const SubobjectDesignator &A,
1643 const SubobjectDesignator &B,
1644 bool &WasArrayIndex) {
1645 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1646 for (/**/; I != N; ++I) {
1647 if (!ObjType.isNull() &&
1648 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
1649 // Next subobject is an array element.
1650 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1651 WasArrayIndex = true;
1654 if (ObjType->isAnyComplexType())
1655 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1657 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1659 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1660 WasArrayIndex = false;
1663 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1664 // Next subobject is a field.
1665 ObjType = FD->getType();
1667 // Next subobject is a base class.
1668 ObjType = QualType();
1671 WasArrayIndex = false;
1675 /// Determine whether the given subobject designators refer to elements of the
1676 /// same array object.
1677 static bool AreElementsOfSameArray(QualType ObjType,
1678 const SubobjectDesignator &A,
1679 const SubobjectDesignator &B) {
1680 if (A.Entries.size() != B.Entries.size())
1683 bool IsArray = A.MostDerivedArraySize != 0;
1684 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1685 // A is a subobject of the array element.
1688 // If A (and B) designates an array element, the last entry will be the array
1689 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1690 // of length 1' case, and the entire path must match.
1692 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1693 return CommonLength >= A.Entries.size() - IsArray;
1696 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1697 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1698 /// for looking up the glvalue referred to by an entity of reference type.
1700 /// \param Info - Information about the ongoing evaluation.
1701 /// \param Conv - The expression for which we are performing the conversion.
1702 /// Used for diagnostics.
1703 /// \param Type - The type we expect this conversion to produce, before
1704 /// stripping cv-qualifiers in the case of a non-clas type.
1705 /// \param LVal - The glvalue on which we are attempting to perform this action.
1706 /// \param RVal - The produced value will be placed here.
1707 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1709 const LValue &LVal, APValue &RVal) {
1710 if (LVal.Designator.Invalid)
1711 // A diagnostic will have already been produced.
1714 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1717 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1718 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1722 CallStackFrame *Frame = 0;
1723 if (LVal.CallIndex) {
1724 Frame = Info.getCallFrame(LVal.CallIndex);
1726 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1727 NoteLValueLocation(Info, LVal.Base);
1732 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1733 // is not a constant expression (even if the object is non-volatile). We also
1734 // apply this rule to C++98, in order to conform to the expected 'volatile'
1736 if (Type.isVolatileQualified()) {
1737 if (Info.getLangOpts().CPlusPlus)
1738 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
1744 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1745 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1746 // In C++11, constexpr, non-volatile variables initialized with constant
1747 // expressions are constant expressions too. Inside constexpr functions,
1748 // parameters are constant expressions even if they're non-const.
1749 // In C, such things can also be folded, although they are not ICEs.
1750 const VarDecl *VD = dyn_cast<VarDecl>(D);
1752 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1755 if (!VD || VD->isInvalidDecl()) {
1760 // DR1313: If the object is volatile-qualified but the glvalue was not,
1761 // behavior is undefined so the result is not a constant expression.
1762 QualType VT = VD->getType();
1763 if (VT.isVolatileQualified()) {
1764 if (Info.getLangOpts().CPlusPlus) {
1765 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1766 Info.Note(VD->getLocation(), diag::note_declared_at);
1773 if (!isa<ParmVarDecl>(VD)) {
1774 if (VD->isConstexpr()) {
1775 // OK, we can read this variable.
1776 } else if (VT->isIntegralOrEnumerationType()) {
1777 if (!VT.isConstQualified()) {
1778 if (Info.getLangOpts().CPlusPlus) {
1779 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1780 Info.Note(VD->getLocation(), diag::note_declared_at);
1786 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1787 // We support folding of const floating-point types, in order to make
1788 // static const data members of such types (supported as an extension)
1790 if (Info.getLangOpts().CPlusPlus0x) {
1791 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1792 Info.Note(VD->getLocation(), diag::note_declared_at);
1797 // FIXME: Allow folding of values of any literal type in all languages.
1798 if (Info.getLangOpts().CPlusPlus0x) {
1799 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1800 Info.Note(VD->getLocation(), diag::note_declared_at);
1808 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1811 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1812 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1814 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1815 // conversion. This happens when the declaration and the lvalue should be
1816 // considered synonymous, for instance when initializing an array of char
1817 // from a string literal. Continue as if the initializer lvalue was the
1818 // value we were originally given.
1819 assert(RVal.getLValueOffset().isZero() &&
1820 "offset for lvalue init of non-reference");
1821 Base = RVal.getLValueBase().get<const Expr*>();
1823 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1824 Frame = Info.getCallFrame(CallIndex);
1826 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1827 NoteLValueLocation(Info, RVal.getLValueBase());
1835 // Volatile temporary objects cannot be read in constant expressions.
1836 if (Base->getType().isVolatileQualified()) {
1837 if (Info.getLangOpts().CPlusPlus) {
1838 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1839 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1847 // If this is a temporary expression with a nontrivial initializer, grab the
1848 // value from the relevant stack frame.
1849 RVal = Frame->Temporaries[Base];
1850 } else if (const CompoundLiteralExpr *CLE
1851 = dyn_cast<CompoundLiteralExpr>(Base)) {
1852 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1853 // initializer until now for such expressions. Such an expression can't be
1854 // an ICE in C, so this only matters for fold.
1855 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1856 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1858 } else if (isa<StringLiteral>(Base)) {
1859 // We represent a string literal array as an lvalue pointing at the
1860 // corresponding expression, rather than building an array of chars.
1861 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1862 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
1864 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1868 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1872 /// Build an lvalue for the object argument of a member function call.
1873 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1875 if (Object->getType()->isPointerType())
1876 return EvaluatePointer(Object, This, Info);
1878 if (Object->isGLValue())
1879 return EvaluateLValue(Object, This, Info);
1881 if (Object->getType()->isLiteralType())
1882 return EvaluateTemporary(Object, This, Info);
1887 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
1888 /// lvalue referring to the result.
1890 /// \param Info - Information about the ongoing evaluation.
1891 /// \param BO - The member pointer access operation.
1892 /// \param LV - Filled in with a reference to the resulting object.
1893 /// \param IncludeMember - Specifies whether the member itself is included in
1894 /// the resulting LValue subobject designator. This is not possible when
1895 /// creating a bound member function.
1896 /// \return The field or method declaration to which the member pointer refers,
1897 /// or 0 if evaluation fails.
1898 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1899 const BinaryOperator *BO,
1901 bool IncludeMember = true) {
1902 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1904 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1905 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1909 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1912 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1913 // member value, the behavior is undefined.
1914 if (!MemPtr.getDecl())
1920 if (MemPtr.isDerivedMember()) {
1921 // This is a member of some derived class. Truncate LV appropriately.
1922 // The end of the derived-to-base path for the base object must match the
1923 // derived-to-base path for the member pointer.
1924 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1925 LV.Designator.Entries.size())
1927 unsigned PathLengthToMember =
1928 LV.Designator.Entries.size() - MemPtr.Path.size();
1929 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1930 const CXXRecordDecl *LVDecl = getAsBaseClass(
1931 LV.Designator.Entries[PathLengthToMember + I]);
1932 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1933 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1937 // Truncate the lvalue to the appropriate derived class.
1938 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1939 PathLengthToMember))
1941 } else if (!MemPtr.Path.empty()) {
1942 // Extend the LValue path with the member pointer's path.
1943 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1944 MemPtr.Path.size() + IncludeMember);
1946 // Walk down to the appropriate base class.
1947 QualType LVType = BO->getLHS()->getType();
1948 if (const PointerType *PT = LVType->getAs<PointerType>())
1949 LVType = PT->getPointeeType();
1950 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1951 assert(RD && "member pointer access on non-class-type expression");
1952 // The first class in the path is that of the lvalue.
1953 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1954 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1955 HandleLValueDirectBase(Info, BO, LV, RD, Base);
1958 // Finally cast to the class containing the member.
1959 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
1962 // Add the member. Note that we cannot build bound member functions here.
1963 if (IncludeMember) {
1964 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1965 HandleLValueMember(Info, BO, LV, FD);
1966 else if (const IndirectFieldDecl *IFD =
1967 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1968 HandleLValueIndirectMember(Info, BO, LV, IFD);
1970 llvm_unreachable("can't construct reference to bound member function");
1973 return MemPtr.getDecl();
1976 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1977 /// the provided lvalue, which currently refers to the base object.
1978 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1980 SubobjectDesignator &D = Result.Designator;
1981 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1984 QualType TargetQT = E->getType();
1985 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1986 TargetQT = PT->getPointeeType();
1988 // Check this cast lands within the final derived-to-base subobject path.
1989 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1990 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
1991 << D.MostDerivedType << TargetQT;
1995 // Check the type of the final cast. We don't need to check the path,
1996 // since a cast can only be formed if the path is unique.
1997 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1998 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1999 const CXXRecordDecl *FinalType;
2000 if (NewEntriesSize == D.MostDerivedPathLength)
2001 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2003 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
2004 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2005 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2006 << D.MostDerivedType << TargetQT;
2010 // Truncate the lvalue to the appropriate derived class.
2011 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
2015 enum EvalStmtResult {
2016 /// Evaluation failed.
2018 /// Hit a 'return' statement.
2020 /// Evaluation succeeded.
2025 // Evaluate a statement.
2026 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2028 switch (S->getStmtClass()) {
2032 case Stmt::NullStmtClass:
2033 case Stmt::DeclStmtClass:
2034 return ESR_Succeeded;
2036 case Stmt::ReturnStmtClass: {
2037 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
2038 if (!Evaluate(Result, Info, RetExpr))
2040 return ESR_Returned;
2043 case Stmt::CompoundStmtClass: {
2044 const CompoundStmt *CS = cast<CompoundStmt>(S);
2045 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2046 BE = CS->body_end(); BI != BE; ++BI) {
2047 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2048 if (ESR != ESR_Succeeded)
2051 return ESR_Succeeded;
2056 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2057 /// default constructor. If so, we'll fold it whether or not it's marked as
2058 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
2059 /// so we need special handling.
2060 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
2061 const CXXConstructorDecl *CD,
2062 bool IsValueInitialization) {
2063 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2066 // Value-initialization does not call a trivial default constructor, so such a
2067 // call is a core constant expression whether or not the constructor is
2069 if (!CD->isConstexpr() && !IsValueInitialization) {
2070 if (Info.getLangOpts().CPlusPlus0x) {
2071 // FIXME: If DiagDecl is an implicitly-declared special member function,
2072 // we should be much more explicit about why it's not constexpr.
2073 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2074 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2075 Info.Note(CD->getLocation(), diag::note_declared_at);
2077 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2083 /// CheckConstexprFunction - Check that a function can be called in a constant
2085 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2086 const FunctionDecl *Declaration,
2087 const FunctionDecl *Definition) {
2088 // Potential constant expressions can contain calls to declared, but not yet
2089 // defined, constexpr functions.
2090 if (Info.CheckingPotentialConstantExpression && !Definition &&
2091 Declaration->isConstexpr())
2094 // Can we evaluate this function call?
2095 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2098 if (Info.getLangOpts().CPlusPlus0x) {
2099 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
2100 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2101 // should be much more explicit about why it's not constexpr.
2102 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2103 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2105 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2107 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2113 typedef SmallVector<APValue, 8> ArgVector;
2116 /// EvaluateArgs - Evaluate the arguments to a function call.
2117 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2119 bool Success = true;
2120 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
2122 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2123 // If we're checking for a potential constant expression, evaluate all
2124 // initializers even if some of them fail.
2125 if (!Info.keepEvaluatingAfterFailure())
2133 /// Evaluate a function call.
2134 static bool HandleFunctionCall(SourceLocation CallLoc,
2135 const FunctionDecl *Callee, const LValue *This,
2136 ArrayRef<const Expr*> Args, const Stmt *Body,
2137 EvalInfo &Info, APValue &Result) {
2138 ArgVector ArgValues(Args.size());
2139 if (!EvaluateArgs(Args, ArgValues, Info))
2142 if (!Info.CheckCallLimit(CallLoc))
2145 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2146 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2149 /// Evaluate a constructor call.
2150 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2151 ArrayRef<const Expr*> Args,
2152 const CXXConstructorDecl *Definition,
2153 EvalInfo &Info, APValue &Result) {
2154 ArgVector ArgValues(Args.size());
2155 if (!EvaluateArgs(Args, ArgValues, Info))
2158 if (!Info.CheckCallLimit(CallLoc))
2161 const CXXRecordDecl *RD = Definition->getParent();
2162 if (RD->getNumVBases()) {
2163 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2167 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2169 // If it's a delegating constructor, just delegate.
2170 if (Definition->isDelegatingConstructor()) {
2171 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2172 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
2175 // For a trivial copy or move constructor, perform an APValue copy. This is
2176 // essential for unions, where the operations performed by the constructor
2177 // cannot be represented by ctor-initializers.
2178 if (Definition->isDefaulted() &&
2179 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2180 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
2182 RHS.setFrom(Info.Ctx, ArgValues[0]);
2183 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2187 // Reserve space for the struct members.
2188 if (!RD->isUnion() && Result.isUninit())
2189 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2190 std::distance(RD->field_begin(), RD->field_end()));
2192 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2194 bool Success = true;
2195 unsigned BasesSeen = 0;
2197 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2199 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2200 E = Definition->init_end(); I != E; ++I) {
2201 LValue Subobject = This;
2202 APValue *Value = &Result;
2204 // Determine the subobject to initialize.
2205 if ((*I)->isBaseInitializer()) {
2206 QualType BaseType((*I)->getBaseClass(), 0);
2208 // Non-virtual base classes are initialized in the order in the class
2209 // definition. We have already checked for virtual base classes.
2210 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2211 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2212 "base class initializers not in expected order");
2215 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2216 BaseType->getAsCXXRecordDecl(), &Layout);
2217 Value = &Result.getStructBase(BasesSeen++);
2218 } else if (FieldDecl *FD = (*I)->getMember()) {
2219 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
2220 if (RD->isUnion()) {
2221 Result = APValue(FD);
2222 Value = &Result.getUnionValue();
2224 Value = &Result.getStructField(FD->getFieldIndex());
2226 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2227 // Walk the indirect field decl's chain to find the object to initialize,
2228 // and make sure we've initialized every step along it.
2229 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2230 CE = IFD->chain_end();
2232 FieldDecl *FD = cast<FieldDecl>(*C);
2233 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2234 // Switch the union field if it differs. This happens if we had
2235 // preceding zero-initialization, and we're now initializing a union
2236 // subobject other than the first.
2237 // FIXME: In this case, the values of the other subobjects are
2238 // specified, since zero-initialization sets all padding bits to zero.
2239 if (Value->isUninit() ||
2240 (Value->isUnion() && Value->getUnionField() != FD)) {
2242 *Value = APValue(FD);
2244 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2245 std::distance(CD->field_begin(), CD->field_end()));
2247 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
2249 Value = &Value->getUnionValue();
2251 Value = &Value->getStructField(FD->getFieldIndex());
2254 llvm_unreachable("unknown base initializer kind");
2257 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2258 (*I)->isBaseInitializer()
2259 ? CCEK_Constant : CCEK_MemberInit)) {
2260 // If we're checking for a potential constant expression, evaluate all
2261 // initializers even if some of them fail.
2262 if (!Info.keepEvaluatingAfterFailure())
2273 : public ConstStmtVisitor<HasSideEffect, bool> {
2274 const ASTContext &Ctx;
2277 HasSideEffect(const ASTContext &C) : Ctx(C) {}
2279 // Unhandled nodes conservatively default to having side effects.
2280 bool VisitStmt(const Stmt *S) {
2284 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2285 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
2286 return Visit(E->getResultExpr());
2288 bool VisitDeclRefExpr(const DeclRefExpr *E) {
2289 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2293 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
2294 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2299 // We don't want to evaluate BlockExprs multiple times, as they generate
2301 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2302 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2303 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
2304 { return Visit(E->getInitializer()); }
2305 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2306 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2307 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2308 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2309 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2310 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
2312 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
2313 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2314 bool VisitChooseExpr(const ChooseExpr *E)
2315 { return Visit(E->getChosenSubExpr(Ctx)); }
2316 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2317 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2318 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2319 bool VisitBinaryOperator(const BinaryOperator *E)
2320 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2321 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2322 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2323 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2324 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2325 bool VisitUnaryDeref(const UnaryOperator *E) {
2326 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2328 return Visit(E->getSubExpr());
2330 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
2332 // Has side effects if any element does.
2333 bool VisitInitListExpr(const InitListExpr *E) {
2334 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2335 if (Visit(E->getInit(i))) return true;
2336 if (const Expr *filler = E->getArrayFiller())
2337 return Visit(filler);
2341 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
2344 class OpaqueValueEvaluation {
2346 OpaqueValueExpr *opaqueValue;
2349 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2351 : info(info), opaqueValue(opaqueValue) {
2353 // If evaluation fails, fail immediately.
2354 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
2355 this->opaqueValue = 0;
2360 bool hasError() const { return opaqueValue == 0; }
2362 ~OpaqueValueEvaluation() {
2363 // FIXME: For a recursive constexpr call, an outer stack frame might have
2364 // been using this opaque value too, and will now have to re-evaluate the
2365 // source expression.
2366 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2370 } // end anonymous namespace
2372 //===----------------------------------------------------------------------===//
2373 // Generic Evaluation
2374 //===----------------------------------------------------------------------===//
2377 // FIXME: RetTy is always bool. Remove it.
2378 template <class Derived, typename RetTy=bool>
2379 class ExprEvaluatorBase
2380 : public ConstStmtVisitor<Derived, RetTy> {
2382 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
2383 return static_cast<Derived*>(this)->Success(V, E);
2385 RetTy DerivedZeroInitialization(const Expr *E) {
2386 return static_cast<Derived*>(this)->ZeroInitialization(E);
2389 // Check whether a conditional operator with a non-constant condition is a
2390 // potential constant expression. If neither arm is a potential constant
2391 // expression, then the conditional operator is not either.
2392 template<typename ConditionalOperator>
2393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2394 assert(Info.CheckingPotentialConstantExpression);
2396 // Speculatively evaluate both arms.
2398 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2401 StmtVisitorTy::Visit(E->getFalseExpr());
2406 StmtVisitorTy::Visit(E->getTrueExpr());
2411 Error(E, diag::note_constexpr_conditional_never_const);
2415 template<typename ConditionalOperator>
2416 bool HandleConditionalOperator(const ConditionalOperator *E) {
2418 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2419 if (Info.CheckingPotentialConstantExpression)
2420 CheckPotentialConstantConditional(E);
2424 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2425 return StmtVisitorTy::Visit(EvalExpr);
2430 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2431 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2433 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2434 return Info.CCEDiag(E, D);
2437 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2440 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2442 EvalInfo &getEvalInfo() { return Info; }
2444 /// Report an evaluation error. This should only be called when an error is
2445 /// first discovered. When propagating an error, just return false.
2446 bool Error(const Expr *E, diag::kind D) {
2450 bool Error(const Expr *E) {
2451 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2454 RetTy VisitStmt(const Stmt *) {
2455 llvm_unreachable("Expression evaluator should not be called on stmts");
2457 RetTy VisitExpr(const Expr *E) {
2461 RetTy VisitParenExpr(const ParenExpr *E)
2462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2463 RetTy VisitUnaryExtension(const UnaryOperator *E)
2464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2465 RetTy VisitUnaryPlus(const UnaryOperator *E)
2466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2467 RetTy VisitChooseExpr(const ChooseExpr *E)
2468 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2469 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2470 { return StmtVisitorTy::Visit(E->getResultExpr()); }
2471 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2472 { return StmtVisitorTy::Visit(E->getReplacement()); }
2473 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2474 { return StmtVisitorTy::Visit(E->getExpr()); }
2475 // We cannot create any objects for which cleanups are required, so there is
2476 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2477 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2478 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2480 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2481 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2482 return static_cast<Derived*>(this)->VisitCastExpr(E);
2484 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2485 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2486 return static_cast<Derived*>(this)->VisitCastExpr(E);
2489 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2490 switch (E->getOpcode()) {
2495 VisitIgnoredValue(E->getLHS());
2496 return StmtVisitorTy::Visit(E->getRHS());
2501 if (!HandleMemberPointerAccess(Info, E, Obj))
2504 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2506 return DerivedSuccess(Result, E);
2511 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2512 // Cache the value of the common expression.
2513 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2514 if (opaque.hasError())
2517 return HandleConditionalOperator(E);
2520 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2521 bool IsBcpCall = false;
2522 // If the condition (ignoring parens) is a __builtin_constant_p call,
2523 // the result is a constant expression if it can be folded without
2524 // side-effects. This is an important GNU extension. See GCC PR38377
2526 if (const CallExpr *CallCE =
2527 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2528 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2531 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2532 // constant expression; we can't check whether it's potentially foldable.
2533 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2536 FoldConstant Fold(Info);
2538 if (!HandleConditionalOperator(E))
2547 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2548 const APValue *Value = Info.getOpaqueValue(E);
2550 const Expr *Source = E->getSourceExpr();
2553 if (Source == E) { // sanity checking.
2554 assert(0 && "OpaqueValueExpr recursively refers to itself");
2557 return StmtVisitorTy::Visit(Source);
2559 return DerivedSuccess(*Value, E);
2562 RetTy VisitCallExpr(const CallExpr *E) {
2563 const Expr *Callee = E->getCallee()->IgnoreParens();
2564 QualType CalleeType = Callee->getType();
2566 const FunctionDecl *FD = 0;
2567 LValue *This = 0, ThisVal;
2568 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2569 bool HasQualifier = false;
2571 // Extract function decl and 'this' pointer from the callee.
2572 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2573 const ValueDecl *Member = 0;
2574 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2575 // Explicit bound member calls, such as x.f() or p->g();
2576 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2578 Member = ME->getMemberDecl();
2580 HasQualifier = ME->hasQualifier();
2581 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2582 // Indirect bound member calls ('.*' or '->*').
2583 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2584 if (!Member) return false;
2587 return Error(Callee);
2589 FD = dyn_cast<FunctionDecl>(Member);
2591 return Error(Callee);
2592 } else if (CalleeType->isFunctionPointerType()) {
2594 if (!EvaluatePointer(Callee, Call, Info))
2597 if (!Call.getLValueOffset().isZero())
2598 return Error(Callee);
2599 FD = dyn_cast_or_null<FunctionDecl>(
2600 Call.getLValueBase().dyn_cast<const ValueDecl*>());
2602 return Error(Callee);
2604 // Overloaded operator calls to member functions are represented as normal
2605 // calls with '*this' as the first argument.
2606 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2607 if (MD && !MD->isStatic()) {
2608 // FIXME: When selecting an implicit conversion for an overloaded
2609 // operator delete, we sometimes try to evaluate calls to conversion
2610 // operators without a 'this' parameter!
2614 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2617 Args = Args.slice(1);
2620 // Don't call function pointers which have been cast to some other type.
2621 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2626 if (This && !This->checkSubobject(Info, E, CSK_This))
2629 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2630 // calls to such functions in constant expressions.
2631 if (This && !HasQualifier &&
2632 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2633 return Error(E, diag::note_constexpr_virtual_call);
2635 const FunctionDecl *Definition = 0;
2636 Stmt *Body = FD->getBody(Definition);
2639 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2640 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2644 return DerivedSuccess(Result, E);
2647 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2648 return StmtVisitorTy::Visit(E->getInitializer());
2650 RetTy VisitInitListExpr(const InitListExpr *E) {
2651 if (E->getNumInits() == 0)
2652 return DerivedZeroInitialization(E);
2653 if (E->getNumInits() == 1)
2654 return StmtVisitorTy::Visit(E->getInit(0));
2657 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2658 return DerivedZeroInitialization(E);
2660 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2661 return DerivedZeroInitialization(E);
2663 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2664 return DerivedZeroInitialization(E);
2667 /// A member expression where the object is a prvalue is itself a prvalue.
2668 RetTy VisitMemberExpr(const MemberExpr *E) {
2669 assert(!E->isArrow() && "missing call to bound member function?");
2672 if (!Evaluate(Val, Info, E->getBase()))
2675 QualType BaseTy = E->getBase()->getType();
2677 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2678 if (!FD) return Error(E);
2679 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2680 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2681 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2683 SubobjectDesignator Designator(BaseTy);
2684 Designator.addDeclUnchecked(FD);
2686 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2687 DerivedSuccess(Val, E);
2690 RetTy VisitCastExpr(const CastExpr *E) {
2691 switch (E->getCastKind()) {
2695 case CK_AtomicToNonAtomic:
2696 case CK_NonAtomicToAtomic:
2698 case CK_UserDefinedConversion:
2699 return StmtVisitorTy::Visit(E->getSubExpr());
2701 case CK_LValueToRValue: {
2703 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2706 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2707 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2710 return DerivedSuccess(RVal, E);
2717 /// Visit a value which is evaluated, but whose value is ignored.
2718 void VisitIgnoredValue(const Expr *E) {
2720 if (!Evaluate(Scratch, Info, E))
2721 Info.EvalStatus.HasSideEffects = true;
2727 //===----------------------------------------------------------------------===//
2728 // Common base class for lvalue and temporary evaluation.
2729 //===----------------------------------------------------------------------===//
2731 template<class Derived>
2732 class LValueExprEvaluatorBase
2733 : public ExprEvaluatorBase<Derived, bool> {
2736 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2737 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2739 bool Success(APValue::LValueBase B) {
2745 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2746 ExprEvaluatorBaseTy(Info), Result(Result) {}
2748 bool Success(const APValue &V, const Expr *E) {
2749 Result.setFrom(this->Info.Ctx, V);
2753 bool VisitMemberExpr(const MemberExpr *E) {
2754 // Handle non-static data members.
2757 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2759 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
2760 } else if (E->getBase()->isRValue()) {
2761 assert(E->getBase()->getType()->isRecordType());
2762 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2764 BaseTy = E->getBase()->getType();
2766 if (!this->Visit(E->getBase()))
2768 BaseTy = E->getBase()->getType();
2771 const ValueDecl *MD = E->getMemberDecl();
2772 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2773 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2774 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2776 HandleLValueMember(this->Info, E, Result, FD);
2777 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2778 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2780 return this->Error(E);
2782 if (MD->getType()->isReferenceType()) {
2784 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2787 return Success(RefValue, E);
2792 bool VisitBinaryOperator(const BinaryOperator *E) {
2793 switch (E->getOpcode()) {
2795 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2799 return HandleMemberPointerAccess(this->Info, E, Result);
2803 bool VisitCastExpr(const CastExpr *E) {
2804 switch (E->getCastKind()) {
2806 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2808 case CK_DerivedToBase:
2809 case CK_UncheckedDerivedToBase: {
2810 if (!this->Visit(E->getSubExpr()))
2813 // Now figure out the necessary offset to add to the base LV to get from
2814 // the derived class to the base class.
2815 QualType Type = E->getSubExpr()->getType();
2817 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2818 PathE = E->path_end(); PathI != PathE; ++PathI) {
2819 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2822 Type = (*PathI)->getType();
2832 //===----------------------------------------------------------------------===//
2833 // LValue Evaluation
2835 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2836 // function designators (in C), decl references to void objects (in C), and
2837 // temporaries (if building with -Wno-address-of-temporary).
2839 // LValue evaluation produces values comprising a base expression of one of the
2845 // * CompoundLiteralExpr in C
2849 // * ObjCStringLiteralExpr
2853 // * CallExpr for a MakeStringConstant builtin
2854 // - Locals and temporaries
2855 // * Any Expr, with a CallIndex indicating the function in which the temporary
2857 // plus an offset in bytes.
2858 //===----------------------------------------------------------------------===//
2860 class LValueExprEvaluator
2861 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2863 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2864 LValueExprEvaluatorBaseTy(Info, Result) {}
2866 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2868 bool VisitDeclRefExpr(const DeclRefExpr *E);
2869 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2870 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2871 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2872 bool VisitMemberExpr(const MemberExpr *E);
2873 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2874 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2875 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2876 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2877 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2878 bool VisitUnaryDeref(const UnaryOperator *E);
2879 bool VisitUnaryReal(const UnaryOperator *E);
2880 bool VisitUnaryImag(const UnaryOperator *E);
2882 bool VisitCastExpr(const CastExpr *E) {
2883 switch (E->getCastKind()) {
2885 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2887 case CK_LValueBitCast:
2888 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2889 if (!Visit(E->getSubExpr()))
2891 Result.Designator.setInvalid();
2894 case CK_BaseToDerived:
2895 if (!Visit(E->getSubExpr()))
2897 return HandleBaseToDerivedCast(Info, E, Result);
2901 } // end anonymous namespace
2903 /// Evaluate an expression as an lvalue. This can be legitimately called on
2904 /// expressions which are not glvalues, in a few cases:
2905 /// * function designators in C,
2906 /// * "extern void" objects,
2907 /// * temporaries, if building with -Wno-address-of-temporary.
2908 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2909 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2910 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2911 "can't evaluate expression as an lvalue");
2912 return LValueExprEvaluator(Info, Result).Visit(E);
2915 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2916 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2918 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2919 return VisitVarDecl(E, VD);
2923 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2924 if (!VD->getType()->isReferenceType()) {
2925 if (isa<ParmVarDecl>(VD)) {
2926 Result.set(VD, Info.CurrentCall->Index);
2933 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2935 return Success(V, E);
2938 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2939 const MaterializeTemporaryExpr *E) {
2940 if (E->GetTemporaryExpr()->isRValue()) {
2941 if (E->getType()->isRecordType())
2942 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2944 Result.set(E, Info.CurrentCall->Index);
2945 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2946 Result, E->GetTemporaryExpr());
2949 // Materialization of an lvalue temporary occurs when we need to force a copy
2950 // (for instance, if it's a bitfield).
2951 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2952 if (!Visit(E->GetTemporaryExpr()))
2954 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2955 Info.CurrentCall->Temporaries[E]))
2957 Result.set(E, Info.CurrentCall->Index);
2962 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2963 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2964 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2965 // only see this when folding in C, so there's no standard to follow here.
2969 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2970 if (E->isTypeOperand())
2972 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2973 if (RD && RD->isPolymorphic()) {
2974 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2975 << E->getExprOperand()->getType()
2976 << E->getExprOperand()->getSourceRange();
2982 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2986 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2987 // Handle static data members.
2988 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2989 VisitIgnoredValue(E->getBase());
2990 return VisitVarDecl(E, VD);
2993 // Handle static member functions.
2994 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2995 if (MD->isStatic()) {
2996 VisitIgnoredValue(E->getBase());
3001 // Handle non-static data members.
3002 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
3005 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
3006 // FIXME: Deal with vectors as array subscript bases.
3007 if (E->getBase()->getType()->isVectorType())
3010 if (!EvaluatePointer(E->getBase(), Result, Info))
3014 if (!EvaluateInteger(E->getIdx(), Index, Info))
3017 = Index.isSigned() ? Index.getSExtValue()
3018 : static_cast<int64_t>(Index.getZExtValue());
3020 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
3023 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
3024 return EvaluatePointer(E->getSubExpr(), Result, Info);
3027 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3028 if (!Visit(E->getSubExpr()))
3030 // __real is a no-op on scalar lvalues.
3031 if (E->getSubExpr()->getType()->isAnyComplexType())
3032 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3036 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3037 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3038 "lvalue __imag__ on scalar?");
3039 if (!Visit(E->getSubExpr()))
3041 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3045 //===----------------------------------------------------------------------===//
3046 // Pointer Evaluation
3047 //===----------------------------------------------------------------------===//
3050 class PointerExprEvaluator
3051 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
3054 bool Success(const Expr *E) {
3060 PointerExprEvaluator(EvalInfo &info, LValue &Result)
3061 : ExprEvaluatorBaseTy(info), Result(Result) {}
3063 bool Success(const APValue &V, const Expr *E) {
3064 Result.setFrom(Info.Ctx, V);
3067 bool ZeroInitialization(const Expr *E) {
3068 return Success((Expr*)0);
3071 bool VisitBinaryOperator(const BinaryOperator *E);
3072 bool VisitCastExpr(const CastExpr* E);
3073 bool VisitUnaryAddrOf(const UnaryOperator *E);
3074 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
3075 { return Success(E); }
3076 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3077 { return Success(E); }
3078 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
3079 { return Success(E); }
3080 bool VisitCallExpr(const CallExpr *E);
3081 bool VisitBlockExpr(const BlockExpr *E) {
3082 if (!E->getBlockDecl()->hasCaptures())
3086 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3087 if (!Info.CurrentCall->This)
3089 Result = *Info.CurrentCall->This;
3093 // FIXME: Missing: @protocol, @selector
3095 } // end anonymous namespace
3097 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
3098 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
3099 return PointerExprEvaluator(Info, Result).Visit(E);
3102 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3103 if (E->getOpcode() != BO_Add &&
3104 E->getOpcode() != BO_Sub)
3105 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3107 const Expr *PExp = E->getLHS();
3108 const Expr *IExp = E->getRHS();
3109 if (IExp->getType()->isPointerType())
3110 std::swap(PExp, IExp);
3112 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3113 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
3116 llvm::APSInt Offset;
3117 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
3119 int64_t AdditionalOffset
3120 = Offset.isSigned() ? Offset.getSExtValue()
3121 : static_cast<int64_t>(Offset.getZExtValue());
3122 if (E->getOpcode() == BO_Sub)
3123 AdditionalOffset = -AdditionalOffset;
3125 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
3126 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3130 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3131 return EvaluateLValue(E->getSubExpr(), Result, Info);
3134 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3135 const Expr* SubExpr = E->getSubExpr();
3137 switch (E->getCastKind()) {
3142 case CK_CPointerToObjCPointerCast:
3143 case CK_BlockPointerToObjCPointerCast:
3144 case CK_AnyPointerToBlockPointerCast:
3145 if (!Visit(SubExpr))
3147 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3148 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3149 // also static_casts, but we disallow them as a resolution to DR1312.
3150 if (!E->getType()->isVoidPointerType()) {
3151 Result.Designator.setInvalid();
3152 if (SubExpr->getType()->isVoidPointerType())
3153 CCEDiag(E, diag::note_constexpr_invalid_cast)
3154 << 3 << SubExpr->getType();
3156 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3160 case CK_DerivedToBase:
3161 case CK_UncheckedDerivedToBase: {
3162 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
3164 if (!Result.Base && Result.Offset.isZero())
3167 // Now figure out the necessary offset to add to the base LV to get from
3168 // the derived class to the base class.
3170 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3172 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3173 PathE = E->path_end(); PathI != PathE; ++PathI) {
3174 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3177 Type = (*PathI)->getType();
3183 case CK_BaseToDerived:
3184 if (!Visit(E->getSubExpr()))
3186 if (!Result.Base && Result.Offset.isZero())
3188 return HandleBaseToDerivedCast(Info, E, Result);
3190 case CK_NullToPointer:
3191 VisitIgnoredValue(E->getSubExpr());
3192 return ZeroInitialization(E);
3194 case CK_IntegralToPointer: {
3195 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3198 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3201 if (Value.isInt()) {
3202 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3203 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3204 Result.Base = (Expr*)0;
3205 Result.Offset = CharUnits::fromQuantity(N);
3206 Result.CallIndex = 0;
3207 Result.Designator.setInvalid();
3210 // Cast is of an lvalue, no need to change value.
3211 Result.setFrom(Info.Ctx, Value);
3215 case CK_ArrayToPointerDecay:
3216 if (SubExpr->isGLValue()) {
3217 if (!EvaluateLValue(SubExpr, Result, Info))
3220 Result.set(SubExpr, Info.CurrentCall->Index);
3221 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3222 Info, Result, SubExpr))
3225 // The result is a pointer to the first element of the array.
3226 if (const ConstantArrayType *CAT
3227 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3228 Result.addArray(Info, E, CAT);
3230 Result.Designator.setInvalid();
3233 case CK_FunctionToPointerDecay:
3234 return EvaluateLValue(SubExpr, Result, Info);
3237 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3240 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3241 if (IsStringLiteralCall(E))
3244 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3247 //===----------------------------------------------------------------------===//
3248 // Member Pointer Evaluation
3249 //===----------------------------------------------------------------------===//
3252 class MemberPointerExprEvaluator
3253 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3256 bool Success(const ValueDecl *D) {
3257 Result = MemberPtr(D);
3262 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3263 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3265 bool Success(const APValue &V, const Expr *E) {
3269 bool ZeroInitialization(const Expr *E) {
3270 return Success((const ValueDecl*)0);
3273 bool VisitCastExpr(const CastExpr *E);
3274 bool VisitUnaryAddrOf(const UnaryOperator *E);
3276 } // end anonymous namespace
3278 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3280 assert(E->isRValue() && E->getType()->isMemberPointerType());
3281 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3284 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3285 switch (E->getCastKind()) {
3287 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3289 case CK_NullToMemberPointer:
3290 VisitIgnoredValue(E->getSubExpr());
3291 return ZeroInitialization(E);
3293 case CK_BaseToDerivedMemberPointer: {
3294 if (!Visit(E->getSubExpr()))
3296 if (E->path_empty())
3298 // Base-to-derived member pointer casts store the path in derived-to-base
3299 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3300 // the wrong end of the derived->base arc, so stagger the path by one class.
3301 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3302 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3303 PathI != PathE; ++PathI) {
3304 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3305 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3306 if (!Result.castToDerived(Derived))
3309 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3310 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3315 case CK_DerivedToBaseMemberPointer:
3316 if (!Visit(E->getSubExpr()))
3318 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3319 PathE = E->path_end(); PathI != PathE; ++PathI) {
3320 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3321 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3322 if (!Result.castToBase(Base))
3329 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3330 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3331 // member can be formed.
3332 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3335 //===----------------------------------------------------------------------===//
3336 // Record Evaluation
3337 //===----------------------------------------------------------------------===//
3340 class RecordExprEvaluator
3341 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3346 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3347 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3349 bool Success(const APValue &V, const Expr *E) {
3353 bool ZeroInitialization(const Expr *E);
3355 bool VisitCastExpr(const CastExpr *E);
3356 bool VisitInitListExpr(const InitListExpr *E);
3357 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3361 /// Perform zero-initialization on an object of non-union class type.
3362 /// C++11 [dcl.init]p5:
3363 /// To zero-initialize an object or reference of type T means:
3365 /// -- if T is a (possibly cv-qualified) non-union class type,
3366 /// each non-static data member and each base-class subobject is
3367 /// zero-initialized
3368 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3369 const RecordDecl *RD,
3370 const LValue &This, APValue &Result) {
3371 assert(!RD->isUnion() && "Expected non-union class type");
3372 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3373 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3374 std::distance(RD->field_begin(), RD->field_end()));
3376 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3380 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3381 End = CD->bases_end(); I != End; ++I, ++Index) {
3382 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3383 LValue Subobject = This;
3384 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3385 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3386 Result.getStructBase(Index)))
3391 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3393 // -- if T is a reference type, no initialization is performed.
3394 if ((*I)->getType()->isReferenceType())
3397 LValue Subobject = This;
3398 HandleLValueMember(Info, E, Subobject, *I, &Layout);
3400 ImplicitValueInitExpr VIE((*I)->getType());
3401 if (!EvaluateInPlace(
3402 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3409 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3410 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3411 if (RD->isUnion()) {
3412 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3413 // object's first non-static named data member is zero-initialized
3414 RecordDecl::field_iterator I = RD->field_begin();
3415 if (I == RD->field_end()) {
3416 Result = APValue((const FieldDecl*)0);
3420 LValue Subobject = This;
3421 HandleLValueMember(Info, E, Subobject, *I);
3422 Result = APValue(*I);
3423 ImplicitValueInitExpr VIE((*I)->getType());
3424 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
3427 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3428 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
3432 return HandleClassZeroInitialization(Info, E, RD, This, Result);
3435 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3436 switch (E->getCastKind()) {
3438 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3440 case CK_ConstructorConversion:
3441 return Visit(E->getSubExpr());
3443 case CK_DerivedToBase:
3444 case CK_UncheckedDerivedToBase: {
3445 APValue DerivedObject;
3446 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3448 if (!DerivedObject.isStruct())
3449 return Error(E->getSubExpr());
3451 // Derived-to-base rvalue conversion: just slice off the derived part.
3452 APValue *Value = &DerivedObject;
3453 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3454 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3455 PathE = E->path_end(); PathI != PathE; ++PathI) {
3456 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3457 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3458 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3467 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3468 // Cannot constant-evaluate std::initializer_list inits.
3469 if (E->initializesStdInitializerList())
3472 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3473 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3475 if (RD->isUnion()) {
3476 const FieldDecl *Field = E->getInitializedFieldInUnion();
3477 Result = APValue(Field);
3481 // If the initializer list for a union does not contain any elements, the
3482 // first element of the union is value-initialized.
3483 ImplicitValueInitExpr VIE(Field->getType());
3484 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3486 LValue Subobject = This;
3487 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
3488 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
3491 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3492 "initializer list for class with base classes");
3493 Result = APValue(APValue::UninitStruct(), 0,
3494 std::distance(RD->field_begin(), RD->field_end()));
3495 unsigned ElementNo = 0;
3496 bool Success = true;
3497 for (RecordDecl::field_iterator Field = RD->field_begin(),
3498 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3499 // Anonymous bit-fields are not considered members of the class for
3500 // purposes of aggregate initialization.
3501 if (Field->isUnnamedBitfield())
3504 LValue Subobject = This;
3506 bool HaveInit = ElementNo < E->getNumInits();
3508 // FIXME: Diagnostics here should point to the end of the initializer
3509 // list, not the start.
3510 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3513 // Perform an implicit value-initialization for members beyond the end of
3514 // the initializer list.
3515 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3517 if (!EvaluateInPlace(
3518 Result.getStructField((*Field)->getFieldIndex()),
3519 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3520 if (!Info.keepEvaluatingAfterFailure())
3529 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3530 const CXXConstructorDecl *FD = E->getConstructor();
3531 bool ZeroInit = E->requiresZeroInitialization();
3532 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3533 // If we've already performed zero-initialization, we're already done.
3534 if (!Result.isUninit())
3538 return ZeroInitialization(E);
3540 const CXXRecordDecl *RD = FD->getParent();
3542 Result = APValue((FieldDecl*)0);
3544 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3545 std::distance(RD->field_begin(), RD->field_end()));
3549 const FunctionDecl *Definition = 0;
3550 FD->getBody(Definition);
3552 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3555 // Avoid materializing a temporary for an elidable copy/move constructor.
3556 if (E->isElidable() && !ZeroInit)
3557 if (const MaterializeTemporaryExpr *ME
3558 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3559 return Visit(ME->GetTemporaryExpr());
3561 if (ZeroInit && !ZeroInitialization(E))
3564 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3565 return HandleConstructorCall(E->getExprLoc(), This, Args,
3566 cast<CXXConstructorDecl>(Definition), Info,
3570 static bool EvaluateRecord(const Expr *E, const LValue &This,
3571 APValue &Result, EvalInfo &Info) {
3572 assert(E->isRValue() && E->getType()->isRecordType() &&
3573 "can't evaluate expression as a record rvalue");
3574 return RecordExprEvaluator(Info, This, Result).Visit(E);
3577 //===----------------------------------------------------------------------===//
3578 // Temporary Evaluation
3580 // Temporaries are represented in the AST as rvalues, but generally behave like
3581 // lvalues. The full-object of which the temporary is a subobject is implicitly
3582 // materialized so that a reference can bind to it.
3583 //===----------------------------------------------------------------------===//
3585 class TemporaryExprEvaluator
3586 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3588 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3589 LValueExprEvaluatorBaseTy(Info, Result) {}
3591 /// Visit an expression which constructs the value of this temporary.
3592 bool VisitConstructExpr(const Expr *E) {
3593 Result.set(E, Info.CurrentCall->Index);
3594 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
3597 bool VisitCastExpr(const CastExpr *E) {
3598 switch (E->getCastKind()) {
3600 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3602 case CK_ConstructorConversion:
3603 return VisitConstructExpr(E->getSubExpr());
3606 bool VisitInitListExpr(const InitListExpr *E) {
3607 return VisitConstructExpr(E);
3609 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3610 return VisitConstructExpr(E);
3612 bool VisitCallExpr(const CallExpr *E) {
3613 return VisitConstructExpr(E);
3616 } // end anonymous namespace
3618 /// Evaluate an expression of record type as a temporary.
3619 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3620 assert(E->isRValue() && E->getType()->isRecordType());
3621 return TemporaryExprEvaluator(Info, Result).Visit(E);
3624 //===----------------------------------------------------------------------===//
3625 // Vector Evaluation
3626 //===----------------------------------------------------------------------===//
3629 class VectorExprEvaluator
3630 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3634 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3635 : ExprEvaluatorBaseTy(info), Result(Result) {}
3637 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3638 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3639 // FIXME: remove this APValue copy.
3640 Result = APValue(V.data(), V.size());
3643 bool Success(const APValue &V, const Expr *E) {
3644 assert(V.isVector());
3648 bool ZeroInitialization(const Expr *E);
3650 bool VisitUnaryReal(const UnaryOperator *E)
3651 { return Visit(E->getSubExpr()); }
3652 bool VisitCastExpr(const CastExpr* E);
3653 bool VisitInitListExpr(const InitListExpr *E);
3654 bool VisitUnaryImag(const UnaryOperator *E);
3655 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3656 // binary comparisons, binary and/or/xor,
3657 // shufflevector, ExtVectorElementExpr
3659 } // end anonymous namespace
3661 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3662 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3663 return VectorExprEvaluator(Info, Result).Visit(E);
3666 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3667 const VectorType *VTy = E->getType()->castAs<VectorType>();
3668 unsigned NElts = VTy->getNumElements();
3670 const Expr *SE = E->getSubExpr();
3671 QualType SETy = SE->getType();
3673 switch (E->getCastKind()) {
3674 case CK_VectorSplat: {
3675 APValue Val = APValue();
3676 if (SETy->isIntegerType()) {
3678 if (!EvaluateInteger(SE, IntResult, Info))
3680 Val = APValue(IntResult);
3681 } else if (SETy->isRealFloatingType()) {
3683 if (!EvaluateFloat(SE, F, Info))
3690 // Splat and create vector APValue.
3691 SmallVector<APValue, 4> Elts(NElts, Val);
3692 return Success(Elts, E);
3695 // Evaluate the operand into an APInt we can extract from.
3696 llvm::APInt SValInt;
3697 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3699 // Extract the elements
3700 QualType EltTy = VTy->getElementType();
3701 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3702 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3703 SmallVector<APValue, 4> Elts;
3704 if (EltTy->isRealFloatingType()) {
3705 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3706 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3707 unsigned FloatEltSize = EltSize;
3708 if (&Sem == &APFloat::x87DoubleExtended)
3710 for (unsigned i = 0; i < NElts; i++) {
3713 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3715 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3716 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3718 } else if (EltTy->isIntegerType()) {
3719 for (unsigned i = 0; i < NElts; i++) {
3722 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3724 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3725 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3730 return Success(Elts, E);
3733 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3738 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3739 const VectorType *VT = E->getType()->castAs<VectorType>();
3740 unsigned NumInits = E->getNumInits();
3741 unsigned NumElements = VT->getNumElements();
3743 QualType EltTy = VT->getElementType();
3744 SmallVector<APValue, 4> Elements;
3746 // The number of initializers can be less than the number of
3747 // vector elements. For OpenCL, this can be due to nested vector
3748 // initialization. For GCC compatibility, missing trailing elements
3749 // should be initialized with zeroes.
3750 unsigned CountInits = 0, CountElts = 0;
3751 while (CountElts < NumElements) {
3752 // Handle nested vector initialization.
3753 if (CountInits < NumInits
3754 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3756 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3758 unsigned vlen = v.getVectorLength();
3759 for (unsigned j = 0; j < vlen; j++)
3760 Elements.push_back(v.getVectorElt(j));
3762 } else if (EltTy->isIntegerType()) {
3763 llvm::APSInt sInt(32);
3764 if (CountInits < NumInits) {
3765 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3767 } else // trailing integer zero.
3768 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3769 Elements.push_back(APValue(sInt));
3772 llvm::APFloat f(0.0);
3773 if (CountInits < NumInits) {
3774 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3776 } else // trailing float zero.
3777 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3778 Elements.push_back(APValue(f));
3783 return Success(Elements, E);
3787 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3788 const VectorType *VT = E->getType()->getAs<VectorType>();
3789 QualType EltTy = VT->getElementType();
3790 APValue ZeroElement;
3791 if (EltTy->isIntegerType())
3792 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3795 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3797 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3798 return Success(Elements, E);
3801 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3802 VisitIgnoredValue(E->getSubExpr());
3803 return ZeroInitialization(E);
3806 //===----------------------------------------------------------------------===//
3808 //===----------------------------------------------------------------------===//
3811 class ArrayExprEvaluator
3812 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3817 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3818 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3820 bool Success(const APValue &V, const Expr *E) {
3821 assert((V.isArray() || V.isLValue()) &&
3822 "expected array or string literal");
3827 bool ZeroInitialization(const Expr *E) {
3828 const ConstantArrayType *CAT =
3829 Info.Ctx.getAsConstantArrayType(E->getType());
3833 Result = APValue(APValue::UninitArray(), 0,
3834 CAT->getSize().getZExtValue());
3835 if (!Result.hasArrayFiller()) return true;
3837 // Zero-initialize all elements.
3838 LValue Subobject = This;
3839 Subobject.addArray(Info, E, CAT);
3840 ImplicitValueInitExpr VIE(CAT->getElementType());
3841 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3844 bool VisitInitListExpr(const InitListExpr *E);
3845 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3847 } // end anonymous namespace
3849 static bool EvaluateArray(const Expr *E, const LValue &This,
3850 APValue &Result, EvalInfo &Info) {
3851 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3852 return ArrayExprEvaluator(Info, This, Result).Visit(E);
3855 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3856 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3860 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3861 // an appropriately-typed string literal enclosed in braces.
3862 if (E->isStringLiteralInit()) {
3864 if (!EvaluateLValue(E->getInit(0), LV, Info))
3868 return Success(Val, E);
3871 bool Success = true;
3873 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3874 CAT->getSize().getZExtValue());
3875 LValue Subobject = This;
3876 Subobject.addArray(Info, E, CAT);
3878 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3879 I != End; ++I, ++Index) {
3880 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3881 Info, Subobject, cast<Expr>(*I)) ||
3882 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3883 CAT->getElementType(), 1)) {
3884 if (!Info.keepEvaluatingAfterFailure())
3890 if (!Result.hasArrayFiller()) return Success;
3891 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3892 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3893 // but sometimes does:
3894 // struct S { constexpr S() : p(&p) {} void *p; };
3896 return EvaluateInPlace(Result.getArrayFiller(), Info,
3897 Subobject, E->getArrayFiller()) && Success;
3900 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3901 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3905 bool HadZeroInit = !Result.isUninit();
3907 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3908 if (!Result.hasArrayFiller())
3911 const CXXConstructorDecl *FD = E->getConstructor();
3913 bool ZeroInit = E->requiresZeroInitialization();
3914 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3919 LValue Subobject = This;
3920 Subobject.addArray(Info, E, CAT);
3921 ImplicitValueInitExpr VIE(CAT->getElementType());
3922 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3925 const CXXRecordDecl *RD = FD->getParent();
3927 Result.getArrayFiller() = APValue((FieldDecl*)0);
3929 Result.getArrayFiller() =
3930 APValue(APValue::UninitStruct(), RD->getNumBases(),
3931 std::distance(RD->field_begin(), RD->field_end()));
3935 const FunctionDecl *Definition = 0;
3936 FD->getBody(Definition);
3938 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3941 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3942 // but sometimes does:
3943 // struct S { constexpr S() : p(&p) {} void *p; };
3945 LValue Subobject = This;
3946 Subobject.addArray(Info, E, CAT);
3948 if (ZeroInit && !HadZeroInit) {
3949 ImplicitValueInitExpr VIE(CAT->getElementType());
3950 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
3954 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3955 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3956 cast<CXXConstructorDecl>(Definition),
3957 Info, Result.getArrayFiller());
3960 //===----------------------------------------------------------------------===//
3961 // Integer Evaluation
3963 // As a GNU extension, we support casting pointers to sufficiently-wide integer
3964 // types and back in constant folding. Integer values are thus represented
3965 // either as an integer-valued APValue, or as an lvalue-valued APValue.
3966 //===----------------------------------------------------------------------===//
3969 class IntExprEvaluator
3970 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3973 IntExprEvaluator(EvalInfo &info, APValue &result)
3974 : ExprEvaluatorBaseTy(info), Result(result) {}
3976 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
3977 assert(E->getType()->isIntegralOrEnumerationType() &&
3978 "Invalid evaluation result.");
3979 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3980 "Invalid evaluation result.");
3981 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3982 "Invalid evaluation result.");
3983 Result = APValue(SI);
3986 bool Success(const llvm::APSInt &SI, const Expr *E) {
3987 return Success(SI, E, Result);
3990 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
3991 assert(E->getType()->isIntegralOrEnumerationType() &&
3992 "Invalid evaluation result.");
3993 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3994 "Invalid evaluation result.");
3995 Result = APValue(APSInt(I));
3996 Result.getInt().setIsUnsigned(
3997 E->getType()->isUnsignedIntegerOrEnumerationType());
4000 bool Success(const llvm::APInt &I, const Expr *E) {
4001 return Success(I, E, Result);
4004 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4005 assert(E->getType()->isIntegralOrEnumerationType() &&
4006 "Invalid evaluation result.");
4007 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
4010 bool Success(uint64_t Value, const Expr *E) {
4011 return Success(Value, E, Result);
4014 bool Success(CharUnits Size, const Expr *E) {
4015 return Success(Size.getQuantity(), E);
4018 bool Success(const APValue &V, const Expr *E) {
4019 if (V.isLValue() || V.isAddrLabelDiff()) {
4023 return Success(V.getInt(), E);
4026 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
4028 //===--------------------------------------------------------------------===//
4030 //===--------------------------------------------------------------------===//
4032 bool VisitIntegerLiteral(const IntegerLiteral *E) {
4033 return Success(E->getValue(), E);
4035 bool VisitCharacterLiteral(const CharacterLiteral *E) {
4036 return Success(E->getValue(), E);
4039 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4040 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4041 if (CheckReferencedDecl(E, E->getDecl()))
4044 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
4046 bool VisitMemberExpr(const MemberExpr *E) {
4047 if (CheckReferencedDecl(E, E->getMemberDecl())) {
4048 VisitIgnoredValue(E->getBase());
4052 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
4055 bool VisitCallExpr(const CallExpr *E);
4056 bool VisitBinaryOperator(const BinaryOperator *E);
4057 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
4058 bool VisitUnaryOperator(const UnaryOperator *E);
4060 bool VisitCastExpr(const CastExpr* E);
4061 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
4063 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4064 return Success(E->getValue(), E);
4067 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4068 return Success(E->getValue(), E);
4071 // Note, GNU defines __null as an integer, not a pointer.
4072 bool VisitGNUNullExpr(const GNUNullExpr *E) {
4073 return ZeroInitialization(E);
4076 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
4077 return Success(E->getValue(), E);
4080 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4081 return Success(E->getValue(), E);
4084 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4085 return Success(E->getValue(), E);
4088 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4089 return Success(E->getValue(), E);
4092 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4093 return Success(E->getValue(), E);
4096 bool VisitUnaryReal(const UnaryOperator *E);
4097 bool VisitUnaryImag(const UnaryOperator *E);
4099 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
4100 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
4103 CharUnits GetAlignOfExpr(const Expr *E);
4104 CharUnits GetAlignOfType(QualType T);
4105 static QualType GetObjectType(APValue::LValueBase B);
4106 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
4107 // FIXME: Missing: array subscript of vector, member of vector
4109 } // end anonymous namespace
4111 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4112 /// produce either the integer value or a pointer.
4114 /// GCC has a heinous extension which folds casts between pointer types and
4115 /// pointer-sized integral types. We support this by allowing the evaluation of
4116 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4117 /// Some simple arithmetic on such values is supported (they are treated much
4119 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
4121 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
4122 return IntExprEvaluator(Info, Result).Visit(E);
4125 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
4127 if (!EvaluateIntegerOrLValue(E, Val, Info))
4130 // FIXME: It would be better to produce the diagnostic for casting
4131 // a pointer to an integer.
4132 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
4135 Result = Val.getInt();
4139 /// Check whether the given declaration can be directly converted to an integral
4140 /// rvalue. If not, no diagnostic is produced; there are other things we can
4142 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
4143 // Enums are integer constant exprs.
4144 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
4145 // Check for signedness/width mismatches between E type and ECD value.
4146 bool SameSign = (ECD->getInitVal().isSigned()
4147 == E->getType()->isSignedIntegerOrEnumerationType());
4148 bool SameWidth = (ECD->getInitVal().getBitWidth()
4149 == Info.Ctx.getIntWidth(E->getType()));
4150 if (SameSign && SameWidth)
4151 return Success(ECD->getInitVal(), E);
4153 // Get rid of mismatch (otherwise Success assertions will fail)
4154 // by computing a new value matching the type of E.
4155 llvm::APSInt Val = ECD->getInitVal();
4157 Val.setIsSigned(!ECD->getInitVal().isSigned());
4159 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4160 return Success(Val, E);
4166 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4168 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4169 // The following enum mimics the values returned by GCC.
4170 // FIXME: Does GCC differ between lvalue and rvalue references here?
4171 enum gcc_type_class {
4173 void_type_class, integer_type_class, char_type_class,
4174 enumeral_type_class, boolean_type_class,
4175 pointer_type_class, reference_type_class, offset_type_class,
4176 real_type_class, complex_type_class,
4177 function_type_class, method_type_class,
4178 record_type_class, union_type_class,
4179 array_type_class, string_type_class,
4183 // If no argument was supplied, default to "no_type_class". This isn't
4184 // ideal, however it is what gcc does.
4185 if (E->getNumArgs() == 0)
4186 return no_type_class;
4188 QualType ArgTy = E->getArg(0)->getType();
4189 if (ArgTy->isVoidType())
4190 return void_type_class;
4191 else if (ArgTy->isEnumeralType())
4192 return enumeral_type_class;
4193 else if (ArgTy->isBooleanType())
4194 return boolean_type_class;
4195 else if (ArgTy->isCharType())
4196 return string_type_class; // gcc doesn't appear to use char_type_class
4197 else if (ArgTy->isIntegerType())
4198 return integer_type_class;
4199 else if (ArgTy->isPointerType())
4200 return pointer_type_class;
4201 else if (ArgTy->isReferenceType())
4202 return reference_type_class;
4203 else if (ArgTy->isRealType())
4204 return real_type_class;
4205 else if (ArgTy->isComplexType())
4206 return complex_type_class;
4207 else if (ArgTy->isFunctionType())
4208 return function_type_class;
4209 else if (ArgTy->isStructureOrClassType())
4210 return record_type_class;
4211 else if (ArgTy->isUnionType())
4212 return union_type_class;
4213 else if (ArgTy->isArrayType())
4214 return array_type_class;
4215 else if (ArgTy->isUnionType())
4216 return union_type_class;
4217 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
4218 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4221 /// EvaluateBuiltinConstantPForLValue - Determine the result of
4222 /// __builtin_constant_p when applied to the given lvalue.
4224 /// An lvalue is only "constant" if it is a pointer or reference to the first
4225 /// character of a string literal.
4226 template<typename LValue>
4227 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4228 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
4229 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4232 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4233 /// GCC as we can manage.
4234 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4235 QualType ArgType = Arg->getType();
4237 // __builtin_constant_p always has one operand. The rules which gcc follows
4238 // are not precisely documented, but are as follows:
4240 // - If the operand is of integral, floating, complex or enumeration type,
4241 // and can be folded to a known value of that type, it returns 1.
4242 // - If the operand and can be folded to a pointer to the first character
4243 // of a string literal (or such a pointer cast to an integral type), it
4246 // Otherwise, it returns 0.
4248 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4249 // its support for this does not currently work.
4250 if (ArgType->isIntegralOrEnumerationType()) {
4251 Expr::EvalResult Result;
4252 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4255 APValue &V = Result.Val;
4256 if (V.getKind() == APValue::Int)
4259 return EvaluateBuiltinConstantPForLValue(V);
4260 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4261 return Arg->isEvaluatable(Ctx);
4262 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4264 Expr::EvalStatus Status;
4265 EvalInfo Info(Ctx, Status);
4266 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4267 : EvaluatePointer(Arg, LV, Info)) &&
4268 !Status.HasSideEffects)
4269 return EvaluateBuiltinConstantPForLValue(LV);
4272 // Anything else isn't considered to be sufficiently constant.
4276 /// Retrieves the "underlying object type" of the given expression,
4277 /// as used by __builtin_object_size.
4278 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4279 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4280 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4281 return VD->getType();
4282 } else if (const Expr *E = B.get<const Expr*>()) {
4283 if (isa<CompoundLiteralExpr>(E))
4284 return E->getType();
4290 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4291 // TODO: Perhaps we should let LLVM lower this?
4293 if (!EvaluatePointer(E->getArg(0), Base, Info))
4296 // If we can prove the base is null, lower to zero now.
4297 if (!Base.getLValueBase()) return Success(0, E);
4299 QualType T = GetObjectType(Base.getLValueBase());
4301 T->isIncompleteType() ||
4302 T->isFunctionType() ||
4303 T->isVariablyModifiedType() ||
4304 T->isDependentType())
4307 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4308 CharUnits Offset = Base.getLValueOffset();
4310 if (!Offset.isNegative() && Offset <= Size)
4313 Size = CharUnits::Zero();
4314 return Success(Size, E);
4317 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
4318 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
4320 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4322 case Builtin::BI__builtin_object_size: {
4323 if (TryEvaluateBuiltinObjectSize(E))
4326 // If evaluating the argument has side-effects we can't determine
4327 // the size of the object and lower it to unknown now.
4328 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
4329 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
4330 return Success(-1ULL, E);
4331 return Success(0, E);
4337 case Builtin::BI__builtin_classify_type:
4338 return Success(EvaluateBuiltinClassifyType(E), E);
4340 case Builtin::BI__builtin_constant_p:
4341 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4343 case Builtin::BI__builtin_eh_return_data_regno: {
4344 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4345 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4346 return Success(Operand, E);
4349 case Builtin::BI__builtin_expect:
4350 return Visit(E->getArg(0));
4352 case Builtin::BIstrlen:
4353 // A call to strlen is not a constant expression.
4354 if (Info.getLangOpts().CPlusPlus0x)
4355 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
4356 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4358 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
4360 case Builtin::BI__builtin_strlen:
4361 // As an extension, we support strlen() and __builtin_strlen() as constant
4362 // expressions when the argument is a string literal.
4363 if (const StringLiteral *S
4364 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4365 // The string literal may have embedded null characters. Find the first
4366 // one and truncate there.
4367 StringRef Str = S->getString();
4368 StringRef::size_type Pos = Str.find(0);
4369 if (Pos != StringRef::npos)
4370 Str = Str.substr(0, Pos);
4372 return Success(Str.size(), E);
4377 case Builtin::BI__atomic_always_lock_free:
4378 case Builtin::BI__atomic_is_lock_free:
4379 case Builtin::BI__c11_atomic_is_lock_free: {
4381 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4384 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4385 // of two less than the maximum inline atomic width, we know it is
4386 // lock-free. If the size isn't a power of two, or greater than the
4387 // maximum alignment where we promote atomics, we know it is not lock-free
4388 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4389 // the answer can only be determined at runtime; for example, 16-byte
4390 // atomics have lock-free implementations on some, but not all,
4391 // x86-64 processors.
4393 // Check power-of-two.
4394 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4395 if (Size.isPowerOfTwo()) {
4396 // Check against inlining width.
4397 unsigned InlineWidthBits =
4398 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4399 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4400 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4401 Size == CharUnits::One() ||
4402 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4403 Expr::NPC_NeverValueDependent))
4404 // OK, we will inline appropriately-aligned operations of this size,
4405 // and _Atomic(T) is appropriately-aligned.
4406 return Success(1, E);
4408 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4409 castAs<PointerType>()->getPointeeType();
4410 if (!PointeeType->isIncompleteType() &&
4411 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4412 // OK, we will inline operations on this object.
4413 return Success(1, E);
4418 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4419 Success(0, E) : Error(E);
4424 static bool HasSameBase(const LValue &A, const LValue &B) {
4425 if (!A.getLValueBase())
4426 return !B.getLValueBase();
4427 if (!B.getLValueBase())
4430 if (A.getLValueBase().getOpaqueValue() !=
4431 B.getLValueBase().getOpaqueValue()) {
4432 const Decl *ADecl = GetLValueBaseDecl(A);
4435 const Decl *BDecl = GetLValueBaseDecl(B);
4436 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4440 return IsGlobalLValue(A.getLValueBase()) ||
4441 A.getLValueCallIndex() == B.getLValueCallIndex();
4444 /// Perform the given integer operation, which is known to need at most BitWidth
4445 /// bits, and check for overflow in the original type (if that type was not an
4447 template<typename Operation>
4448 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4449 const APSInt &LHS, const APSInt &RHS,
4450 unsigned BitWidth, Operation Op) {
4451 if (LHS.isUnsigned())
4452 return Op(LHS, RHS);
4454 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4455 APSInt Result = Value.trunc(LHS.getBitWidth());
4456 if (Result.extend(BitWidth) != Value)
4457 HandleOverflow(Info, E, Value, E->getType());
4463 /// \brief Data recursive integer evaluator of certain binary operators.
4465 /// We use a data recursive algorithm for binary operators so that we are able
4466 /// to handle extreme cases of chained binary operators without causing stack
4468 class DataRecursiveIntBinOpEvaluator {
4473 EvalResult() : Failed(false) { }
4475 void swap(EvalResult &RHS) {
4477 Failed = RHS.Failed;
4484 EvalResult LHSResult; // meaningful only for binary operator expression.
4485 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4487 Job() : StoredInfo(0) { }
4488 void startSpeculativeEval(EvalInfo &Info) {
4489 OldEvalStatus = Info.EvalStatus;
4490 Info.EvalStatus.Diag = 0;
4495 StoredInfo->EvalStatus = OldEvalStatus;
4499 EvalInfo *StoredInfo; // non-null if status changed.
4500 Expr::EvalStatus OldEvalStatus;
4503 SmallVector<Job, 16> Queue;
4505 IntExprEvaluator &IntEval;
4507 APValue &FinalResult;
4510 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4511 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4513 /// \brief True if \param E is a binary operator that we are going to handle
4514 /// data recursively.
4515 /// We handle binary operators that are comma, logical, or that have operands
4516 /// with integral or enumeration type.
4517 static bool shouldEnqueue(const BinaryOperator *E) {
4518 return E->getOpcode() == BO_Comma ||
4520 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4521 E->getRHS()->getType()->isIntegralOrEnumerationType());
4524 bool Traverse(const BinaryOperator *E) {
4526 EvalResult PrevResult;
4527 while (!Queue.empty())
4528 process(PrevResult);
4530 if (PrevResult.Failed) return false;
4532 FinalResult.swap(PrevResult.Val);
4537 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4538 return IntEval.Success(Value, E, Result);
4540 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4541 return IntEval.Success(Value, E, Result);
4543 bool Error(const Expr *E) {
4544 return IntEval.Error(E);
4546 bool Error(const Expr *E, diag::kind D) {
4547 return IntEval.Error(E, D);
4550 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4551 return Info.CCEDiag(E, D);
4554 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4555 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4556 bool &SuppressRHSDiags);
4558 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4559 const BinaryOperator *E, APValue &Result);
4561 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4562 Result.Failed = !Evaluate(Result.Val, Info, E);
4564 Result.Val = APValue();
4567 void process(EvalResult &Result);
4569 void enqueue(const Expr *E) {
4570 E = E->IgnoreParens();
4571 Queue.resize(Queue.size()+1);
4573 Queue.back().Kind = Job::AnyExprKind;
4579 bool DataRecursiveIntBinOpEvaluator::
4580 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4581 bool &SuppressRHSDiags) {
4582 if (E->getOpcode() == BO_Comma) {
4583 // Ignore LHS but note if we could not evaluate it.
4584 if (LHSResult.Failed)
4585 Info.EvalStatus.HasSideEffects = true;
4589 if (E->isLogicalOp()) {
4591 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
4592 // We were able to evaluate the LHS, see if we can get away with not
4593 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4594 if (lhsResult == (E->getOpcode() == BO_LOr)) {
4595 Success(lhsResult, E, LHSResult.Val);
4596 return false; // Ignore RHS
4599 // Since we weren't able to evaluate the left hand side, it
4600 // must have had side effects.
4601 Info.EvalStatus.HasSideEffects = true;
4603 // We can't evaluate the LHS; however, sometimes the result
4604 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4605 // Don't ignore RHS and suppress diagnostics from this arm.
4606 SuppressRHSDiags = true;
4612 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4613 E->getRHS()->getType()->isIntegralOrEnumerationType());
4615 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
4616 return false; // Ignore RHS;
4621 bool DataRecursiveIntBinOpEvaluator::
4622 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4623 const BinaryOperator *E, APValue &Result) {
4624 if (E->getOpcode() == BO_Comma) {
4625 if (RHSResult.Failed)
4627 Result = RHSResult.Val;
4631 if (E->isLogicalOp()) {
4632 bool lhsResult, rhsResult;
4633 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4634 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4638 if (E->getOpcode() == BO_LOr)
4639 return Success(lhsResult || rhsResult, E, Result);
4641 return Success(lhsResult && rhsResult, E, Result);
4645 // We can't evaluate the LHS; however, sometimes the result
4646 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4647 if (rhsResult == (E->getOpcode() == BO_LOr))
4648 return Success(rhsResult, E, Result);
4655 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4656 E->getRHS()->getType()->isIntegralOrEnumerationType());
4658 if (LHSResult.Failed || RHSResult.Failed)
4661 const APValue &LHSVal = LHSResult.Val;
4662 const APValue &RHSVal = RHSResult.Val;
4664 // Handle cases like (unsigned long)&a + 4.
4665 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4667 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4668 RHSVal.getInt().getZExtValue());
4669 if (E->getOpcode() == BO_Add)
4670 Result.getLValueOffset() += AdditionalOffset;
4672 Result.getLValueOffset() -= AdditionalOffset;
4676 // Handle cases like 4 + (unsigned long)&a
4677 if (E->getOpcode() == BO_Add &&
4678 RHSVal.isLValue() && LHSVal.isInt()) {
4680 Result.getLValueOffset() += CharUnits::fromQuantity(
4681 LHSVal.getInt().getZExtValue());
4685 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4686 // Handle (intptr_t)&&A - (intptr_t)&&B.
4687 if (!LHSVal.getLValueOffset().isZero() ||
4688 !RHSVal.getLValueOffset().isZero())
4690 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4691 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4692 if (!LHSExpr || !RHSExpr)
4694 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4695 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4696 if (!LHSAddrExpr || !RHSAddrExpr)
4698 // Make sure both labels come from the same function.
4699 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4700 RHSAddrExpr->getLabel()->getDeclContext())
4702 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4706 // All the following cases expect both operands to be an integer
4707 if (!LHSVal.isInt() || !RHSVal.isInt())
4710 const APSInt &LHS = LHSVal.getInt();
4711 APSInt RHS = RHSVal.getInt();
4713 switch (E->getOpcode()) {
4717 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4718 LHS.getBitWidth() * 2,
4719 std::multiplies<APSInt>()), E,
4722 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4723 LHS.getBitWidth() + 1,
4724 std::plus<APSInt>()), E, Result);
4726 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4727 LHS.getBitWidth() + 1,
4728 std::minus<APSInt>()), E, Result);
4729 case BO_And: return Success(LHS & RHS, E, Result);
4730 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4731 case BO_Or: return Success(LHS | RHS, E, Result);
4735 return Error(E, diag::note_expr_divide_by_zero);
4736 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4737 // not actually undefined behavior in C++11 due to a language defect.
4738 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4739 LHS.isSigned() && LHS.isMinSignedValue())
4740 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4741 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4744 // During constant-folding, a negative shift is an opposite shift. Such
4745 // a shift is not a constant expression.
4746 if (RHS.isSigned() && RHS.isNegative()) {
4747 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4753 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4754 // the shifted type.
4755 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4757 CCEDiag(E, diag::note_constexpr_large_shift)
4758 << RHS << E->getType() << LHS.getBitWidth();
4759 } else if (LHS.isSigned()) {
4760 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4761 // operand, and must not overflow the corresponding unsigned type.
4762 if (LHS.isNegative())
4763 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4764 else if (LHS.countLeadingZeros() < SA)
4765 CCEDiag(E, diag::note_constexpr_lshift_discards);
4768 return Success(LHS << SA, E, Result);
4771 // During constant-folding, a negative shift is an opposite shift. Such a
4772 // shift is not a constant expression.
4773 if (RHS.isSigned() && RHS.isNegative()) {
4774 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4780 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4782 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4784 CCEDiag(E, diag::note_constexpr_large_shift)
4785 << RHS << E->getType() << LHS.getBitWidth();
4787 return Success(LHS >> SA, E, Result);
4790 case BO_LT: return Success(LHS < RHS, E, Result);
4791 case BO_GT: return Success(LHS > RHS, E, Result);
4792 case BO_LE: return Success(LHS <= RHS, E, Result);
4793 case BO_GE: return Success(LHS >= RHS, E, Result);
4794 case BO_EQ: return Success(LHS == RHS, E, Result);
4795 case BO_NE: return Success(LHS != RHS, E, Result);
4799 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
4800 Job &job = Queue.back();
4803 case Job::AnyExprKind: {
4804 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4805 if (shouldEnqueue(Bop)) {
4806 job.Kind = Job::BinOpKind;
4807 enqueue(Bop->getLHS());
4812 EvaluateExpr(job.E, Result);
4817 case Job::BinOpKind: {
4818 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4819 bool SuppressRHSDiags = false;
4820 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
4824 if (SuppressRHSDiags)
4825 job.startSpeculativeEval(Info);
4826 job.LHSResult.swap(Result);
4827 job.Kind = Job::BinOpVisitedLHSKind;
4828 enqueue(Bop->getRHS());
4832 case Job::BinOpVisitedLHSKind: {
4833 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4836 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
4842 llvm_unreachable("Invalid Job::Kind!");
4845 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4846 if (E->isAssignmentOp())
4849 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4850 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
4852 QualType LHSTy = E->getLHS()->getType();
4853 QualType RHSTy = E->getRHS()->getType();
4855 if (LHSTy->isAnyComplexType()) {
4856 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4857 ComplexValue LHS, RHS;
4859 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4860 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4863 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4866 if (LHS.isComplexFloat()) {
4867 APFloat::cmpResult CR_r =
4868 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4869 APFloat::cmpResult CR_i =
4870 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4872 if (E->getOpcode() == BO_EQ)
4873 return Success((CR_r == APFloat::cmpEqual &&
4874 CR_i == APFloat::cmpEqual), E);
4876 assert(E->getOpcode() == BO_NE &&
4877 "Invalid complex comparison.");
4878 return Success(((CR_r == APFloat::cmpGreaterThan ||
4879 CR_r == APFloat::cmpLessThan ||
4880 CR_r == APFloat::cmpUnordered) ||
4881 (CR_i == APFloat::cmpGreaterThan ||
4882 CR_i == APFloat::cmpLessThan ||
4883 CR_i == APFloat::cmpUnordered)), E);
4886 if (E->getOpcode() == BO_EQ)
4887 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4888 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4890 assert(E->getOpcode() == BO_NE &&
4891 "Invalid compex comparison.");
4892 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4893 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4898 if (LHSTy->isRealFloatingType() &&
4899 RHSTy->isRealFloatingType()) {
4900 APFloat RHS(0.0), LHS(0.0);
4902 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4903 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4906 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4909 APFloat::cmpResult CR = LHS.compare(RHS);
4911 switch (E->getOpcode()) {
4913 llvm_unreachable("Invalid binary operator!");
4915 return Success(CR == APFloat::cmpLessThan, E);
4917 return Success(CR == APFloat::cmpGreaterThan, E);
4919 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4921 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4924 return Success(CR == APFloat::cmpEqual, E);
4926 return Success(CR == APFloat::cmpGreaterThan
4927 || CR == APFloat::cmpLessThan
4928 || CR == APFloat::cmpUnordered, E);
4932 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4933 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4934 LValue LHSValue, RHSValue;
4936 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4937 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4940 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4943 // Reject differing bases from the normal codepath; we special-case
4944 // comparisons to null.
4945 if (!HasSameBase(LHSValue, RHSValue)) {
4946 if (E->getOpcode() == BO_Sub) {
4947 // Handle &&A - &&B.
4948 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4950 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4951 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4952 if (!LHSExpr || !RHSExpr)
4954 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4955 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4956 if (!LHSAddrExpr || !RHSAddrExpr)
4958 // Make sure both labels come from the same function.
4959 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4960 RHSAddrExpr->getLabel()->getDeclContext())
4962 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4965 // Inequalities and subtractions between unrelated pointers have
4966 // unspecified or undefined behavior.
4967 if (!E->isEqualityOp())
4969 // A constant address may compare equal to the address of a symbol.
4970 // The one exception is that address of an object cannot compare equal
4971 // to a null pointer constant.
4972 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4973 (!RHSValue.Base && !RHSValue.Offset.isZero()))
4975 // It's implementation-defined whether distinct literals will have
4976 // distinct addresses. In clang, the result of such a comparison is
4977 // unspecified, so it is not a constant expression. However, we do know
4978 // that the address of a literal will be non-null.
4979 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4980 LHSValue.Base && RHSValue.Base)
4982 // We can't tell whether weak symbols will end up pointing to the same
4984 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4986 // Pointers with different bases cannot represent the same object.
4987 // (Note that clang defaults to -fmerge-all-constants, which can
4988 // lead to inconsistent results for comparisons involving the address
4989 // of a constant; this generally doesn't matter in practice.)
4990 return Success(E->getOpcode() == BO_NE, E);
4993 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4994 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4996 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4997 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4999 if (E->getOpcode() == BO_Sub) {
5000 // C++11 [expr.add]p6:
5001 // Unless both pointers point to elements of the same array object, or
5002 // one past the last element of the array object, the behavior is
5004 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5005 !AreElementsOfSameArray(getType(LHSValue.Base),
5006 LHSDesignator, RHSDesignator))
5007 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5009 QualType Type = E->getLHS()->getType();
5010 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
5012 CharUnits ElementSize;
5013 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
5016 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5017 // and produce incorrect results when it overflows. Such behavior
5018 // appears to be non-conforming, but is common, so perhaps we should
5019 // assume the standard intended for such cases to be undefined behavior
5020 // and check for them.
5022 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5023 // overflow in the final conversion to ptrdiff_t.
5025 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5027 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5029 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5030 APSInt TrueResult = (LHS - RHS) / ElemSize;
5031 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5033 if (Result.extend(65) != TrueResult)
5034 HandleOverflow(Info, E, TrueResult, E->getType());
5035 return Success(Result, E);
5038 // C++11 [expr.rel]p3:
5039 // Pointers to void (after pointer conversions) can be compared, with a
5040 // result defined as follows: If both pointers represent the same
5041 // address or are both the null pointer value, the result is true if the
5042 // operator is <= or >= and false otherwise; otherwise the result is
5044 // We interpret this as applying to pointers to *cv* void.
5045 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
5046 E->isRelationalOp())
5047 CCEDiag(E, diag::note_constexpr_void_comparison);
5049 // C++11 [expr.rel]p2:
5050 // - If two pointers point to non-static data members of the same object,
5051 // or to subobjects or array elements fo such members, recursively, the
5052 // pointer to the later declared member compares greater provided the
5053 // two members have the same access control and provided their class is
5056 // - Otherwise pointer comparisons are unspecified.
5057 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5058 E->isRelationalOp()) {
5061 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5062 RHSDesignator, WasArrayIndex);
5063 // At the point where the designators diverge, the comparison has a
5064 // specified value if:
5065 // - we are comparing array indices
5066 // - we are comparing fields of a union, or fields with the same access
5067 // Otherwise, the result is unspecified and thus the comparison is not a
5068 // constant expression.
5069 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5070 Mismatch < RHSDesignator.Entries.size()) {
5071 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5072 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5074 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5076 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5077 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5078 << RF->getParent() << RF;
5080 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5081 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5082 << LF->getParent() << LF;
5083 else if (!LF->getParent()->isUnion() &&
5084 LF->getAccess() != RF->getAccess())
5085 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5086 << LF << LF->getAccess() << RF << RF->getAccess()
5091 // The comparison here must be unsigned, and performed with the same
5092 // width as the pointer.
5093 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5094 uint64_t CompareLHS = LHSOffset.getQuantity();
5095 uint64_t CompareRHS = RHSOffset.getQuantity();
5096 assert(PtrSize <= 64 && "Unexpected pointer width");
5097 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5101 // If there is a base and this is a relational operator, we can only
5102 // compare pointers within the object in question; otherwise, the result
5103 // depends on where the object is located in memory.
5104 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5105 QualType BaseTy = getType(LHSValue.Base);
5106 if (BaseTy->isIncompleteType())
5108 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5109 uint64_t OffsetLimit = Size.getQuantity();
5110 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5114 switch (E->getOpcode()) {
5115 default: llvm_unreachable("missing comparison operator");
5116 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5117 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5118 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5119 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5120 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5121 case BO_NE: return Success(CompareLHS != CompareRHS, E);
5126 if (LHSTy->isMemberPointerType()) {
5127 assert(E->isEqualityOp() && "unexpected member pointer operation");
5128 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5130 MemberPtr LHSValue, RHSValue;
5132 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5133 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5136 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5139 // C++11 [expr.eq]p2:
5140 // If both operands are null, they compare equal. Otherwise if only one is
5141 // null, they compare unequal.
5142 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5143 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5144 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5147 // Otherwise if either is a pointer to a virtual member function, the
5148 // result is unspecified.
5149 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5150 if (MD->isVirtual())
5151 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5152 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5153 if (MD->isVirtual())
5154 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5156 // Otherwise they compare equal if and only if they would refer to the
5157 // same member of the same most derived object or the same subobject if
5158 // they were dereferenced with a hypothetical object of the associated
5160 bool Equal = LHSValue == RHSValue;
5161 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5164 if (LHSTy->isNullPtrType()) {
5165 assert(E->isComparisonOp() && "unexpected nullptr operation");
5166 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5167 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5168 // are compared, the result is true of the operator is <=, >= or ==, and
5170 BinaryOperator::Opcode Opcode = E->getOpcode();
5171 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5174 assert((!LHSTy->isIntegralOrEnumerationType() ||
5175 !RHSTy->isIntegralOrEnumerationType()) &&
5176 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5177 // We can't continue from here for non-integral types.
5178 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5181 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
5182 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5183 // result shall be the alignment of the referenced type."
5184 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5185 T = Ref->getPointeeType();
5187 // __alignof is defined to return the preferred alignment.
5188 return Info.Ctx.toCharUnitsFromBits(
5189 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5192 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
5193 E = E->IgnoreParens();
5195 // alignof decl is always accepted, even if it doesn't make sense: we default
5196 // to 1 in those cases.
5197 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5198 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5199 /*RefAsPointee*/true);
5201 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5202 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5203 /*RefAsPointee*/true);
5205 return GetAlignOfType(E->getType());
5209 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5210 /// a result as the expression's type.
5211 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5212 const UnaryExprOrTypeTraitExpr *E) {
5213 switch(E->getKind()) {
5214 case UETT_AlignOf: {
5215 if (E->isArgumentType())
5216 return Success(GetAlignOfType(E->getArgumentType()), E);
5218 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
5221 case UETT_VecStep: {
5222 QualType Ty = E->getTypeOfArgument();
5224 if (Ty->isVectorType()) {
5225 unsigned n = Ty->getAs<VectorType>()->getNumElements();
5227 // The vec_step built-in functions that take a 3-component
5228 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5232 return Success(n, E);
5234 return Success(1, E);
5238 QualType SrcTy = E->getTypeOfArgument();
5239 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5240 // the result is the size of the referenced type."
5241 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5242 SrcTy = Ref->getPointeeType();
5245 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
5247 return Success(Sizeof, E);
5251 llvm_unreachable("unknown expr/type trait");
5254 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
5256 unsigned n = OOE->getNumComponents();
5259 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
5260 for (unsigned i = 0; i != n; ++i) {
5261 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5262 switch (ON.getKind()) {
5263 case OffsetOfExpr::OffsetOfNode::Array: {
5264 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
5266 if (!EvaluateInteger(Idx, IdxResult, Info))
5268 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5271 CurrentType = AT->getElementType();
5272 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5273 Result += IdxResult.getSExtValue() * ElementSize;
5277 case OffsetOfExpr::OffsetOfNode::Field: {
5278 FieldDecl *MemberDecl = ON.getField();
5279 const RecordType *RT = CurrentType->getAs<RecordType>();
5282 RecordDecl *RD = RT->getDecl();
5283 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5284 unsigned i = MemberDecl->getFieldIndex();
5285 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
5286 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
5287 CurrentType = MemberDecl->getType().getNonReferenceType();
5291 case OffsetOfExpr::OffsetOfNode::Identifier:
5292 llvm_unreachable("dependent __builtin_offsetof");
5294 case OffsetOfExpr::OffsetOfNode::Base: {
5295 CXXBaseSpecifier *BaseSpec = ON.getBase();
5296 if (BaseSpec->isVirtual())
5299 // Find the layout of the class whose base we are looking into.
5300 const RecordType *RT = CurrentType->getAs<RecordType>();
5303 RecordDecl *RD = RT->getDecl();
5304 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5306 // Find the base class itself.
5307 CurrentType = BaseSpec->getType();
5308 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5312 // Add the offset to the base.
5313 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
5318 return Success(Result, OOE);
5321 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5322 switch (E->getOpcode()) {
5324 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5328 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5329 // If so, we could clear the diagnostic ID.
5330 return Visit(E->getSubExpr());
5332 // The result is just the value.
5333 return Visit(E->getSubExpr());
5335 if (!Visit(E->getSubExpr()))
5337 if (!Result.isInt()) return Error(E);
5338 const APSInt &Value = Result.getInt();
5339 if (Value.isSigned() && Value.isMinSignedValue())
5340 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5342 return Success(-Value, E);
5345 if (!Visit(E->getSubExpr()))
5347 if (!Result.isInt()) return Error(E);
5348 return Success(~Result.getInt(), E);
5352 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
5354 return Success(!bres, E);
5359 /// HandleCast - This is used to evaluate implicit or explicit casts where the
5360 /// result type is integer.
5361 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5362 const Expr *SubExpr = E->getSubExpr();
5363 QualType DestType = E->getType();
5364 QualType SrcType = SubExpr->getType();
5366 switch (E->getCastKind()) {
5367 case CK_BaseToDerived:
5368 case CK_DerivedToBase:
5369 case CK_UncheckedDerivedToBase:
5372 case CK_ArrayToPointerDecay:
5373 case CK_FunctionToPointerDecay:
5374 case CK_NullToPointer:
5375 case CK_NullToMemberPointer:
5376 case CK_BaseToDerivedMemberPointer:
5377 case CK_DerivedToBaseMemberPointer:
5378 case CK_ReinterpretMemberPointer:
5379 case CK_ConstructorConversion:
5380 case CK_IntegralToPointer:
5382 case CK_VectorSplat:
5383 case CK_IntegralToFloating:
5384 case CK_FloatingCast:
5385 case CK_CPointerToObjCPointerCast:
5386 case CK_BlockPointerToObjCPointerCast:
5387 case CK_AnyPointerToBlockPointerCast:
5388 case CK_ObjCObjectLValueCast:
5389 case CK_FloatingRealToComplex:
5390 case CK_FloatingComplexToReal:
5391 case CK_FloatingComplexCast:
5392 case CK_FloatingComplexToIntegralComplex:
5393 case CK_IntegralRealToComplex:
5394 case CK_IntegralComplexCast:
5395 case CK_IntegralComplexToFloatingComplex:
5396 llvm_unreachable("invalid cast kind for integral value");
5400 case CK_LValueBitCast:
5401 case CK_ARCProduceObject:
5402 case CK_ARCConsumeObject:
5403 case CK_ARCReclaimReturnedObject:
5404 case CK_ARCExtendBlockObject:
5405 case CK_CopyAndAutoreleaseBlockObject:
5408 case CK_UserDefinedConversion:
5409 case CK_LValueToRValue:
5410 case CK_AtomicToNonAtomic:
5411 case CK_NonAtomicToAtomic:
5413 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5415 case CK_MemberPointerToBoolean:
5416 case CK_PointerToBoolean:
5417 case CK_IntegralToBoolean:
5418 case CK_FloatingToBoolean:
5419 case CK_FloatingComplexToBoolean:
5420 case CK_IntegralComplexToBoolean: {
5422 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
5424 return Success(BoolResult, E);
5427 case CK_IntegralCast: {
5428 if (!Visit(SubExpr))
5431 if (!Result.isInt()) {
5432 // Allow casts of address-of-label differences if they are no-ops
5433 // or narrowing. (The narrowing case isn't actually guaranteed to
5434 // be constant-evaluatable except in some narrow cases which are hard
5435 // to detect here. We let it through on the assumption the user knows
5436 // what they are doing.)
5437 if (Result.isAddrLabelDiff())
5438 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
5439 // Only allow casts of lvalues if they are lossless.
5440 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5443 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5444 Result.getInt()), E);
5447 case CK_PointerToIntegral: {
5448 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5451 if (!EvaluatePointer(SubExpr, LV, Info))
5454 if (LV.getLValueBase()) {
5455 // Only allow based lvalue casts if they are lossless.
5456 // FIXME: Allow a larger integer size than the pointer size, and allow
5457 // narrowing back down to pointer width in subsequent integral casts.
5458 // FIXME: Check integer type's active bits, not its type size.
5459 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
5462 LV.Designator.setInvalid();
5463 LV.moveInto(Result);
5467 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5469 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
5472 case CK_IntegralComplexToReal: {
5474 if (!EvaluateComplex(SubExpr, C, Info))
5476 return Success(C.getComplexIntReal(), E);
5479 case CK_FloatingToIntegral: {
5481 if (!EvaluateFloat(SubExpr, F, Info))
5485 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5487 return Success(Value, E);
5491 llvm_unreachable("unknown cast resulting in integral value");
5494 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5495 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5497 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5499 if (!LV.isComplexInt())
5501 return Success(LV.getComplexIntReal(), E);
5504 return Visit(E->getSubExpr());
5507 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5508 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
5510 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5512 if (!LV.isComplexInt())
5514 return Success(LV.getComplexIntImag(), E);
5517 VisitIgnoredValue(E->getSubExpr());
5518 return Success(0, E);
5521 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5522 return Success(E->getPackLength(), E);
5525 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5526 return Success(E->getValue(), E);
5529 //===----------------------------------------------------------------------===//
5531 //===----------------------------------------------------------------------===//
5534 class FloatExprEvaluator
5535 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
5538 FloatExprEvaluator(EvalInfo &info, APFloat &result)
5539 : ExprEvaluatorBaseTy(info), Result(result) {}
5541 bool Success(const APValue &V, const Expr *e) {
5542 Result = V.getFloat();
5546 bool ZeroInitialization(const Expr *E) {
5547 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5551 bool VisitCallExpr(const CallExpr *E);
5553 bool VisitUnaryOperator(const UnaryOperator *E);
5554 bool VisitBinaryOperator(const BinaryOperator *E);
5555 bool VisitFloatingLiteral(const FloatingLiteral *E);
5556 bool VisitCastExpr(const CastExpr *E);
5558 bool VisitUnaryReal(const UnaryOperator *E);
5559 bool VisitUnaryImag(const UnaryOperator *E);
5561 // FIXME: Missing: array subscript of vector, member of vector
5563 } // end anonymous namespace
5565 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
5566 assert(E->isRValue() && E->getType()->isRealFloatingType());
5567 return FloatExprEvaluator(Info, Result).Visit(E);
5570 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
5574 llvm::APFloat &Result) {
5575 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5576 if (!S) return false;
5578 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5582 // Treat empty strings as if they were zero.
5583 if (S->getString().empty())
5584 fill = llvm::APInt(32, 0);
5585 else if (S->getString().getAsInteger(0, fill))
5589 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5591 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5595 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
5596 switch (E->isBuiltinCall()) {
5598 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5600 case Builtin::BI__builtin_huge_val:
5601 case Builtin::BI__builtin_huge_valf:
5602 case Builtin::BI__builtin_huge_vall:
5603 case Builtin::BI__builtin_inf:
5604 case Builtin::BI__builtin_inff:
5605 case Builtin::BI__builtin_infl: {
5606 const llvm::fltSemantics &Sem =
5607 Info.Ctx.getFloatTypeSemantics(E->getType());
5608 Result = llvm::APFloat::getInf(Sem);
5612 case Builtin::BI__builtin_nans:
5613 case Builtin::BI__builtin_nansf:
5614 case Builtin::BI__builtin_nansl:
5615 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5620 case Builtin::BI__builtin_nan:
5621 case Builtin::BI__builtin_nanf:
5622 case Builtin::BI__builtin_nanl:
5623 // If this is __builtin_nan() turn this into a nan, otherwise we
5624 // can't constant fold it.
5625 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5630 case Builtin::BI__builtin_fabs:
5631 case Builtin::BI__builtin_fabsf:
5632 case Builtin::BI__builtin_fabsl:
5633 if (!EvaluateFloat(E->getArg(0), Result, Info))
5636 if (Result.isNegative())
5637 Result.changeSign();
5640 case Builtin::BI__builtin_copysign:
5641 case Builtin::BI__builtin_copysignf:
5642 case Builtin::BI__builtin_copysignl: {
5644 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5645 !EvaluateFloat(E->getArg(1), RHS, Info))
5647 Result.copySign(RHS);
5653 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5654 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5656 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5658 Result = CV.FloatReal;
5662 return Visit(E->getSubExpr());
5665 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5666 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5668 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5670 Result = CV.FloatImag;
5674 VisitIgnoredValue(E->getSubExpr());
5675 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5676 Result = llvm::APFloat::getZero(Sem);
5680 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5681 switch (E->getOpcode()) {
5682 default: return Error(E);
5684 return EvaluateFloat(E->getSubExpr(), Result, Info);
5686 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5688 Result.changeSign();
5693 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5694 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5695 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5698 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5699 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5701 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
5704 switch (E->getOpcode()) {
5705 default: return Error(E);
5707 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5710 Result.add(RHS, APFloat::rmNearestTiesToEven);
5713 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5716 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5720 if (Result.isInfinity() || Result.isNaN())
5721 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5725 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5726 Result = E->getValue();
5730 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5731 const Expr* SubExpr = E->getSubExpr();
5733 switch (E->getCastKind()) {
5735 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5737 case CK_IntegralToFloating: {
5739 return EvaluateInteger(SubExpr, IntResult, Info) &&
5740 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5741 E->getType(), Result);
5744 case CK_FloatingCast: {
5745 if (!Visit(SubExpr))
5747 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5751 case CK_FloatingComplexToReal: {
5753 if (!EvaluateComplex(SubExpr, V, Info))
5755 Result = V.getComplexFloatReal();
5761 //===----------------------------------------------------------------------===//
5762 // Complex Evaluation (for float and integer)
5763 //===----------------------------------------------------------------------===//
5766 class ComplexExprEvaluator
5767 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5768 ComplexValue &Result;
5771 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5772 : ExprEvaluatorBaseTy(info), Result(Result) {}
5774 bool Success(const APValue &V, const Expr *e) {
5779 bool ZeroInitialization(const Expr *E);
5781 //===--------------------------------------------------------------------===//
5783 //===--------------------------------------------------------------------===//
5785 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5786 bool VisitCastExpr(const CastExpr *E);
5787 bool VisitBinaryOperator(const BinaryOperator *E);
5788 bool VisitUnaryOperator(const UnaryOperator *E);
5789 bool VisitInitListExpr(const InitListExpr *E);
5791 } // end anonymous namespace
5793 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5795 assert(E->isRValue() && E->getType()->isAnyComplexType());
5796 return ComplexExprEvaluator(Info, Result).Visit(E);
5799 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5800 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
5801 if (ElemTy->isRealFloatingType()) {
5802 Result.makeComplexFloat();
5803 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5804 Result.FloatReal = Zero;
5805 Result.FloatImag = Zero;
5807 Result.makeComplexInt();
5808 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5809 Result.IntReal = Zero;
5810 Result.IntImag = Zero;
5815 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5816 const Expr* SubExpr = E->getSubExpr();
5818 if (SubExpr->getType()->isRealFloatingType()) {
5819 Result.makeComplexFloat();
5820 APFloat &Imag = Result.FloatImag;
5821 if (!EvaluateFloat(SubExpr, Imag, Info))
5824 Result.FloatReal = APFloat(Imag.getSemantics());
5827 assert(SubExpr->getType()->isIntegerType() &&
5828 "Unexpected imaginary literal.");
5830 Result.makeComplexInt();
5831 APSInt &Imag = Result.IntImag;
5832 if (!EvaluateInteger(SubExpr, Imag, Info))
5835 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5840 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5842 switch (E->getCastKind()) {
5844 case CK_BaseToDerived:
5845 case CK_DerivedToBase:
5846 case CK_UncheckedDerivedToBase:
5849 case CK_ArrayToPointerDecay:
5850 case CK_FunctionToPointerDecay:
5851 case CK_NullToPointer:
5852 case CK_NullToMemberPointer:
5853 case CK_BaseToDerivedMemberPointer:
5854 case CK_DerivedToBaseMemberPointer:
5855 case CK_MemberPointerToBoolean:
5856 case CK_ReinterpretMemberPointer:
5857 case CK_ConstructorConversion:
5858 case CK_IntegralToPointer:
5859 case CK_PointerToIntegral:
5860 case CK_PointerToBoolean:
5862 case CK_VectorSplat:
5863 case CK_IntegralCast:
5864 case CK_IntegralToBoolean:
5865 case CK_IntegralToFloating:
5866 case CK_FloatingToIntegral:
5867 case CK_FloatingToBoolean:
5868 case CK_FloatingCast:
5869 case CK_CPointerToObjCPointerCast:
5870 case CK_BlockPointerToObjCPointerCast:
5871 case CK_AnyPointerToBlockPointerCast:
5872 case CK_ObjCObjectLValueCast:
5873 case CK_FloatingComplexToReal:
5874 case CK_FloatingComplexToBoolean:
5875 case CK_IntegralComplexToReal:
5876 case CK_IntegralComplexToBoolean:
5877 case CK_ARCProduceObject:
5878 case CK_ARCConsumeObject:
5879 case CK_ARCReclaimReturnedObject:
5880 case CK_ARCExtendBlockObject:
5881 case CK_CopyAndAutoreleaseBlockObject:
5882 llvm_unreachable("invalid cast kind for complex value");
5884 case CK_LValueToRValue:
5885 case CK_AtomicToNonAtomic:
5886 case CK_NonAtomicToAtomic:
5888 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5891 case CK_LValueBitCast:
5892 case CK_UserDefinedConversion:
5895 case CK_FloatingRealToComplex: {
5896 APFloat &Real = Result.FloatReal;
5897 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5900 Result.makeComplexFloat();
5901 Result.FloatImag = APFloat(Real.getSemantics());
5905 case CK_FloatingComplexCast: {
5906 if (!Visit(E->getSubExpr()))
5909 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5911 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5913 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5914 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5917 case CK_FloatingComplexToIntegralComplex: {
5918 if (!Visit(E->getSubExpr()))
5921 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5923 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5924 Result.makeComplexInt();
5925 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5926 To, Result.IntReal) &&
5927 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5928 To, Result.IntImag);
5931 case CK_IntegralRealToComplex: {
5932 APSInt &Real = Result.IntReal;
5933 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5936 Result.makeComplexInt();
5937 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5941 case CK_IntegralComplexCast: {
5942 if (!Visit(E->getSubExpr()))
5945 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5947 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5949 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5950 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
5954 case CK_IntegralComplexToFloatingComplex: {
5955 if (!Visit(E->getSubExpr()))
5958 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5960 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5961 Result.makeComplexFloat();
5962 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5963 To, Result.FloatReal) &&
5964 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5965 To, Result.FloatImag);
5969 llvm_unreachable("unknown cast resulting in complex value");
5972 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5973 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5974 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5976 bool LHSOK = Visit(E->getLHS());
5977 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5981 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5984 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5985 "Invalid operands to binary operator.");
5986 switch (E->getOpcode()) {
5987 default: return Error(E);
5989 if (Result.isComplexFloat()) {
5990 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5991 APFloat::rmNearestTiesToEven);
5992 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5993 APFloat::rmNearestTiesToEven);
5995 Result.getComplexIntReal() += RHS.getComplexIntReal();
5996 Result.getComplexIntImag() += RHS.getComplexIntImag();
6000 if (Result.isComplexFloat()) {
6001 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6002 APFloat::rmNearestTiesToEven);
6003 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6004 APFloat::rmNearestTiesToEven);
6006 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6007 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6011 if (Result.isComplexFloat()) {
6012 ComplexValue LHS = Result;
6013 APFloat &LHS_r = LHS.getComplexFloatReal();
6014 APFloat &LHS_i = LHS.getComplexFloatImag();
6015 APFloat &RHS_r = RHS.getComplexFloatReal();
6016 APFloat &RHS_i = RHS.getComplexFloatImag();
6018 APFloat Tmp = LHS_r;
6019 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6020 Result.getComplexFloatReal() = Tmp;
6022 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6023 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6026 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6027 Result.getComplexFloatImag() = Tmp;
6029 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6030 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6032 ComplexValue LHS = Result;
6033 Result.getComplexIntReal() =
6034 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6035 LHS.getComplexIntImag() * RHS.getComplexIntImag());
6036 Result.getComplexIntImag() =
6037 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6038 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6042 if (Result.isComplexFloat()) {
6043 ComplexValue LHS = Result;
6044 APFloat &LHS_r = LHS.getComplexFloatReal();
6045 APFloat &LHS_i = LHS.getComplexFloatImag();
6046 APFloat &RHS_r = RHS.getComplexFloatReal();
6047 APFloat &RHS_i = RHS.getComplexFloatImag();
6048 APFloat &Res_r = Result.getComplexFloatReal();
6049 APFloat &Res_i = Result.getComplexFloatImag();
6051 APFloat Den = RHS_r;
6052 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6053 APFloat Tmp = RHS_i;
6054 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6055 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6058 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6060 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6061 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6062 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6065 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6067 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6068 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6069 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6071 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6072 return Error(E, diag::note_expr_divide_by_zero);
6074 ComplexValue LHS = Result;
6075 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6076 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6077 Result.getComplexIntReal() =
6078 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6079 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6080 Result.getComplexIntImag() =
6081 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6082 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6090 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6091 // Get the operand value into 'Result'.
6092 if (!Visit(E->getSubExpr()))
6095 switch (E->getOpcode()) {
6101 // The result is always just the subexpr.
6104 if (Result.isComplexFloat()) {
6105 Result.getComplexFloatReal().changeSign();
6106 Result.getComplexFloatImag().changeSign();
6109 Result.getComplexIntReal() = -Result.getComplexIntReal();
6110 Result.getComplexIntImag() = -Result.getComplexIntImag();
6114 if (Result.isComplexFloat())
6115 Result.getComplexFloatImag().changeSign();
6117 Result.getComplexIntImag() = -Result.getComplexIntImag();
6122 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6123 if (E->getNumInits() == 2) {
6124 if (E->getType()->isComplexType()) {
6125 Result.makeComplexFloat();
6126 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6128 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6131 Result.makeComplexInt();
6132 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6134 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6139 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6142 //===----------------------------------------------------------------------===//
6143 // Void expression evaluation, primarily for a cast to void on the LHS of a
6145 //===----------------------------------------------------------------------===//
6148 class VoidExprEvaluator
6149 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6151 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6153 bool Success(const APValue &V, const Expr *e) { return true; }
6155 bool VisitCastExpr(const CastExpr *E) {
6156 switch (E->getCastKind()) {
6158 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6160 VisitIgnoredValue(E->getSubExpr());
6165 } // end anonymous namespace
6167 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6168 assert(E->isRValue() && E->getType()->isVoidType());
6169 return VoidExprEvaluator(Info).Visit(E);
6172 //===----------------------------------------------------------------------===//
6173 // Top level Expr::EvaluateAsRValue method.
6174 //===----------------------------------------------------------------------===//
6176 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
6177 // In C, function designators are not lvalues, but we evaluate them as if they
6179 if (E->isGLValue() || E->getType()->isFunctionType()) {
6181 if (!EvaluateLValue(E, LV, Info))
6183 LV.moveInto(Result);
6184 } else if (E->getType()->isVectorType()) {
6185 if (!EvaluateVector(E, Result, Info))
6187 } else if (E->getType()->isIntegralOrEnumerationType()) {
6188 if (!IntExprEvaluator(Info, Result).Visit(E))
6190 } else if (E->getType()->hasPointerRepresentation()) {
6192 if (!EvaluatePointer(E, LV, Info))
6194 LV.moveInto(Result);
6195 } else if (E->getType()->isRealFloatingType()) {
6196 llvm::APFloat F(0.0);
6197 if (!EvaluateFloat(E, F, Info))
6199 Result = APValue(F);
6200 } else if (E->getType()->isAnyComplexType()) {
6202 if (!EvaluateComplex(E, C, Info))
6205 } else if (E->getType()->isMemberPointerType()) {
6207 if (!EvaluateMemberPointer(E, P, Info))
6211 } else if (E->getType()->isArrayType()) {
6213 LV.set(E, Info.CurrentCall->Index);
6214 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
6216 Result = Info.CurrentCall->Temporaries[E];
6217 } else if (E->getType()->isRecordType()) {
6219 LV.set(E, Info.CurrentCall->Index);
6220 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6222 Result = Info.CurrentCall->Temporaries[E];
6223 } else if (E->getType()->isVoidType()) {
6224 if (Info.getLangOpts().CPlusPlus0x)
6225 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
6228 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6229 if (!EvaluateVoid(E, Info))
6231 } else if (Info.getLangOpts().CPlusPlus0x) {
6232 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
6235 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6242 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6243 /// cases, the in-place evaluation is essential, since later initializers for
6244 /// an object can indirectly refer to subobjects which were initialized earlier.
6245 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6246 const Expr *E, CheckConstantExpressionKind CCEK,
6247 bool AllowNonLiteralTypes) {
6248 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
6251 if (E->isRValue()) {
6252 // Evaluate arrays and record types in-place, so that later initializers can
6253 // refer to earlier-initialized members of the object.
6254 if (E->getType()->isArrayType())
6255 return EvaluateArray(E, This, Result, Info);
6256 else if (E->getType()->isRecordType())
6257 return EvaluateRecord(E, This, Result, Info);
6260 // For any other type, in-place evaluation is unimportant.
6261 return Evaluate(Result, Info, E);
6264 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6265 /// lvalue-to-rvalue cast if it is an lvalue.
6266 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
6267 if (!CheckLiteralType(Info, E))
6270 if (!::Evaluate(Result, Info, E))
6273 if (E->isGLValue()) {
6275 LV.setFrom(Info.Ctx, Result);
6276 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
6280 // Check this core constant expression is a constant expression.
6281 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
6284 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
6285 /// any crazy technique (that has nothing to do with language standards) that
6286 /// we want to. If this function returns true, it returns the folded constant
6287 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6288 /// will be applied to the result.
6289 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
6290 // Fast-path evaluations of integer literals, since we sometimes see files
6291 // containing vast quantities of these.
6292 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6293 Result.Val = APValue(APSInt(L->getValue(),
6294 L->getType()->isUnsignedIntegerType()));
6298 // FIXME: Evaluating values of large array and record types can cause
6299 // performance problems. Only do so in C++11 for now.
6300 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6301 !Ctx.getLangOpts().CPlusPlus0x)
6304 EvalInfo Info(Ctx, Result);
6305 return ::EvaluateAsRValue(Info, this, Result.Val);
6308 bool Expr::EvaluateAsBooleanCondition(bool &Result,
6309 const ASTContext &Ctx) const {
6311 return EvaluateAsRValue(Scratch, Ctx) &&
6312 HandleConversionToBool(Scratch.Val, Result);
6315 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6316 SideEffectsKind AllowSideEffects) const {
6317 if (!getType()->isIntegralOrEnumerationType())
6320 EvalResult ExprResult;
6321 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6322 (!AllowSideEffects && ExprResult.HasSideEffects))
6325 Result = ExprResult.Val.getInt();
6329 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
6330 EvalInfo Info(Ctx, Result);
6333 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6334 !CheckLValueConstantExpression(Info, getExprLoc(),
6335 Ctx.getLValueReferenceType(getType()), LV))
6338 LV.moveInto(Result.Val);
6342 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6344 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
6345 // FIXME: Evaluating initializers for large array and record types can cause
6346 // performance problems. Only do so in C++11 for now.
6347 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6348 !Ctx.getLangOpts().CPlusPlus0x)
6351 Expr::EvalStatus EStatus;
6352 EStatus.Diag = &Notes;
6354 EvalInfo InitInfo(Ctx, EStatus);
6355 InitInfo.setEvaluatingDecl(VD, Value);
6360 // C++11 [basic.start.init]p2:
6361 // Variables with static storage duration or thread storage duration shall be
6362 // zero-initialized before any other initialization takes place.
6363 // This behavior is not present in C.
6364 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
6365 !VD->getType()->isReferenceType()) {
6366 ImplicitValueInitExpr VIE(VD->getType());
6367 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6368 /*AllowNonLiteralTypes=*/true))
6372 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6373 /*AllowNonLiteralTypes=*/true) ||
6374 EStatus.HasSideEffects)
6377 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6381 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6382 /// constant folded, but discard the result.
6383 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
6385 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
6388 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
6389 return HasSideEffect(Ctx).Visit(this);
6392 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
6393 EvalResult EvalResult;
6394 bool Result = EvaluateAsRValue(EvalResult, Ctx);
6396 assert(Result && "Could not evaluate expression");
6397 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
6399 return EvalResult.Val.getInt();
6402 bool Expr::EvalResult::isGlobalLValue() const {
6403 assert(Val.isLValue());
6404 return IsGlobalLValue(Val.getLValueBase());
6408 /// isIntegerConstantExpr - this recursive routine will test if an expression is
6409 /// an integer constant expression.
6411 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6414 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6415 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6416 /// cast+dereference.
6418 // CheckICE - This function does the fundamental ICE checking: the returned
6419 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6420 // Note that to reduce code duplication, this helper does no evaluation
6421 // itself; the caller checks whether the expression is evaluatable, and
6422 // in the rare cases where CheckICE actually cares about the evaluated
6423 // value, it calls into Evalute.
6426 // 0: This expression is an ICE.
6427 // 1: This expression is not an ICE, but if it isn't evaluated, it's
6428 // a legal subexpression for an ICE. This return value is used to handle
6429 // the comma operator in C99 mode.
6430 // 2: This expression is not an ICE, and is not a legal subexpression for one.
6439 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6440 ICEDiag() : Val(0) {}
6445 static ICEDiag NoDiag() { return ICEDiag(); }
6447 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6448 Expr::EvalResult EVResult;
6449 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
6450 !EVResult.Val.isInt()) {
6451 return ICEDiag(2, E->getLocStart());
6456 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6457 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
6458 if (!E->getType()->isIntegralOrEnumerationType()) {
6459 return ICEDiag(2, E->getLocStart());
6462 switch (E->getStmtClass()) {
6463 #define ABSTRACT_STMT(Node)
6464 #define STMT(Node, Base) case Expr::Node##Class:
6465 #define EXPR(Node, Base)
6466 #include "clang/AST/StmtNodes.inc"
6467 case Expr::PredefinedExprClass:
6468 case Expr::FloatingLiteralClass:
6469 case Expr::ImaginaryLiteralClass:
6470 case Expr::StringLiteralClass:
6471 case Expr::ArraySubscriptExprClass:
6472 case Expr::MemberExprClass:
6473 case Expr::CompoundAssignOperatorClass:
6474 case Expr::CompoundLiteralExprClass:
6475 case Expr::ExtVectorElementExprClass:
6476 case Expr::DesignatedInitExprClass:
6477 case Expr::ImplicitValueInitExprClass:
6478 case Expr::ParenListExprClass:
6479 case Expr::VAArgExprClass:
6480 case Expr::AddrLabelExprClass:
6481 case Expr::StmtExprClass:
6482 case Expr::CXXMemberCallExprClass:
6483 case Expr::CUDAKernelCallExprClass:
6484 case Expr::CXXDynamicCastExprClass:
6485 case Expr::CXXTypeidExprClass:
6486 case Expr::CXXUuidofExprClass:
6487 case Expr::CXXNullPtrLiteralExprClass:
6488 case Expr::UserDefinedLiteralClass:
6489 case Expr::CXXThisExprClass:
6490 case Expr::CXXThrowExprClass:
6491 case Expr::CXXNewExprClass:
6492 case Expr::CXXDeleteExprClass:
6493 case Expr::CXXPseudoDestructorExprClass:
6494 case Expr::UnresolvedLookupExprClass:
6495 case Expr::DependentScopeDeclRefExprClass:
6496 case Expr::CXXConstructExprClass:
6497 case Expr::CXXBindTemporaryExprClass:
6498 case Expr::ExprWithCleanupsClass:
6499 case Expr::CXXTemporaryObjectExprClass:
6500 case Expr::CXXUnresolvedConstructExprClass:
6501 case Expr::CXXDependentScopeMemberExprClass:
6502 case Expr::UnresolvedMemberExprClass:
6503 case Expr::ObjCStringLiteralClass:
6504 case Expr::ObjCNumericLiteralClass:
6505 case Expr::ObjCArrayLiteralClass:
6506 case Expr::ObjCDictionaryLiteralClass:
6507 case Expr::ObjCEncodeExprClass:
6508 case Expr::ObjCMessageExprClass:
6509 case Expr::ObjCSelectorExprClass:
6510 case Expr::ObjCProtocolExprClass:
6511 case Expr::ObjCIvarRefExprClass:
6512 case Expr::ObjCPropertyRefExprClass:
6513 case Expr::ObjCSubscriptRefExprClass:
6514 case Expr::ObjCIsaExprClass:
6515 case Expr::ShuffleVectorExprClass:
6516 case Expr::BlockExprClass:
6517 case Expr::NoStmtClass:
6518 case Expr::OpaqueValueExprClass:
6519 case Expr::PackExpansionExprClass:
6520 case Expr::SubstNonTypeTemplateParmPackExprClass:
6521 case Expr::AsTypeExprClass:
6522 case Expr::ObjCIndirectCopyRestoreExprClass:
6523 case Expr::MaterializeTemporaryExprClass:
6524 case Expr::PseudoObjectExprClass:
6525 case Expr::AtomicExprClass:
6526 case Expr::InitListExprClass:
6527 case Expr::LambdaExprClass:
6528 return ICEDiag(2, E->getLocStart());
6530 case Expr::SizeOfPackExprClass:
6531 case Expr::GNUNullExprClass:
6532 // GCC considers the GNU __null value to be an integral constant expression.
6535 case Expr::SubstNonTypeTemplateParmExprClass:
6537 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6539 case Expr::ParenExprClass:
6540 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
6541 case Expr::GenericSelectionExprClass:
6542 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
6543 case Expr::IntegerLiteralClass:
6544 case Expr::CharacterLiteralClass:
6545 case Expr::ObjCBoolLiteralExprClass:
6546 case Expr::CXXBoolLiteralExprClass:
6547 case Expr::CXXScalarValueInitExprClass:
6548 case Expr::UnaryTypeTraitExprClass:
6549 case Expr::BinaryTypeTraitExprClass:
6550 case Expr::TypeTraitExprClass:
6551 case Expr::ArrayTypeTraitExprClass:
6552 case Expr::ExpressionTraitExprClass:
6553 case Expr::CXXNoexceptExprClass:
6555 case Expr::CallExprClass:
6556 case Expr::CXXOperatorCallExprClass: {
6557 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6558 // constant expressions, but they can never be ICEs because an ICE cannot
6559 // contain an operand of (pointer to) function type.
6560 const CallExpr *CE = cast<CallExpr>(E);
6561 if (CE->isBuiltinCall())
6562 return CheckEvalInICE(E, Ctx);
6563 return ICEDiag(2, E->getLocStart());
6565 case Expr::DeclRefExprClass: {
6566 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6568 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6569 if (Ctx.getLangOpts().CPlusPlus &&
6570 D && IsConstNonVolatile(D->getType())) {
6571 // Parameter variables are never constants. Without this check,
6572 // getAnyInitializer() can find a default argument, which leads
6574 if (isa<ParmVarDecl>(D))
6575 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6578 // A variable of non-volatile const-qualified integral or enumeration
6579 // type initialized by an ICE can be used in ICEs.
6580 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
6581 if (!Dcl->getType()->isIntegralOrEnumerationType())
6582 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6585 // Look for a declaration of this variable that has an initializer, and
6586 // check whether it is an ICE.
6587 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6590 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6593 return ICEDiag(2, E->getLocStart());
6595 case Expr::UnaryOperatorClass: {
6596 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6597 switch (Exp->getOpcode()) {
6604 // C99 6.6/3 allows increment and decrement within unevaluated
6605 // subexpressions of constant expressions, but they can never be ICEs
6606 // because an ICE cannot contain an lvalue operand.
6607 return ICEDiag(2, E->getLocStart());
6615 return CheckICE(Exp->getSubExpr(), Ctx);
6618 // OffsetOf falls through here.
6620 case Expr::OffsetOfExprClass: {
6621 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6622 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6623 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6624 // compliance: we should warn earlier for offsetof expressions with
6625 // array subscripts that aren't ICEs, and if the array subscripts
6626 // are ICEs, the value of the offsetof must be an integer constant.
6627 return CheckEvalInICE(E, Ctx);
6629 case Expr::UnaryExprOrTypeTraitExprClass: {
6630 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6631 if ((Exp->getKind() == UETT_SizeOf) &&
6632 Exp->getTypeOfArgument()->isVariableArrayType())
6633 return ICEDiag(2, E->getLocStart());
6636 case Expr::BinaryOperatorClass: {
6637 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6638 switch (Exp->getOpcode()) {
6652 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6653 // constant expressions, but they can never be ICEs because an ICE cannot
6654 // contain an lvalue operand.
6655 return ICEDiag(2, E->getLocStart());
6674 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6675 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6676 if (Exp->getOpcode() == BO_Div ||
6677 Exp->getOpcode() == BO_Rem) {
6678 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
6679 // we don't evaluate one.
6680 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
6681 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
6683 return ICEDiag(1, E->getLocStart());
6684 if (REval.isSigned() && REval.isAllOnesValue()) {
6685 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
6686 if (LEval.isMinSignedValue())
6687 return ICEDiag(1, E->getLocStart());
6691 if (Exp->getOpcode() == BO_Comma) {
6692 if (Ctx.getLangOpts().C99) {
6693 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6694 // if it isn't evaluated.
6695 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6696 return ICEDiag(1, E->getLocStart());
6698 // In both C89 and C++, commas in ICEs are illegal.
6699 return ICEDiag(2, E->getLocStart());
6702 if (LHSResult.Val >= RHSResult.Val)
6708 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6709 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6710 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6711 // Rare case where the RHS has a comma "side-effect"; we need
6712 // to actually check the condition to see whether the side
6713 // with the comma is evaluated.
6714 if ((Exp->getOpcode() == BO_LAnd) !=
6715 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
6720 if (LHSResult.Val >= RHSResult.Val)
6726 case Expr::ImplicitCastExprClass:
6727 case Expr::CStyleCastExprClass:
6728 case Expr::CXXFunctionalCastExprClass:
6729 case Expr::CXXStaticCastExprClass:
6730 case Expr::CXXReinterpretCastExprClass:
6731 case Expr::CXXConstCastExprClass:
6732 case Expr::ObjCBridgedCastExprClass: {
6733 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
6734 if (isa<ExplicitCastExpr>(E)) {
6735 if (const FloatingLiteral *FL
6736 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6737 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6738 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6739 APSInt IgnoredVal(DestWidth, !DestSigned);
6741 // If the value does not fit in the destination type, the behavior is
6742 // undefined, so we are not required to treat it as a constant
6744 if (FL->getValue().convertToInteger(IgnoredVal,
6745 llvm::APFloat::rmTowardZero,
6746 &Ignored) & APFloat::opInvalidOp)
6747 return ICEDiag(2, E->getLocStart());
6751 switch (cast<CastExpr>(E)->getCastKind()) {
6752 case CK_LValueToRValue:
6753 case CK_AtomicToNonAtomic:
6754 case CK_NonAtomicToAtomic:
6756 case CK_IntegralToBoolean:
6757 case CK_IntegralCast:
6758 return CheckICE(SubExpr, Ctx);
6760 return ICEDiag(2, E->getLocStart());
6763 case Expr::BinaryConditionalOperatorClass: {
6764 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6765 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6766 if (CommonResult.Val == 2) return CommonResult;
6767 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6768 if (FalseResult.Val == 2) return FalseResult;
6769 if (CommonResult.Val == 1) return CommonResult;
6770 if (FalseResult.Val == 1 &&
6771 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6774 case Expr::ConditionalOperatorClass: {
6775 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6776 // If the condition (ignoring parens) is a __builtin_constant_p call,
6777 // then only the true side is actually considered in an integer constant
6778 // expression, and it is fully evaluated. This is an important GNU
6779 // extension. See GCC PR38377 for discussion.
6780 if (const CallExpr *CallCE
6781 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6782 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6783 return CheckEvalInICE(E, Ctx);
6784 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6785 if (CondResult.Val == 2)
6788 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6789 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6791 if (TrueResult.Val == 2)
6793 if (FalseResult.Val == 2)
6795 if (CondResult.Val == 1)
6797 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6799 // Rare case where the diagnostics depend on which side is evaluated
6800 // Note that if we get here, CondResult is 0, and at least one of
6801 // TrueResult and FalseResult is non-zero.
6802 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6807 case Expr::CXXDefaultArgExprClass:
6808 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6809 case Expr::ChooseExprClass: {
6810 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6814 llvm_unreachable("Invalid StmtClass!");
6817 /// Evaluate an expression as a C++11 integral constant expression.
6818 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6820 llvm::APSInt *Value,
6821 SourceLocation *Loc) {
6822 if (!E->getType()->isIntegralOrEnumerationType()) {
6823 if (Loc) *Loc = E->getExprLoc();
6828 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6831 assert(Result.isInt() && "pointer cast to int is not an ICE");
6832 if (Value) *Value = Result.getInt();
6836 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6837 if (Ctx.getLangOpts().CPlusPlus0x)
6838 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6840 ICEDiag d = CheckICE(this, Ctx);
6842 if (Loc) *Loc = d.Loc;
6848 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6849 SourceLocation *Loc, bool isEvaluated) const {
6850 if (Ctx.getLangOpts().CPlusPlus0x)
6851 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6853 if (!isIntegerConstantExpr(Ctx, Loc))
6855 if (!EvaluateAsInt(Value, Ctx))
6856 llvm_unreachable("ICE cannot be evaluated!");
6860 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6861 return CheckICE(this, Ctx).Val == 0;
6864 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6865 SourceLocation *Loc) const {
6866 // We support this checking in C++98 mode in order to diagnose compatibility
6868 assert(Ctx.getLangOpts().CPlusPlus);
6870 // Build evaluation settings.
6871 Expr::EvalStatus Status;
6872 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6873 Status.Diag = &Diags;
6874 EvalInfo Info(Ctx, Status);
6877 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6879 if (!Diags.empty()) {
6880 IsConstExpr = false;
6881 if (Loc) *Loc = Diags[0].first;
6882 } else if (!IsConstExpr) {
6883 // FIXME: This shouldn't happen.
6884 if (Loc) *Loc = getExprLoc();
6890 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6891 llvm::SmallVectorImpl<
6892 PartialDiagnosticAt> &Diags) {
6893 // FIXME: It would be useful to check constexpr function templates, but at the
6894 // moment the constant expression evaluator cannot cope with the non-rigorous
6895 // ASTs which we build for dependent expressions.
6896 if (FD->isDependentContext())
6899 Expr::EvalStatus Status;
6900 Status.Diag = &Diags;
6902 EvalInfo Info(FD->getASTContext(), Status);
6903 Info.CheckingPotentialConstantExpression = true;
6905 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6906 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6908 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6909 // is a temporary being used as the 'this' pointer.
6911 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6912 This.set(&VIE, Info.CurrentCall->Index);
6914 ArrayRef<const Expr*> Args;
6916 SourceLocation Loc = FD->getLocation();
6919 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
6920 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6922 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6923 Args, FD->getBody(), Info, Scratch);
6925 return Diags.empty();