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 // Note that we intentionally use std::map here so that references to
291 // values are stable.
292 typedef std::map<const Expr*, APValue> MapTy;
293 typedef MapTy::const_iterator temp_iterator;
294 /// Temporaries - Temporary lvalues materialized within this stack frame.
297 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
298 const FunctionDecl *Callee, const LValue *This,
299 const APValue *Arguments);
303 /// A partial diagnostic which we might know in advance that we are not going
305 class OptionalDiagnostic {
306 PartialDiagnostic *Diag;
309 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
312 OptionalDiagnostic &operator<<(const T &v) {
318 OptionalDiagnostic &operator<<(const APSInt &I) {
320 llvm::SmallVector<char, 32> Buffer;
322 *Diag << StringRef(Buffer.data(), Buffer.size());
327 OptionalDiagnostic &operator<<(const APFloat &F) {
329 llvm::SmallVector<char, 32> Buffer;
331 *Diag << StringRef(Buffer.data(), Buffer.size());
337 /// EvalInfo - This is a private struct used by the evaluator to capture
338 /// information about a subexpression as it is folded. It retains information
339 /// about the AST context, but also maintains information about the folded
342 /// If an expression could be evaluated, it is still possible it is not a C
343 /// "integer constant expression" or constant expression. If not, this struct
344 /// captures information about how and why not.
346 /// One bit of information passed *into* the request for constant folding
347 /// indicates whether the subexpression is "evaluated" or not according to C
348 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
349 /// evaluate the expression regardless of what the RHS is, but C only allows
350 /// certain things in certain situations.
354 /// EvalStatus - Contains information about the evaluation.
355 Expr::EvalStatus &EvalStatus;
357 /// CurrentCall - The top of the constexpr call stack.
358 CallStackFrame *CurrentCall;
360 /// CallStackDepth - The number of calls in the call stack right now.
361 unsigned CallStackDepth;
363 /// NextCallIndex - The next call index to assign.
364 unsigned NextCallIndex;
366 /// BottomFrame - The frame in which evaluation started. This must be
367 /// initialized after CurrentCall and CallStackDepth.
368 CallStackFrame BottomFrame;
370 /// EvaluatingDecl - This is the declaration whose initializer is being
371 /// evaluated, if any.
372 const VarDecl *EvaluatingDecl;
374 /// EvaluatingDeclValue - This is the value being constructed for the
375 /// declaration whose initializer is being evaluated, if any.
376 APValue *EvaluatingDeclValue;
378 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
379 /// notes attached to it will also be stored, otherwise they will not be.
380 bool HasActiveDiagnostic;
382 /// CheckingPotentialConstantExpression - Are we checking whether the
383 /// expression is a potential constant expression? If so, some diagnostics
385 bool CheckingPotentialConstantExpression;
387 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
388 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
389 CallStackDepth(0), NextCallIndex(1),
390 BottomFrame(*this, SourceLocation(), 0, 0, 0),
391 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
392 CheckingPotentialConstantExpression(false) {}
394 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
396 EvaluatingDeclValue = &Value;
399 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
401 bool CheckCallLimit(SourceLocation Loc) {
402 // Don't perform any constexpr calls (other than the call we're checking)
403 // when checking a potential constant expression.
404 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
406 if (NextCallIndex == 0) {
407 // NextCallIndex has wrapped around.
408 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
411 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
413 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
414 << getLangOpts().ConstexprCallDepth;
418 CallStackFrame *getCallFrame(unsigned CallIndex) {
419 assert(CallIndex && "no call index in getCallFrame");
420 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
421 // be null in this loop.
422 CallStackFrame *Frame = CurrentCall;
423 while (Frame->Index > CallIndex)
424 Frame = Frame->Caller;
425 return (Frame->Index == CallIndex) ? Frame : 0;
429 /// Add a diagnostic to the diagnostics list.
430 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
431 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
432 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
433 return EvalStatus.Diag->back().second;
436 /// Add notes containing a call stack to the current point of evaluation.
437 void addCallStack(unsigned Limit);
440 /// Diagnose that the evaluation cannot be folded.
441 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
442 = diag::note_invalid_subexpr_in_const_expr,
443 unsigned ExtraNotes = 0) {
444 // If we have a prior diagnostic, it will be noting that the expression
445 // isn't a constant expression. This diagnostic is more important.
446 // FIXME: We might want to show both diagnostics to the user.
447 if (EvalStatus.Diag) {
448 unsigned CallStackNotes = CallStackDepth - 1;
449 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
451 CallStackNotes = std::min(CallStackNotes, Limit + 1);
452 if (CheckingPotentialConstantExpression)
455 HasActiveDiagnostic = true;
456 EvalStatus.Diag->clear();
457 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
458 addDiag(Loc, DiagId);
459 if (!CheckingPotentialConstantExpression)
461 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
463 HasActiveDiagnostic = false;
464 return OptionalDiagnostic();
467 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
468 = diag::note_invalid_subexpr_in_const_expr,
469 unsigned ExtraNotes = 0) {
471 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
476 /// Diagnose that the evaluation does not produce a C++11 core constant
478 template<typename LocArg>
479 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
480 = diag::note_invalid_subexpr_in_const_expr,
481 unsigned ExtraNotes = 0) {
482 // Don't override a previous diagnostic.
483 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
484 HasActiveDiagnostic = false;
485 return OptionalDiagnostic();
487 return Diag(Loc, DiagId, ExtraNotes);
490 /// Add a note to a prior diagnostic.
491 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
492 if (!HasActiveDiagnostic)
493 return OptionalDiagnostic();
494 return OptionalDiagnostic(&addDiag(Loc, DiagId));
497 /// Add a stack of notes to a prior diagnostic.
498 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
499 if (HasActiveDiagnostic) {
500 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
501 Diags.begin(), Diags.end());
505 /// Should we continue evaluation as much as possible after encountering a
506 /// construct which can't be folded?
507 bool keepEvaluatingAfterFailure() {
508 return CheckingPotentialConstantExpression &&
509 EvalStatus.Diag && EvalStatus.Diag->empty();
513 /// Object used to treat all foldable expressions as constant expressions.
514 struct FoldConstant {
517 explicit FoldConstant(EvalInfo &Info)
518 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
519 !Info.EvalStatus.HasSideEffects) {
521 // Treat the value we've computed since this object was created as constant.
522 void Fold(EvalInfo &Info) {
523 if (Enabled && !Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects)
525 Info.EvalStatus.Diag->clear();
529 /// RAII object used to suppress diagnostics and side-effects from a
530 /// speculative evaluation.
531 class SpeculativeEvaluationRAII {
533 Expr::EvalStatus Old;
536 SpeculativeEvaluationRAII(EvalInfo &Info,
537 llvm::SmallVectorImpl<PartialDiagnosticAt>
539 : Info(Info), Old(Info.EvalStatus) {
540 Info.EvalStatus.Diag = NewDiag;
542 ~SpeculativeEvaluationRAII() {
543 Info.EvalStatus = Old;
548 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
549 CheckSubobjectKind CSK) {
552 if (isOnePastTheEnd()) {
553 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
561 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
562 const Expr *E, uint64_t N) {
563 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
564 Info.CCEDiag(E, diag::note_constexpr_array_index)
565 << static_cast<int>(N) << /*array*/ 0
566 << static_cast<unsigned>(MostDerivedArraySize);
568 Info.CCEDiag(E, diag::note_constexpr_array_index)
569 << static_cast<int>(N) << /*non-array*/ 1;
573 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
574 const FunctionDecl *Callee, const LValue *This,
575 const APValue *Arguments)
576 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
577 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
578 Info.CurrentCall = this;
579 ++Info.CallStackDepth;
582 CallStackFrame::~CallStackFrame() {
583 assert(Info.CurrentCall == this && "calls retired out of order");
584 --Info.CallStackDepth;
585 Info.CurrentCall = Caller;
588 /// Produce a string describing the given constexpr call.
589 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
590 unsigned ArgIndex = 0;
591 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
592 !isa<CXXConstructorDecl>(Frame->Callee) &&
593 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
596 Out << *Frame->Callee << '(';
598 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
599 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
600 if (ArgIndex > (unsigned)IsMemberCall)
603 const ParmVarDecl *Param = *I;
604 const APValue &Arg = Frame->Arguments[ArgIndex];
605 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
607 if (ArgIndex == 0 && IsMemberCall)
608 Out << "->" << *Frame->Callee << '(';
614 void EvalInfo::addCallStack(unsigned Limit) {
615 // Determine which calls to skip, if any.
616 unsigned ActiveCalls = CallStackDepth - 1;
617 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
618 if (Limit && Limit < ActiveCalls) {
619 SkipStart = Limit / 2 + Limit % 2;
620 SkipEnd = ActiveCalls - Limit / 2;
623 // Walk the call stack and add the diagnostics.
624 unsigned CallIdx = 0;
625 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
626 Frame = Frame->Caller, ++CallIdx) {
628 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
629 if (CallIdx == SkipStart) {
630 // Note that we're skipping calls.
631 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
632 << unsigned(ActiveCalls - Limit);
637 llvm::SmallVector<char, 128> Buffer;
638 llvm::raw_svector_ostream Out(Buffer);
639 describeCall(Frame, Out);
640 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
645 struct ComplexValue {
650 APSInt IntReal, IntImag;
651 APFloat FloatReal, FloatImag;
653 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
655 void makeComplexFloat() { IsInt = false; }
656 bool isComplexFloat() const { return !IsInt; }
657 APFloat &getComplexFloatReal() { return FloatReal; }
658 APFloat &getComplexFloatImag() { return FloatImag; }
660 void makeComplexInt() { IsInt = true; }
661 bool isComplexInt() const { return IsInt; }
662 APSInt &getComplexIntReal() { return IntReal; }
663 APSInt &getComplexIntImag() { return IntImag; }
665 void moveInto(APValue &v) const {
666 if (isComplexFloat())
667 v = APValue(FloatReal, FloatImag);
669 v = APValue(IntReal, IntImag);
671 void setFrom(const APValue &v) {
672 assert(v.isComplexFloat() || v.isComplexInt());
673 if (v.isComplexFloat()) {
675 FloatReal = v.getComplexFloatReal();
676 FloatImag = v.getComplexFloatImag();
679 IntReal = v.getComplexIntReal();
680 IntImag = v.getComplexIntImag();
686 APValue::LValueBase Base;
689 SubobjectDesignator Designator;
691 const APValue::LValueBase getLValueBase() const { return Base; }
692 CharUnits &getLValueOffset() { return Offset; }
693 const CharUnits &getLValueOffset() const { return Offset; }
694 unsigned getLValueCallIndex() const { return CallIndex; }
695 SubobjectDesignator &getLValueDesignator() { return Designator; }
696 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
698 void moveInto(APValue &V) const {
699 if (Designator.Invalid)
700 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
702 V = APValue(Base, Offset, Designator.Entries,
703 Designator.IsOnePastTheEnd, CallIndex);
705 void setFrom(ASTContext &Ctx, const APValue &V) {
706 assert(V.isLValue());
707 Base = V.getLValueBase();
708 Offset = V.getLValueOffset();
709 CallIndex = V.getLValueCallIndex();
710 Designator = SubobjectDesignator(Ctx, V);
713 void set(APValue::LValueBase B, unsigned I = 0) {
715 Offset = CharUnits::Zero();
717 Designator = SubobjectDesignator(getType(B));
720 // Check that this LValue is not based on a null pointer. If it is, produce
721 // a diagnostic and mark the designator as invalid.
722 bool checkNullPointer(EvalInfo &Info, const Expr *E,
723 CheckSubobjectKind CSK) {
724 if (Designator.Invalid)
727 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
729 Designator.setInvalid();
735 // Check this LValue refers to an object. If not, set the designator to be
736 // invalid and emit a diagnostic.
737 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
738 // Outside C++11, do not build a designator referring to a subobject of
739 // any object: we won't use such a designator for anything.
740 if (!Info.getLangOpts().CPlusPlus0x)
741 Designator.setInvalid();
742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
775 /// Is this actually a member of some type derived from the relevant class?
776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
779 /// Get the class which the declaration actually lives in.
780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
788 void setFrom(const APValue &V) {
789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
805 /// Perform a cast towards the class of the Decl (either up or down the
807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
826 /// Perform a base-to-derived member pointer cast.
827 bool castToDerived(const CXXRecordDecl *Derived) {
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
834 if (!castBack(Derived))
837 DeclAndIsDerivedMember.setInt(false);
840 /// Perform a derived-to-base member pointer cast.
841 bool castToBase(const CXXRecordDecl *Base) {
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
850 return castBack(Base);
854 /// Compare two member pointers, which are assumed to be of the same type.
855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
860 return LHS.Path == RHS.Path;
863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
871 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
872 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
876 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
878 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
880 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
881 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
882 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
884 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
885 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
887 //===----------------------------------------------------------------------===//
889 //===----------------------------------------------------------------------===//
891 /// Should this call expression be treated as a string literal?
892 static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
898 static bool IsGlobalLValue(APValue::LValueBase B) {
899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
902 // ... a null pointer value, or a prvalue core constant expression of type
906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
914 const Expr *E = B.get<const Expr*>();
915 switch (E->getStmtClass()) {
918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
927 case Expr::CXXTypeidExprClass:
928 case Expr::CXXUuidofExprClass:
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
939 case Expr::ImplicitValueInitExprClass:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
950 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
954 Info.Note(VD->getLocation(), diag::note_declared_at);
956 Info.Note(Base.get<const Expr*>()->getExprLoc(),
957 diag::note_constexpr_temporary_here);
960 /// Check that this reference or pointer core constant expression is a valid
961 /// value for an address or reference constant expression. Return true if we
962 /// can fold this expression, whether or not it's a constant expression.
963 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
973 if (!IsGlobalLValue(Base)) {
974 if (Info.getLangOpts().CPlusPlus0x) {
975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
979 NoteLValueLocation(Info, Base);
983 // Don't allow references to temporaries to escape.
986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
990 // Check if this is a thread-local variable.
991 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
992 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
993 if (Var->isThreadSpecified())
998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1003 // A reference constant expression must refer to an object.
1005 // FIXME: diagnostic
1010 // Does this refer one past the end of some object?
1011 if (Designator.isOnePastTheEnd()) {
1012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
1014 << !Designator.Entries.empty() << !!VD << VD;
1015 NoteLValueLocation(Info, Base);
1021 /// Check that this core constant expression is of literal type, and if not,
1022 /// produce an appropriate diagnostic.
1023 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
1029 Info.Diag(E, diag::note_constexpr_nonliteral)
1032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1036 /// Check that this core constant expression value is a valid value for a
1037 /// constant expression. If not, report an appropriate diagnostic. Does not
1038 /// check that the expression is of literal type.
1039 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1051 if (!Value.hasArrayFiller())
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
1056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075 Value.getStructField(I->getFieldIndex())))
1080 if (Value.isLValue()) {
1082 LVal.setFrom(Info.Ctx, Value);
1083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1086 // Everything else is fine.
1090 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1091 return LVal.Base.dyn_cast<const ValueDecl*>();
1094 static bool IsLiteralLValue(const LValue &Value) {
1095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
1098 static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
1100 return Decl && Decl->isWeak();
1103 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
1106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
1111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
1114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1115 return !Decl || !Decl->isWeak();
1118 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1123 Result = Val.getInt().getBoolValue();
1125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
1128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1141 case APValue::Vector:
1142 case APValue::Array:
1143 case APValue::Struct:
1144 case APValue::Union:
1145 case APValue::AddrLabelDiff:
1149 llvm_unreachable("unknown APValue kind");
1152 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1156 if (!Evaluate(Val, Info, E))
1158 return HandleConversionToBool(Val, Result);
1161 template<typename T>
1162 static void HandleOverflow(EvalInfo &Info, const Expr *E,
1163 const T &SrcValue, QualType DestType) {
1164 Info.CCEDiag(E, diag::note_constexpr_overflow)
1165 << SrcValue << DestType;
1168 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1169 QualType SrcType, const APFloat &Value,
1170 QualType DestType, APSInt &Result) {
1171 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1172 // Determine whether we are converting to unsigned or signed.
1173 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1175 Result = APSInt(DestWidth, !DestSigned);
1177 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1178 & APFloat::opInvalidOp)
1179 HandleOverflow(Info, E, Value, DestType);
1183 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1184 QualType SrcType, QualType DestType,
1186 APFloat Value = Result;
1188 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1189 APFloat::rmNearestTiesToEven, &ignored)
1190 & APFloat::opOverflow)
1191 HandleOverflow(Info, E, Value, DestType);
1195 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1196 QualType DestType, QualType SrcType,
1198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1199 APSInt Result = Value;
1200 // Figure out if this is a truncate, extend or noop cast.
1201 // If the input is signed, do a sign extend, noop, or truncate.
1202 Result = Result.extOrTrunc(DestWidth);
1203 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1207 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1208 QualType SrcType, const APSInt &Value,
1209 QualType DestType, APFloat &Result) {
1210 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1211 if (Result.convertFromAPInt(Value, Value.isSigned(),
1212 APFloat::rmNearestTiesToEven)
1213 & APFloat::opOverflow)
1214 HandleOverflow(Info, E, Value, DestType);
1218 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1221 if (!Evaluate(SVal, Info, E))
1224 Res = SVal.getInt();
1227 if (SVal.isFloat()) {
1228 Res = SVal.getFloat().bitcastToAPInt();
1231 if (SVal.isVector()) {
1232 QualType VecTy = E->getType();
1233 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1234 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1235 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1236 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1237 Res = llvm::APInt::getNullValue(VecSize);
1238 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1239 APValue &Elt = SVal.getVectorElt(i);
1240 llvm::APInt EltAsInt;
1242 EltAsInt = Elt.getInt();
1243 } else if (Elt.isFloat()) {
1244 EltAsInt = Elt.getFloat().bitcastToAPInt();
1246 // Don't try to handle vectors of anything other than int or float
1247 // (not sure if it's possible to hit this case).
1248 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1251 unsigned BaseEltSize = EltAsInt.getBitWidth();
1253 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1259 // Give up if the input isn't an int, float, or vector. For example, we
1260 // reject "(v4i16)(intptr_t)&a".
1261 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1265 /// Cast an lvalue referring to a base subobject to a derived class, by
1266 /// truncating the lvalue's path to the given length.
1267 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1268 const RecordDecl *TruncatedType,
1269 unsigned TruncatedElements) {
1270 SubobjectDesignator &D = Result.Designator;
1272 // Check we actually point to a derived class object.
1273 if (TruncatedElements == D.Entries.size())
1275 assert(TruncatedElements >= D.MostDerivedPathLength &&
1276 "not casting to a derived class");
1277 if (!Result.checkSubobject(Info, E, CSK_Derived))
1280 // Truncate the path to the subobject, and remove any derived-to-base offsets.
1281 const RecordDecl *RD = TruncatedType;
1282 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1283 if (RD->isInvalidDecl()) return false;
1284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1286 if (isVirtualBaseClass(D.Entries[I]))
1287 Result.Offset -= Layout.getVBaseClassOffset(Base);
1289 Result.Offset -= Layout.getBaseClassOffset(Base);
1292 D.Entries.resize(TruncatedElements);
1296 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
1301 if (Derived->isInvalidDecl()) return false;
1302 RL = &Info.Ctx.getASTRecordLayout(Derived);
1305 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1306 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1310 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1311 const CXXRecordDecl *DerivedDecl,
1312 const CXXBaseSpecifier *Base) {
1313 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1315 if (!Base->isVirtual())
1316 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1318 SubobjectDesignator &D = Obj.Designator;
1322 // Extract most-derived object and corresponding type.
1323 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1324 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1327 // Find the virtual base class.
1328 if (DerivedDecl->isInvalidDecl()) return false;
1329 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1330 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1331 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1335 /// Update LVal to refer to the given field, which must be a member of the type
1336 /// currently described by LVal.
1337 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1338 const FieldDecl *FD,
1339 const ASTRecordLayout *RL = 0) {
1341 if (FD->getParent()->isInvalidDecl()) return false;
1342 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1347 LVal.addDecl(Info, E, FD);
1351 /// Update LVal to refer to the given indirect field.
1352 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1354 const IndirectFieldDecl *IFD) {
1355 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356 CE = IFD->chain_end(); C != CE; ++C)
1357 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1362 /// Get the size of the given type in char units.
1363 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1364 QualType Type, CharUnits &Size) {
1365 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1367 if (Type->isVoidType() || Type->isFunctionType()) {
1368 Size = CharUnits::One();
1372 if (!Type->isConstantSizeType()) {
1373 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1374 // FIXME: Better diagnostic.
1379 Size = Info.Ctx.getTypeSizeInChars(Type);
1383 /// Update a pointer value to model pointer arithmetic.
1384 /// \param Info - Information about the ongoing evaluation.
1385 /// \param E - The expression being evaluated, for diagnostic purposes.
1386 /// \param LVal - The pointer value to be updated.
1387 /// \param EltTy - The pointee type represented by LVal.
1388 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1389 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1390 LValue &LVal, QualType EltTy,
1391 int64_t Adjustment) {
1392 CharUnits SizeOfPointee;
1393 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
1396 // Compute the new offset in the appropriate width.
1397 LVal.Offset += Adjustment * SizeOfPointee;
1398 LVal.adjustIndex(Info, E, Adjustment);
1402 /// Update an lvalue to refer to a component of a complex number.
1403 /// \param Info - Information about the ongoing evaluation.
1404 /// \param LVal - The lvalue to be updated.
1405 /// \param EltTy - The complex number's component type.
1406 /// \param Imag - False for the real component, true for the imaginary.
1407 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1408 LValue &LVal, QualType EltTy,
1411 CharUnits SizeOfComponent;
1412 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1414 LVal.Offset += SizeOfComponent;
1416 LVal.addComplex(Info, E, EltTy, Imag);
1420 /// Try to evaluate the initializer for a variable declaration.
1421 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1423 CallStackFrame *Frame, APValue &Result) {
1424 // If this is a parameter to an active constexpr function call, perform
1425 // argument substitution.
1426 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1427 // Assume arguments of a potential constant expression are unknown
1428 // constant expressions.
1429 if (Info.CheckingPotentialConstantExpression)
1431 if (!Frame || !Frame->Arguments) {
1432 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1435 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1439 // Dig out the initializer, and use the declaration which it's attached to.
1440 const Expr *Init = VD->getAnyInitializer(VD);
1441 if (!Init || Init->isValueDependent()) {
1442 // If we're checking a potential constant expression, the variable could be
1443 // initialized later.
1444 if (!Info.CheckingPotentialConstantExpression)
1445 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1449 // If we're currently evaluating the initializer of this declaration, use that
1451 if (Info.EvaluatingDecl == VD) {
1452 Result = *Info.EvaluatingDeclValue;
1453 return !Result.isUninit();
1456 // Never evaluate the initializer of a weak variable. We can't be sure that
1457 // this is the definition which will be used.
1459 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1463 // Check that we can fold the initializer. In C++, we will have already done
1464 // this in the cases where it matters for conformance.
1465 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1466 if (!VD->evaluateValue(Notes)) {
1467 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
1468 Notes.size() + 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 Info.addNotes(Notes);
1472 } else if (!VD->checkInitIsICE()) {
1473 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
1474 Notes.size() + 1) << VD;
1475 Info.Note(VD->getLocation(), diag::note_declared_at);
1476 Info.addNotes(Notes);
1479 Result = *VD->getEvaluatedValue();
1483 static bool IsConstNonVolatile(QualType T) {
1484 Qualifiers Quals = T.getQualifiers();
1485 return Quals.hasConst() && !Quals.hasVolatile();
1488 /// Get the base index of the given base class within an APValue representing
1489 /// the given derived class.
1490 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1491 const CXXRecordDecl *Base) {
1492 Base = Base->getCanonicalDecl();
1494 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1495 E = Derived->bases_end(); I != E; ++I, ++Index) {
1496 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1500 llvm_unreachable("base class missing from derived class's bases list");
1503 /// Extract the value of a character from a string literal. CharType is used to
1504 /// determine the expected signedness of the result -- a string literal used to
1505 /// initialize an array of 'signed char' or 'unsigned char' might contain chars
1506 /// of the wrong signedness.
1507 static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1508 uint64_t Index, QualType CharType) {
1509 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1510 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1511 assert(S && "unexpected string literal expression kind");
1512 assert(CharType->isIntegerType() && "unexpected character type");
1514 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1515 CharType->isUnsignedIntegerType());
1516 if (Index < S->getLength())
1517 Value = S->getCodeUnit(Index);
1521 /// Extract the designated sub-object of an rvalue.
1522 static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1523 APValue &Obj, QualType ObjType,
1524 const SubobjectDesignator &Sub, QualType SubType) {
1526 // A diagnostic will have already been produced.
1528 if (Sub.isOnePastTheEnd()) {
1529 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1530 (unsigned)diag::note_constexpr_read_past_end :
1531 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1534 if (Sub.Entries.empty())
1536 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1537 // This object might be initialized later.
1541 // Walk the designator's path to find the subobject.
1542 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1543 if (ObjType->isArrayType()) {
1544 // Next subobject is an array element.
1545 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1546 assert(CAT && "vla in literal type?");
1547 uint64_t Index = Sub.Entries[I].ArrayIndex;
1548 if (CAT->getSize().ule(Index)) {
1549 // Note, it should not be possible to form a pointer with a valid
1550 // designator which points more than one past the end of the array.
1551 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1552 (unsigned)diag::note_constexpr_read_past_end :
1553 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1556 // An array object is represented as either an Array APValue or as an
1557 // LValue which refers to a string literal.
1558 if (O->isLValue()) {
1559 assert(I == N - 1 && "extracting subobject of character?");
1560 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1561 Obj = APValue(ExtractStringLiteralCharacter(
1562 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
1564 } else if (O->getArrayInitializedElts() > Index)
1565 O = &O->getArrayInitializedElt(Index);
1567 O = &O->getArrayFiller();
1568 ObjType = CAT->getElementType();
1569 } else if (ObjType->isAnyComplexType()) {
1570 // Next subobject is a complex number.
1571 uint64_t Index = Sub.Entries[I].ArrayIndex;
1573 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
1574 (unsigned)diag::note_constexpr_read_past_end :
1575 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1578 assert(I == N - 1 && "extracting subobject of scalar?");
1579 if (O->isComplexInt()) {
1580 Obj = APValue(Index ? O->getComplexIntImag()
1581 : O->getComplexIntReal());
1583 assert(O->isComplexFloat());
1584 Obj = APValue(Index ? O->getComplexFloatImag()
1585 : O->getComplexFloatReal());
1588 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1589 if (Field->isMutable()) {
1590 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
1592 Info.Note(Field->getLocation(), diag::note_declared_at);
1596 // Next subobject is a class, struct or union field.
1597 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1598 if (RD->isUnion()) {
1599 const FieldDecl *UnionField = O->getUnionField();
1601 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1602 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
1603 << Field << !UnionField << UnionField;
1606 O = &O->getUnionValue();
1608 O = &O->getStructField(Field->getFieldIndex());
1609 ObjType = Field->getType();
1611 if (ObjType.isVolatileQualified()) {
1612 if (Info.getLangOpts().CPlusPlus) {
1613 // FIXME: Include a description of the path to the volatile subobject.
1614 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
1616 Info.Note(Field->getLocation(), diag::note_declared_at);
1618 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
1623 // Next subobject is a base class.
1624 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1625 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1626 O = &O->getStructBase(getBaseIndex(Derived, Base));
1627 ObjType = Info.Ctx.getRecordType(Base);
1630 if (O->isUninit()) {
1631 if (!Info.CheckingPotentialConstantExpression)
1632 Info.Diag(E, diag::note_constexpr_read_uninit);
1637 // This may look super-stupid, but it serves an important purpose: if we just
1638 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1639 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1640 // object, which is destroyed by Tmp's destructor.
1647 /// Find the position where two subobject designators diverge, or equivalently
1648 /// the length of the common initial subsequence.
1649 static unsigned FindDesignatorMismatch(QualType ObjType,
1650 const SubobjectDesignator &A,
1651 const SubobjectDesignator &B,
1652 bool &WasArrayIndex) {
1653 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1654 for (/**/; I != N; ++I) {
1655 if (!ObjType.isNull() &&
1656 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
1657 // Next subobject is an array element.
1658 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1659 WasArrayIndex = true;
1662 if (ObjType->isAnyComplexType())
1663 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1665 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
1667 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1668 WasArrayIndex = false;
1671 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1672 // Next subobject is a field.
1673 ObjType = FD->getType();
1675 // Next subobject is a base class.
1676 ObjType = QualType();
1679 WasArrayIndex = false;
1683 /// Determine whether the given subobject designators refer to elements of the
1684 /// same array object.
1685 static bool AreElementsOfSameArray(QualType ObjType,
1686 const SubobjectDesignator &A,
1687 const SubobjectDesignator &B) {
1688 if (A.Entries.size() != B.Entries.size())
1691 bool IsArray = A.MostDerivedArraySize != 0;
1692 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1693 // A is a subobject of the array element.
1696 // If A (and B) designates an array element, the last entry will be the array
1697 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1698 // of length 1' case, and the entire path must match.
1700 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1701 return CommonLength >= A.Entries.size() - IsArray;
1704 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1705 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1706 /// for looking up the glvalue referred to by an entity of reference type.
1708 /// \param Info - Information about the ongoing evaluation.
1709 /// \param Conv - The expression for which we are performing the conversion.
1710 /// Used for diagnostics.
1711 /// \param Type - The type we expect this conversion to produce, before
1712 /// stripping cv-qualifiers in the case of a non-clas type.
1713 /// \param LVal - The glvalue on which we are attempting to perform this action.
1714 /// \param RVal - The produced value will be placed here.
1715 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1717 const LValue &LVal, APValue &RVal) {
1718 if (LVal.Designator.Invalid)
1719 // A diagnostic will have already been produced.
1722 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1725 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1726 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1730 CallStackFrame *Frame = 0;
1731 if (LVal.CallIndex) {
1732 Frame = Info.getCallFrame(LVal.CallIndex);
1734 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1735 NoteLValueLocation(Info, LVal.Base);
1740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1741 // is not a constant expression (even if the object is non-volatile). We also
1742 // apply this rule to C++98, in order to conform to the expected 'volatile'
1744 if (Type.isVolatileQualified()) {
1745 if (Info.getLangOpts().CPlusPlus)
1746 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
1752 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1753 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1754 // In C++11, constexpr, non-volatile variables initialized with constant
1755 // expressions are constant expressions too. Inside constexpr functions,
1756 // parameters are constant expressions even if they're non-const.
1757 // In C, such things can also be folded, although they are not ICEs.
1758 const VarDecl *VD = dyn_cast<VarDecl>(D);
1760 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1763 if (!VD || VD->isInvalidDecl()) {
1768 // DR1313: If the object is volatile-qualified but the glvalue was not,
1769 // behavior is undefined so the result is not a constant expression.
1770 QualType VT = VD->getType();
1771 if (VT.isVolatileQualified()) {
1772 if (Info.getLangOpts().CPlusPlus) {
1773 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1774 Info.Note(VD->getLocation(), diag::note_declared_at);
1781 if (!isa<ParmVarDecl>(VD)) {
1782 if (VD->isConstexpr()) {
1783 // OK, we can read this variable.
1784 } else if (VT->isIntegralOrEnumerationType()) {
1785 if (!VT.isConstQualified()) {
1786 if (Info.getLangOpts().CPlusPlus) {
1787 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1788 Info.Note(VD->getLocation(), diag::note_declared_at);
1794 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1795 // We support folding of const floating-point types, in order to make
1796 // static const data members of such types (supported as an extension)
1798 if (Info.getLangOpts().CPlusPlus0x) {
1799 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1800 Info.Note(VD->getLocation(), diag::note_declared_at);
1805 // FIXME: Allow folding of values of any literal type in all languages.
1806 if (Info.getLangOpts().CPlusPlus0x) {
1807 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1808 Info.Note(VD->getLocation(), diag::note_declared_at);
1816 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1819 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1820 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1822 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1823 // conversion. This happens when the declaration and the lvalue should be
1824 // considered synonymous, for instance when initializing an array of char
1825 // from a string literal. Continue as if the initializer lvalue was the
1826 // value we were originally given.
1827 assert(RVal.getLValueOffset().isZero() &&
1828 "offset for lvalue init of non-reference");
1829 Base = RVal.getLValueBase().get<const Expr*>();
1831 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1832 Frame = Info.getCallFrame(CallIndex);
1834 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
1835 NoteLValueLocation(Info, RVal.getLValueBase());
1843 // Volatile temporary objects cannot be read in constant expressions.
1844 if (Base->getType().isVolatileQualified()) {
1845 if (Info.getLangOpts().CPlusPlus) {
1846 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1847 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1855 // If this is a temporary expression with a nontrivial initializer, grab the
1856 // value from the relevant stack frame.
1857 RVal = Frame->Temporaries[Base];
1858 } else if (const CompoundLiteralExpr *CLE
1859 = dyn_cast<CompoundLiteralExpr>(Base)) {
1860 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1861 // initializer until now for such expressions. Such an expression can't be
1862 // an ICE in C, so this only matters for fold.
1863 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1864 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1866 } else if (isa<StringLiteral>(Base)) {
1867 // We represent a string literal array as an lvalue pointing at the
1868 // corresponding expression, rather than building an array of chars.
1869 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1870 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
1872 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
1876 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1880 /// Build an lvalue for the object argument of a member function call.
1881 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1883 if (Object->getType()->isPointerType())
1884 return EvaluatePointer(Object, This, Info);
1886 if (Object->isGLValue())
1887 return EvaluateLValue(Object, This, Info);
1889 if (Object->getType()->isLiteralType())
1890 return EvaluateTemporary(Object, This, Info);
1895 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
1896 /// lvalue referring to the result.
1898 /// \param Info - Information about the ongoing evaluation.
1899 /// \param BO - The member pointer access operation.
1900 /// \param LV - Filled in with a reference to the resulting object.
1901 /// \param IncludeMember - Specifies whether the member itself is included in
1902 /// the resulting LValue subobject designator. This is not possible when
1903 /// creating a bound member function.
1904 /// \return The field or method declaration to which the member pointer refers,
1905 /// or 0 if evaluation fails.
1906 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1907 const BinaryOperator *BO,
1909 bool IncludeMember = true) {
1910 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1912 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1913 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1917 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1920 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1921 // member value, the behavior is undefined.
1922 if (!MemPtr.getDecl())
1928 if (MemPtr.isDerivedMember()) {
1929 // This is a member of some derived class. Truncate LV appropriately.
1930 // The end of the derived-to-base path for the base object must match the
1931 // derived-to-base path for the member pointer.
1932 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1933 LV.Designator.Entries.size())
1935 unsigned PathLengthToMember =
1936 LV.Designator.Entries.size() - MemPtr.Path.size();
1937 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1938 const CXXRecordDecl *LVDecl = getAsBaseClass(
1939 LV.Designator.Entries[PathLengthToMember + I]);
1940 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1941 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1945 // Truncate the lvalue to the appropriate derived class.
1946 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1947 PathLengthToMember))
1949 } else if (!MemPtr.Path.empty()) {
1950 // Extend the LValue path with the member pointer's path.
1951 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1952 MemPtr.Path.size() + IncludeMember);
1954 // Walk down to the appropriate base class.
1955 QualType LVType = BO->getLHS()->getType();
1956 if (const PointerType *PT = LVType->getAs<PointerType>())
1957 LVType = PT->getPointeeType();
1958 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1959 assert(RD && "member pointer access on non-class-type expression");
1960 // The first class in the path is that of the lvalue.
1961 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1962 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1963 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1967 // Finally cast to the class containing the member.
1968 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1972 // Add the member. Note that we cannot build bound member functions here.
1973 if (IncludeMember) {
1974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1975 if (!HandleLValueMember(Info, BO, LV, FD))
1977 } else if (const IndirectFieldDecl *IFD =
1978 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1979 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1982 llvm_unreachable("can't construct reference to bound member function");
1986 return MemPtr.getDecl();
1989 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1990 /// the provided lvalue, which currently refers to the base object.
1991 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1993 SubobjectDesignator &D = Result.Designator;
1994 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1997 QualType TargetQT = E->getType();
1998 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1999 TargetQT = PT->getPointeeType();
2001 // Check this cast lands within the final derived-to-base subobject path.
2002 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2003 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2004 << D.MostDerivedType << TargetQT;
2008 // Check the type of the final cast. We don't need to check the path,
2009 // since a cast can only be formed if the path is unique.
2010 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
2011 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2012 const CXXRecordDecl *FinalType;
2013 if (NewEntriesSize == D.MostDerivedPathLength)
2014 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2016 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
2017 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2018 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
2019 << D.MostDerivedType << TargetQT;
2023 // Truncate the lvalue to the appropriate derived class.
2024 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
2028 enum EvalStmtResult {
2029 /// Evaluation failed.
2031 /// Hit a 'return' statement.
2033 /// Evaluation succeeded.
2038 // Evaluate a statement.
2039 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
2041 switch (S->getStmtClass()) {
2045 case Stmt::NullStmtClass:
2046 case Stmt::DeclStmtClass:
2047 return ESR_Succeeded;
2049 case Stmt::ReturnStmtClass: {
2050 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
2051 if (!Evaluate(Result, Info, RetExpr))
2053 return ESR_Returned;
2056 case Stmt::CompoundStmtClass: {
2057 const CompoundStmt *CS = cast<CompoundStmt>(S);
2058 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2059 BE = CS->body_end(); BI != BE; ++BI) {
2060 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2061 if (ESR != ESR_Succeeded)
2064 return ESR_Succeeded;
2069 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2070 /// default constructor. If so, we'll fold it whether or not it's marked as
2071 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
2072 /// so we need special handling.
2073 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
2074 const CXXConstructorDecl *CD,
2075 bool IsValueInitialization) {
2076 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2079 // Value-initialization does not call a trivial default constructor, so such a
2080 // call is a core constant expression whether or not the constructor is
2082 if (!CD->isConstexpr() && !IsValueInitialization) {
2083 if (Info.getLangOpts().CPlusPlus0x) {
2084 // FIXME: If DiagDecl is an implicitly-declared special member function,
2085 // we should be much more explicit about why it's not constexpr.
2086 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2087 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2088 Info.Note(CD->getLocation(), diag::note_declared_at);
2090 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2096 /// CheckConstexprFunction - Check that a function can be called in a constant
2098 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2099 const FunctionDecl *Declaration,
2100 const FunctionDecl *Definition) {
2101 // Potential constant expressions can contain calls to declared, but not yet
2102 // defined, constexpr functions.
2103 if (Info.CheckingPotentialConstantExpression && !Definition &&
2104 Declaration->isConstexpr())
2107 // Can we evaluate this function call?
2108 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2111 if (Info.getLangOpts().CPlusPlus0x) {
2112 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
2113 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2114 // should be much more explicit about why it's not constexpr.
2115 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2116 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2120 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2126 typedef SmallVector<APValue, 8> ArgVector;
2129 /// EvaluateArgs - Evaluate the arguments to a function call.
2130 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2132 bool Success = true;
2133 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
2135 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2136 // If we're checking for a potential constant expression, evaluate all
2137 // initializers even if some of them fail.
2138 if (!Info.keepEvaluatingAfterFailure())
2146 /// Evaluate a function call.
2147 static bool HandleFunctionCall(SourceLocation CallLoc,
2148 const FunctionDecl *Callee, const LValue *This,
2149 ArrayRef<const Expr*> Args, const Stmt *Body,
2150 EvalInfo &Info, APValue &Result) {
2151 ArgVector ArgValues(Args.size());
2152 if (!EvaluateArgs(Args, ArgValues, Info))
2155 if (!Info.CheckCallLimit(CallLoc))
2158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
2159 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2162 /// Evaluate a constructor call.
2163 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
2164 ArrayRef<const Expr*> Args,
2165 const CXXConstructorDecl *Definition,
2166 EvalInfo &Info, APValue &Result) {
2167 ArgVector ArgValues(Args.size());
2168 if (!EvaluateArgs(Args, ArgValues, Info))
2171 if (!Info.CheckCallLimit(CallLoc))
2174 const CXXRecordDecl *RD = Definition->getParent();
2175 if (RD->getNumVBases()) {
2176 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2180 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
2182 // If it's a delegating constructor, just delegate.
2183 if (Definition->isDelegatingConstructor()) {
2184 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
2185 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
2188 // For a trivial copy or move constructor, perform an APValue copy. This is
2189 // essential for unions, where the operations performed by the constructor
2190 // cannot be represented by ctor-initializers.
2191 if (Definition->isDefaulted() &&
2192 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2193 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
2195 RHS.setFrom(Info.Ctx, ArgValues[0]);
2196 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2200 // Reserve space for the struct members.
2201 if (!RD->isUnion() && Result.isUninit())
2202 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2203 std::distance(RD->field_begin(), RD->field_end()));
2205 if (RD->isInvalidDecl()) return false;
2206 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2208 bool Success = true;
2209 unsigned BasesSeen = 0;
2211 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2213 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2214 E = Definition->init_end(); I != E; ++I) {
2215 LValue Subobject = This;
2216 APValue *Value = &Result;
2218 // Determine the subobject to initialize.
2219 if ((*I)->isBaseInitializer()) {
2220 QualType BaseType((*I)->getBaseClass(), 0);
2222 // Non-virtual base classes are initialized in the order in the class
2223 // definition. We have already checked for virtual base classes.
2224 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2225 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2226 "base class initializers not in expected order");
2229 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2230 BaseType->getAsCXXRecordDecl(), &Layout))
2232 Value = &Result.getStructBase(BasesSeen++);
2233 } else if (FieldDecl *FD = (*I)->getMember()) {
2234 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2236 if (RD->isUnion()) {
2237 Result = APValue(FD);
2238 Value = &Result.getUnionValue();
2240 Value = &Result.getStructField(FD->getFieldIndex());
2242 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
2243 // Walk the indirect field decl's chain to find the object to initialize,
2244 // and make sure we've initialized every step along it.
2245 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2246 CE = IFD->chain_end();
2248 FieldDecl *FD = cast<FieldDecl>(*C);
2249 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2250 // Switch the union field if it differs. This happens if we had
2251 // preceding zero-initialization, and we're now initializing a union
2252 // subobject other than the first.
2253 // FIXME: In this case, the values of the other subobjects are
2254 // specified, since zero-initialization sets all padding bits to zero.
2255 if (Value->isUninit() ||
2256 (Value->isUnion() && Value->getUnionField() != FD)) {
2258 *Value = APValue(FD);
2260 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2261 std::distance(CD->field_begin(), CD->field_end()));
2263 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2266 Value = &Value->getUnionValue();
2268 Value = &Value->getStructField(FD->getFieldIndex());
2271 llvm_unreachable("unknown base initializer kind");
2274 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2275 (*I)->isBaseInitializer()
2276 ? CCEK_Constant : CCEK_MemberInit)) {
2277 // If we're checking for a potential constant expression, evaluate all
2278 // initializers even if some of them fail.
2279 if (!Info.keepEvaluatingAfterFailure())
2288 //===----------------------------------------------------------------------===//
2289 // Generic Evaluation
2290 //===----------------------------------------------------------------------===//
2293 // FIXME: RetTy is always bool. Remove it.
2294 template <class Derived, typename RetTy=bool>
2295 class ExprEvaluatorBase
2296 : public ConstStmtVisitor<Derived, RetTy> {
2298 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
2299 return static_cast<Derived*>(this)->Success(V, E);
2301 RetTy DerivedZeroInitialization(const Expr *E) {
2302 return static_cast<Derived*>(this)->ZeroInitialization(E);
2305 // Check whether a conditional operator with a non-constant condition is a
2306 // potential constant expression. If neither arm is a potential constant
2307 // expression, then the conditional operator is not either.
2308 template<typename ConditionalOperator>
2309 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2310 assert(Info.CheckingPotentialConstantExpression);
2312 // Speculatively evaluate both arms.
2314 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2315 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2317 StmtVisitorTy::Visit(E->getFalseExpr());
2322 StmtVisitorTy::Visit(E->getTrueExpr());
2327 Error(E, diag::note_constexpr_conditional_never_const);
2331 template<typename ConditionalOperator>
2332 bool HandleConditionalOperator(const ConditionalOperator *E) {
2334 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2335 if (Info.CheckingPotentialConstantExpression)
2336 CheckPotentialConstantConditional(E);
2340 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2341 return StmtVisitorTy::Visit(EvalExpr);
2346 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2347 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2349 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2350 return Info.CCEDiag(E, D);
2353 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2356 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2358 EvalInfo &getEvalInfo() { return Info; }
2360 /// Report an evaluation error. This should only be called when an error is
2361 /// first discovered. When propagating an error, just return false.
2362 bool Error(const Expr *E, diag::kind D) {
2366 bool Error(const Expr *E) {
2367 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2370 RetTy VisitStmt(const Stmt *) {
2371 llvm_unreachable("Expression evaluator should not be called on stmts");
2373 RetTy VisitExpr(const Expr *E) {
2377 RetTy VisitParenExpr(const ParenExpr *E)
2378 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2379 RetTy VisitUnaryExtension(const UnaryOperator *E)
2380 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2381 RetTy VisitUnaryPlus(const UnaryOperator *E)
2382 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2383 RetTy VisitChooseExpr(const ChooseExpr *E)
2384 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2385 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2386 { return StmtVisitorTy::Visit(E->getResultExpr()); }
2387 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2388 { return StmtVisitorTy::Visit(E->getReplacement()); }
2389 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2390 { return StmtVisitorTy::Visit(E->getExpr()); }
2391 // We cannot create any objects for which cleanups are required, so there is
2392 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2393 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2394 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2396 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2397 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2398 return static_cast<Derived*>(this)->VisitCastExpr(E);
2400 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2402 return static_cast<Derived*>(this)->VisitCastExpr(E);
2405 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2406 switch (E->getOpcode()) {
2411 VisitIgnoredValue(E->getLHS());
2412 return StmtVisitorTy::Visit(E->getRHS());
2417 if (!HandleMemberPointerAccess(Info, E, Obj))
2420 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2422 return DerivedSuccess(Result, E);
2427 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2428 // Evaluate and cache the common expression. We treat it as a temporary,
2429 // even though it's not quite the same thing.
2430 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2431 Info, E->getCommon()))
2434 return HandleConditionalOperator(E);
2437 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2438 bool IsBcpCall = false;
2439 // If the condition (ignoring parens) is a __builtin_constant_p call,
2440 // the result is a constant expression if it can be folded without
2441 // side-effects. This is an important GNU extension. See GCC PR38377
2443 if (const CallExpr *CallCE =
2444 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2445 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2448 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2449 // constant expression; we can't check whether it's potentially foldable.
2450 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2453 FoldConstant Fold(Info);
2455 if (!HandleConditionalOperator(E))
2464 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2465 APValue &Value = Info.CurrentCall->Temporaries[E];
2466 if (Value.isUninit()) {
2467 const Expr *Source = E->getSourceExpr();
2470 if (Source == E) { // sanity checking.
2471 assert(0 && "OpaqueValueExpr recursively refers to itself");
2474 return StmtVisitorTy::Visit(Source);
2476 return DerivedSuccess(Value, E);
2479 RetTy VisitCallExpr(const CallExpr *E) {
2480 const Expr *Callee = E->getCallee()->IgnoreParens();
2481 QualType CalleeType = Callee->getType();
2483 const FunctionDecl *FD = 0;
2484 LValue *This = 0, ThisVal;
2485 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2486 bool HasQualifier = false;
2488 // Extract function decl and 'this' pointer from the callee.
2489 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2490 const ValueDecl *Member = 0;
2491 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2492 // Explicit bound member calls, such as x.f() or p->g();
2493 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2495 Member = ME->getMemberDecl();
2497 HasQualifier = ME->hasQualifier();
2498 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2499 // Indirect bound member calls ('.*' or '->*').
2500 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2501 if (!Member) return false;
2504 return Error(Callee);
2506 FD = dyn_cast<FunctionDecl>(Member);
2508 return Error(Callee);
2509 } else if (CalleeType->isFunctionPointerType()) {
2511 if (!EvaluatePointer(Callee, Call, Info))
2514 if (!Call.getLValueOffset().isZero())
2515 return Error(Callee);
2516 FD = dyn_cast_or_null<FunctionDecl>(
2517 Call.getLValueBase().dyn_cast<const ValueDecl*>());
2519 return Error(Callee);
2521 // Overloaded operator calls to member functions are represented as normal
2522 // calls with '*this' as the first argument.
2523 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2524 if (MD && !MD->isStatic()) {
2525 // FIXME: When selecting an implicit conversion for an overloaded
2526 // operator delete, we sometimes try to evaluate calls to conversion
2527 // operators without a 'this' parameter!
2531 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2534 Args = Args.slice(1);
2537 // Don't call function pointers which have been cast to some other type.
2538 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2543 if (This && !This->checkSubobject(Info, E, CSK_This))
2546 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2547 // calls to such functions in constant expressions.
2548 if (This && !HasQualifier &&
2549 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2550 return Error(E, diag::note_constexpr_virtual_call);
2552 const FunctionDecl *Definition = 0;
2553 Stmt *Body = FD->getBody(Definition);
2556 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2557 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2561 return DerivedSuccess(Result, E);
2564 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2565 return StmtVisitorTy::Visit(E->getInitializer());
2567 RetTy VisitInitListExpr(const InitListExpr *E) {
2568 if (E->getNumInits() == 0)
2569 return DerivedZeroInitialization(E);
2570 if (E->getNumInits() == 1)
2571 return StmtVisitorTy::Visit(E->getInit(0));
2574 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2575 return DerivedZeroInitialization(E);
2577 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2578 return DerivedZeroInitialization(E);
2580 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2581 return DerivedZeroInitialization(E);
2584 /// A member expression where the object is a prvalue is itself a prvalue.
2585 RetTy VisitMemberExpr(const MemberExpr *E) {
2586 assert(!E->isArrow() && "missing call to bound member function?");
2589 if (!Evaluate(Val, Info, E->getBase()))
2592 QualType BaseTy = E->getBase()->getType();
2594 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2595 if (!FD) return Error(E);
2596 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2597 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2598 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2600 SubobjectDesignator Designator(BaseTy);
2601 Designator.addDeclUnchecked(FD);
2603 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2604 DerivedSuccess(Val, E);
2607 RetTy VisitCastExpr(const CastExpr *E) {
2608 switch (E->getCastKind()) {
2612 case CK_AtomicToNonAtomic:
2613 case CK_NonAtomicToAtomic:
2615 case CK_UserDefinedConversion:
2616 return StmtVisitorTy::Visit(E->getSubExpr());
2618 case CK_LValueToRValue: {
2620 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2623 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2624 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2627 return DerivedSuccess(RVal, E);
2634 /// Visit a value which is evaluated, but whose value is ignored.
2635 void VisitIgnoredValue(const Expr *E) {
2637 if (!Evaluate(Scratch, Info, E))
2638 Info.EvalStatus.HasSideEffects = true;
2644 //===----------------------------------------------------------------------===//
2645 // Common base class for lvalue and temporary evaluation.
2646 //===----------------------------------------------------------------------===//
2648 template<class Derived>
2649 class LValueExprEvaluatorBase
2650 : public ExprEvaluatorBase<Derived, bool> {
2653 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2654 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2656 bool Success(APValue::LValueBase B) {
2662 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2663 ExprEvaluatorBaseTy(Info), Result(Result) {}
2665 bool Success(const APValue &V, const Expr *E) {
2666 Result.setFrom(this->Info.Ctx, V);
2670 bool VisitMemberExpr(const MemberExpr *E) {
2671 // Handle non-static data members.
2674 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2676 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
2677 } else if (E->getBase()->isRValue()) {
2678 assert(E->getBase()->getType()->isRecordType());
2679 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2681 BaseTy = E->getBase()->getType();
2683 if (!this->Visit(E->getBase()))
2685 BaseTy = E->getBase()->getType();
2688 const ValueDecl *MD = E->getMemberDecl();
2689 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2690 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2691 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2693 if (!HandleLValueMember(this->Info, E, Result, FD))
2695 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2696 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2699 return this->Error(E);
2701 if (MD->getType()->isReferenceType()) {
2703 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2706 return Success(RefValue, E);
2711 bool VisitBinaryOperator(const BinaryOperator *E) {
2712 switch (E->getOpcode()) {
2714 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2718 return HandleMemberPointerAccess(this->Info, E, Result);
2722 bool VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2727 case CK_DerivedToBase:
2728 case CK_UncheckedDerivedToBase: {
2729 if (!this->Visit(E->getSubExpr()))
2732 // Now figure out the necessary offset to add to the base LV to get from
2733 // the derived class to the base class.
2734 QualType Type = E->getSubExpr()->getType();
2736 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2737 PathE = E->path_end(); PathI != PathE; ++PathI) {
2738 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2741 Type = (*PathI)->getType();
2751 //===----------------------------------------------------------------------===//
2752 // LValue Evaluation
2754 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2755 // function designators (in C), decl references to void objects (in C), and
2756 // temporaries (if building with -Wno-address-of-temporary).
2758 // LValue evaluation produces values comprising a base expression of one of the
2764 // * CompoundLiteralExpr in C
2768 // * ObjCStringLiteralExpr
2772 // * CallExpr for a MakeStringConstant builtin
2773 // - Locals and temporaries
2774 // * Any Expr, with a CallIndex indicating the function in which the temporary
2776 // plus an offset in bytes.
2777 //===----------------------------------------------------------------------===//
2779 class LValueExprEvaluator
2780 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2782 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2783 LValueExprEvaluatorBaseTy(Info, Result) {}
2785 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2787 bool VisitDeclRefExpr(const DeclRefExpr *E);
2788 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2789 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2790 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2791 bool VisitMemberExpr(const MemberExpr *E);
2792 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2793 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2794 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2795 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
2796 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2797 bool VisitUnaryDeref(const UnaryOperator *E);
2798 bool VisitUnaryReal(const UnaryOperator *E);
2799 bool VisitUnaryImag(const UnaryOperator *E);
2801 bool VisitCastExpr(const CastExpr *E) {
2802 switch (E->getCastKind()) {
2804 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2806 case CK_LValueBitCast:
2807 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2808 if (!Visit(E->getSubExpr()))
2810 Result.Designator.setInvalid();
2813 case CK_BaseToDerived:
2814 if (!Visit(E->getSubExpr()))
2816 return HandleBaseToDerivedCast(Info, E, Result);
2820 } // end anonymous namespace
2822 /// Evaluate an expression as an lvalue. This can be legitimately called on
2823 /// expressions which are not glvalues, in a few cases:
2824 /// * function designators in C,
2825 /// * "extern void" objects,
2826 /// * temporaries, if building with -Wno-address-of-temporary.
2827 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2828 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2829 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2830 "can't evaluate expression as an lvalue");
2831 return LValueExprEvaluator(Info, Result).Visit(E);
2834 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2835 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2837 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2838 return VisitVarDecl(E, VD);
2842 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2843 if (!VD->getType()->isReferenceType()) {
2844 if (isa<ParmVarDecl>(VD)) {
2845 Result.set(VD, Info.CurrentCall->Index);
2852 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2854 return Success(V, E);
2857 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2858 const MaterializeTemporaryExpr *E) {
2859 if (E->GetTemporaryExpr()->isRValue()) {
2860 if (E->getType()->isRecordType())
2861 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2863 Result.set(E, Info.CurrentCall->Index);
2864 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2865 Result, E->GetTemporaryExpr());
2868 // Materialization of an lvalue temporary occurs when we need to force a copy
2869 // (for instance, if it's a bitfield).
2870 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2871 if (!Visit(E->GetTemporaryExpr()))
2873 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2874 Info.CurrentCall->Temporaries[E]))
2876 Result.set(E, Info.CurrentCall->Index);
2881 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2882 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2883 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2884 // only see this when folding in C, so there's no standard to follow here.
2888 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2889 if (!E->isPotentiallyEvaluated())
2892 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2893 << E->getExprOperand()->getType()
2894 << E->getExprOperand()->getSourceRange();
2898 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2902 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2903 // Handle static data members.
2904 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2905 VisitIgnoredValue(E->getBase());
2906 return VisitVarDecl(E, VD);
2909 // Handle static member functions.
2910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2911 if (MD->isStatic()) {
2912 VisitIgnoredValue(E->getBase());
2917 // Handle non-static data members.
2918 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
2921 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2922 // FIXME: Deal with vectors as array subscript bases.
2923 if (E->getBase()->getType()->isVectorType())
2926 if (!EvaluatePointer(E->getBase(), Result, Info))
2930 if (!EvaluateInteger(E->getIdx(), Index, Info))
2933 = Index.isSigned() ? Index.getSExtValue()
2934 : static_cast<int64_t>(Index.getZExtValue());
2936 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
2939 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
2940 return EvaluatePointer(E->getSubExpr(), Result, Info);
2943 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2944 if (!Visit(E->getSubExpr()))
2946 // __real is a no-op on scalar lvalues.
2947 if (E->getSubExpr()->getType()->isAnyComplexType())
2948 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2952 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2953 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2954 "lvalue __imag__ on scalar?");
2955 if (!Visit(E->getSubExpr()))
2957 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2961 //===----------------------------------------------------------------------===//
2962 // Pointer Evaluation
2963 //===----------------------------------------------------------------------===//
2966 class PointerExprEvaluator
2967 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
2970 bool Success(const Expr *E) {
2976 PointerExprEvaluator(EvalInfo &info, LValue &Result)
2977 : ExprEvaluatorBaseTy(info), Result(Result) {}
2979 bool Success(const APValue &V, const Expr *E) {
2980 Result.setFrom(Info.Ctx, V);
2983 bool ZeroInitialization(const Expr *E) {
2984 return Success((Expr*)0);
2987 bool VisitBinaryOperator(const BinaryOperator *E);
2988 bool VisitCastExpr(const CastExpr* E);
2989 bool VisitUnaryAddrOf(const UnaryOperator *E);
2990 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
2991 { return Success(E); }
2992 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
2993 { return Success(E); }
2994 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
2995 { return Success(E); }
2996 bool VisitCallExpr(const CallExpr *E);
2997 bool VisitBlockExpr(const BlockExpr *E) {
2998 if (!E->getBlockDecl()->hasCaptures())
3002 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3003 if (!Info.CurrentCall->This)
3005 Result = *Info.CurrentCall->This;
3009 // FIXME: Missing: @protocol, @selector
3011 } // end anonymous namespace
3013 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
3014 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
3015 return PointerExprEvaluator(Info, Result).Visit(E);
3018 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3019 if (E->getOpcode() != BO_Add &&
3020 E->getOpcode() != BO_Sub)
3021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3023 const Expr *PExp = E->getLHS();
3024 const Expr *IExp = E->getRHS();
3025 if (IExp->getType()->isPointerType())
3026 std::swap(PExp, IExp);
3028 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3029 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
3032 llvm::APSInt Offset;
3033 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
3035 int64_t AdditionalOffset
3036 = Offset.isSigned() ? Offset.getSExtValue()
3037 : static_cast<int64_t>(Offset.getZExtValue());
3038 if (E->getOpcode() == BO_Sub)
3039 AdditionalOffset = -AdditionalOffset;
3041 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
3042 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3046 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3047 return EvaluateLValue(E->getSubExpr(), Result, Info);
3050 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3051 const Expr* SubExpr = E->getSubExpr();
3053 switch (E->getCastKind()) {
3058 case CK_CPointerToObjCPointerCast:
3059 case CK_BlockPointerToObjCPointerCast:
3060 case CK_AnyPointerToBlockPointerCast:
3061 if (!Visit(SubExpr))
3063 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3064 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3065 // also static_casts, but we disallow them as a resolution to DR1312.
3066 if (!E->getType()->isVoidPointerType()) {
3067 Result.Designator.setInvalid();
3068 if (SubExpr->getType()->isVoidPointerType())
3069 CCEDiag(E, diag::note_constexpr_invalid_cast)
3070 << 3 << SubExpr->getType();
3072 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3076 case CK_DerivedToBase:
3077 case CK_UncheckedDerivedToBase: {
3078 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
3080 if (!Result.Base && Result.Offset.isZero())
3083 // Now figure out the necessary offset to add to the base LV to get from
3084 // the derived class to the base class.
3086 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
3088 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3089 PathE = E->path_end(); PathI != PathE; ++PathI) {
3090 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3093 Type = (*PathI)->getType();
3099 case CK_BaseToDerived:
3100 if (!Visit(E->getSubExpr()))
3102 if (!Result.Base && Result.Offset.isZero())
3104 return HandleBaseToDerivedCast(Info, E, Result);
3106 case CK_NullToPointer:
3107 VisitIgnoredValue(E->getSubExpr());
3108 return ZeroInitialization(E);
3110 case CK_IntegralToPointer: {
3111 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3114 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
3117 if (Value.isInt()) {
3118 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3119 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
3120 Result.Base = (Expr*)0;
3121 Result.Offset = CharUnits::fromQuantity(N);
3122 Result.CallIndex = 0;
3123 Result.Designator.setInvalid();
3126 // Cast is of an lvalue, no need to change value.
3127 Result.setFrom(Info.Ctx, Value);
3131 case CK_ArrayToPointerDecay:
3132 if (SubExpr->isGLValue()) {
3133 if (!EvaluateLValue(SubExpr, Result, Info))
3136 Result.set(SubExpr, Info.CurrentCall->Index);
3137 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3138 Info, Result, SubExpr))
3141 // The result is a pointer to the first element of the array.
3142 if (const ConstantArrayType *CAT
3143 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3144 Result.addArray(Info, E, CAT);
3146 Result.Designator.setInvalid();
3149 case CK_FunctionToPointerDecay:
3150 return EvaluateLValue(SubExpr, Result, Info);
3153 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3156 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
3157 if (IsStringLiteralCall(E))
3160 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3163 //===----------------------------------------------------------------------===//
3164 // Member Pointer Evaluation
3165 //===----------------------------------------------------------------------===//
3168 class MemberPointerExprEvaluator
3169 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3172 bool Success(const ValueDecl *D) {
3173 Result = MemberPtr(D);
3178 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3179 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3181 bool Success(const APValue &V, const Expr *E) {
3185 bool ZeroInitialization(const Expr *E) {
3186 return Success((const ValueDecl*)0);
3189 bool VisitCastExpr(const CastExpr *E);
3190 bool VisitUnaryAddrOf(const UnaryOperator *E);
3192 } // end anonymous namespace
3194 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3196 assert(E->isRValue() && E->getType()->isMemberPointerType());
3197 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3200 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3201 switch (E->getCastKind()) {
3203 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3205 case CK_NullToMemberPointer:
3206 VisitIgnoredValue(E->getSubExpr());
3207 return ZeroInitialization(E);
3209 case CK_BaseToDerivedMemberPointer: {
3210 if (!Visit(E->getSubExpr()))
3212 if (E->path_empty())
3214 // Base-to-derived member pointer casts store the path in derived-to-base
3215 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3216 // the wrong end of the derived->base arc, so stagger the path by one class.
3217 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3218 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3219 PathI != PathE; ++PathI) {
3220 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3221 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3222 if (!Result.castToDerived(Derived))
3225 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3226 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
3231 case CK_DerivedToBaseMemberPointer:
3232 if (!Visit(E->getSubExpr()))
3234 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3235 PathE = E->path_end(); PathI != PathE; ++PathI) {
3236 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3237 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3238 if (!Result.castToBase(Base))
3245 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3246 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3247 // member can be formed.
3248 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3251 //===----------------------------------------------------------------------===//
3252 // Record Evaluation
3253 //===----------------------------------------------------------------------===//
3256 class RecordExprEvaluator
3257 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3262 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3263 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3265 bool Success(const APValue &V, const Expr *E) {
3269 bool ZeroInitialization(const Expr *E);
3271 bool VisitCastExpr(const CastExpr *E);
3272 bool VisitInitListExpr(const InitListExpr *E);
3273 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3277 /// Perform zero-initialization on an object of non-union class type.
3278 /// C++11 [dcl.init]p5:
3279 /// To zero-initialize an object or reference of type T means:
3281 /// -- if T is a (possibly cv-qualified) non-union class type,
3282 /// each non-static data member and each base-class subobject is
3283 /// zero-initialized
3284 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3285 const RecordDecl *RD,
3286 const LValue &This, APValue &Result) {
3287 assert(!RD->isUnion() && "Expected non-union class type");
3288 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3289 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3290 std::distance(RD->field_begin(), RD->field_end()));
3292 if (RD->isInvalidDecl()) return false;
3293 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3297 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3298 End = CD->bases_end(); I != End; ++I, ++Index) {
3299 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3300 LValue Subobject = This;
3301 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3303 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3304 Result.getStructBase(Index)))
3309 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3311 // -- if T is a reference type, no initialization is performed.
3312 if (I->getType()->isReferenceType())
3315 LValue Subobject = This;
3316 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
3319 ImplicitValueInitExpr VIE(I->getType());
3320 if (!EvaluateInPlace(
3321 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
3328 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3329 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3330 if (RD->isInvalidDecl()) return false;
3331 if (RD->isUnion()) {
3332 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3333 // object's first non-static named data member is zero-initialized
3334 RecordDecl::field_iterator I = RD->field_begin();
3335 if (I == RD->field_end()) {
3336 Result = APValue((const FieldDecl*)0);
3340 LValue Subobject = This;
3341 if (!HandleLValueMember(Info, E, Subobject, *I))
3343 Result = APValue(*I);
3344 ImplicitValueInitExpr VIE(I->getType());
3345 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
3348 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3349 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
3353 return HandleClassZeroInitialization(Info, E, RD, This, Result);
3356 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3357 switch (E->getCastKind()) {
3359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3361 case CK_ConstructorConversion:
3362 return Visit(E->getSubExpr());
3364 case CK_DerivedToBase:
3365 case CK_UncheckedDerivedToBase: {
3366 APValue DerivedObject;
3367 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3369 if (!DerivedObject.isStruct())
3370 return Error(E->getSubExpr());
3372 // Derived-to-base rvalue conversion: just slice off the derived part.
3373 APValue *Value = &DerivedObject;
3374 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3375 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3376 PathE = E->path_end(); PathI != PathE; ++PathI) {
3377 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3378 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3379 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3388 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3389 // Cannot constant-evaluate std::initializer_list inits.
3390 if (E->initializesStdInitializerList())
3393 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3394 if (RD->isInvalidDecl()) return false;
3395 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3397 if (RD->isUnion()) {
3398 const FieldDecl *Field = E->getInitializedFieldInUnion();
3399 Result = APValue(Field);
3403 // If the initializer list for a union does not contain any elements, the
3404 // first element of the union is value-initialized.
3405 ImplicitValueInitExpr VIE(Field->getType());
3406 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3408 LValue Subobject = This;
3409 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3411 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
3414 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3415 "initializer list for class with base classes");
3416 Result = APValue(APValue::UninitStruct(), 0,
3417 std::distance(RD->field_begin(), RD->field_end()));
3418 unsigned ElementNo = 0;
3419 bool Success = true;
3420 for (RecordDecl::field_iterator Field = RD->field_begin(),
3421 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3422 // Anonymous bit-fields are not considered members of the class for
3423 // purposes of aggregate initialization.
3424 if (Field->isUnnamedBitfield())
3427 LValue Subobject = This;
3429 bool HaveInit = ElementNo < E->getNumInits();
3431 // FIXME: Diagnostics here should point to the end of the initializer
3432 // list, not the start.
3433 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
3434 Subobject, *Field, &Layout))
3437 // Perform an implicit value-initialization for members beyond the end of
3438 // the initializer list.
3439 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3441 if (!EvaluateInPlace(
3442 Result.getStructField(Field->getFieldIndex()),
3443 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3444 if (!Info.keepEvaluatingAfterFailure())
3453 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3454 const CXXConstructorDecl *FD = E->getConstructor();
3455 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3457 bool ZeroInit = E->requiresZeroInitialization();
3458 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3459 // If we've already performed zero-initialization, we're already done.
3460 if (!Result.isUninit())
3464 return ZeroInitialization(E);
3466 const CXXRecordDecl *RD = FD->getParent();
3468 Result = APValue((FieldDecl*)0);
3470 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3471 std::distance(RD->field_begin(), RD->field_end()));
3475 const FunctionDecl *Definition = 0;
3476 FD->getBody(Definition);
3478 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3481 // Avoid materializing a temporary for an elidable copy/move constructor.
3482 if (E->isElidable() && !ZeroInit)
3483 if (const MaterializeTemporaryExpr *ME
3484 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3485 return Visit(ME->GetTemporaryExpr());
3487 if (ZeroInit && !ZeroInitialization(E))
3490 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3491 return HandleConstructorCall(E->getExprLoc(), This, Args,
3492 cast<CXXConstructorDecl>(Definition), Info,
3496 static bool EvaluateRecord(const Expr *E, const LValue &This,
3497 APValue &Result, EvalInfo &Info) {
3498 assert(E->isRValue() && E->getType()->isRecordType() &&
3499 "can't evaluate expression as a record rvalue");
3500 return RecordExprEvaluator(Info, This, Result).Visit(E);
3503 //===----------------------------------------------------------------------===//
3504 // Temporary Evaluation
3506 // Temporaries are represented in the AST as rvalues, but generally behave like
3507 // lvalues. The full-object of which the temporary is a subobject is implicitly
3508 // materialized so that a reference can bind to it.
3509 //===----------------------------------------------------------------------===//
3511 class TemporaryExprEvaluator
3512 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3514 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3515 LValueExprEvaluatorBaseTy(Info, Result) {}
3517 /// Visit an expression which constructs the value of this temporary.
3518 bool VisitConstructExpr(const Expr *E) {
3519 Result.set(E, Info.CurrentCall->Index);
3520 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
3523 bool VisitCastExpr(const CastExpr *E) {
3524 switch (E->getCastKind()) {
3526 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3528 case CK_ConstructorConversion:
3529 return VisitConstructExpr(E->getSubExpr());
3532 bool VisitInitListExpr(const InitListExpr *E) {
3533 return VisitConstructExpr(E);
3535 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3536 return VisitConstructExpr(E);
3538 bool VisitCallExpr(const CallExpr *E) {
3539 return VisitConstructExpr(E);
3542 } // end anonymous namespace
3544 /// Evaluate an expression of record type as a temporary.
3545 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3546 assert(E->isRValue() && E->getType()->isRecordType());
3547 return TemporaryExprEvaluator(Info, Result).Visit(E);
3550 //===----------------------------------------------------------------------===//
3551 // Vector Evaluation
3552 //===----------------------------------------------------------------------===//
3555 class VectorExprEvaluator
3556 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3560 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3561 : ExprEvaluatorBaseTy(info), Result(Result) {}
3563 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3564 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3565 // FIXME: remove this APValue copy.
3566 Result = APValue(V.data(), V.size());
3569 bool Success(const APValue &V, const Expr *E) {
3570 assert(V.isVector());
3574 bool ZeroInitialization(const Expr *E);
3576 bool VisitUnaryReal(const UnaryOperator *E)
3577 { return Visit(E->getSubExpr()); }
3578 bool VisitCastExpr(const CastExpr* E);
3579 bool VisitInitListExpr(const InitListExpr *E);
3580 bool VisitUnaryImag(const UnaryOperator *E);
3581 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3582 // binary comparisons, binary and/or/xor,
3583 // shufflevector, ExtVectorElementExpr
3585 } // end anonymous namespace
3587 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3588 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3589 return VectorExprEvaluator(Info, Result).Visit(E);
3592 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3593 const VectorType *VTy = E->getType()->castAs<VectorType>();
3594 unsigned NElts = VTy->getNumElements();
3596 const Expr *SE = E->getSubExpr();
3597 QualType SETy = SE->getType();
3599 switch (E->getCastKind()) {
3600 case CK_VectorSplat: {
3601 APValue Val = APValue();
3602 if (SETy->isIntegerType()) {
3604 if (!EvaluateInteger(SE, IntResult, Info))
3606 Val = APValue(IntResult);
3607 } else if (SETy->isRealFloatingType()) {
3609 if (!EvaluateFloat(SE, F, Info))
3616 // Splat and create vector APValue.
3617 SmallVector<APValue, 4> Elts(NElts, Val);
3618 return Success(Elts, E);
3621 // Evaluate the operand into an APInt we can extract from.
3622 llvm::APInt SValInt;
3623 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3625 // Extract the elements
3626 QualType EltTy = VTy->getElementType();
3627 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3628 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3629 SmallVector<APValue, 4> Elts;
3630 if (EltTy->isRealFloatingType()) {
3631 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3632 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3633 unsigned FloatEltSize = EltSize;
3634 if (&Sem == &APFloat::x87DoubleExtended)
3636 for (unsigned i = 0; i < NElts; i++) {
3639 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3641 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3642 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3644 } else if (EltTy->isIntegerType()) {
3645 for (unsigned i = 0; i < NElts; i++) {
3648 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3650 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3651 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3656 return Success(Elts, E);
3659 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3664 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3665 const VectorType *VT = E->getType()->castAs<VectorType>();
3666 unsigned NumInits = E->getNumInits();
3667 unsigned NumElements = VT->getNumElements();
3669 QualType EltTy = VT->getElementType();
3670 SmallVector<APValue, 4> Elements;
3672 // The number of initializers can be less than the number of
3673 // vector elements. For OpenCL, this can be due to nested vector
3674 // initialization. For GCC compatibility, missing trailing elements
3675 // should be initialized with zeroes.
3676 unsigned CountInits = 0, CountElts = 0;
3677 while (CountElts < NumElements) {
3678 // Handle nested vector initialization.
3679 if (CountInits < NumInits
3680 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3682 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3684 unsigned vlen = v.getVectorLength();
3685 for (unsigned j = 0; j < vlen; j++)
3686 Elements.push_back(v.getVectorElt(j));
3688 } else if (EltTy->isIntegerType()) {
3689 llvm::APSInt sInt(32);
3690 if (CountInits < NumInits) {
3691 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3693 } else // trailing integer zero.
3694 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3695 Elements.push_back(APValue(sInt));
3698 llvm::APFloat f(0.0);
3699 if (CountInits < NumInits) {
3700 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3702 } else // trailing float zero.
3703 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3704 Elements.push_back(APValue(f));
3709 return Success(Elements, E);
3713 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3714 const VectorType *VT = E->getType()->getAs<VectorType>();
3715 QualType EltTy = VT->getElementType();
3716 APValue ZeroElement;
3717 if (EltTy->isIntegerType())
3718 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3721 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3723 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3724 return Success(Elements, E);
3727 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3728 VisitIgnoredValue(E->getSubExpr());
3729 return ZeroInitialization(E);
3732 //===----------------------------------------------------------------------===//
3734 //===----------------------------------------------------------------------===//
3737 class ArrayExprEvaluator
3738 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3743 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3744 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3746 bool Success(const APValue &V, const Expr *E) {
3747 assert((V.isArray() || V.isLValue()) &&
3748 "expected array or string literal");
3753 bool ZeroInitialization(const Expr *E) {
3754 const ConstantArrayType *CAT =
3755 Info.Ctx.getAsConstantArrayType(E->getType());
3759 Result = APValue(APValue::UninitArray(), 0,
3760 CAT->getSize().getZExtValue());
3761 if (!Result.hasArrayFiller()) return true;
3763 // Zero-initialize all elements.
3764 LValue Subobject = This;
3765 Subobject.addArray(Info, E, CAT);
3766 ImplicitValueInitExpr VIE(CAT->getElementType());
3767 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
3770 bool VisitInitListExpr(const InitListExpr *E);
3771 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3773 } // end anonymous namespace
3775 static bool EvaluateArray(const Expr *E, const LValue &This,
3776 APValue &Result, EvalInfo &Info) {
3777 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3778 return ArrayExprEvaluator(Info, This, Result).Visit(E);
3781 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3782 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3786 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3787 // an appropriately-typed string literal enclosed in braces.
3788 if (E->isStringLiteralInit()) {
3790 if (!EvaluateLValue(E->getInit(0), LV, Info))
3794 return Success(Val, E);
3797 bool Success = true;
3799 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3800 "zero-initialized array shouldn't have any initialized elts");
3802 if (Result.isArray() && Result.hasArrayFiller())
3803 Filler = Result.getArrayFiller();
3805 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3806 CAT->getSize().getZExtValue());
3808 // If the array was previously zero-initialized, preserve the
3809 // zero-initialized values.
3810 if (!Filler.isUninit()) {
3811 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3812 Result.getArrayInitializedElt(I) = Filler;
3813 if (Result.hasArrayFiller())
3814 Result.getArrayFiller() = Filler;
3817 LValue Subobject = This;
3818 Subobject.addArray(Info, E, CAT);
3820 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3821 I != End; ++I, ++Index) {
3822 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3823 Info, Subobject, cast<Expr>(*I)) ||
3824 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3825 CAT->getElementType(), 1)) {
3826 if (!Info.keepEvaluatingAfterFailure())
3832 if (!Result.hasArrayFiller()) return Success;
3833 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3834 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3835 // but sometimes does:
3836 // struct S { constexpr S() : p(&p) {} void *p; };
3838 return EvaluateInPlace(Result.getArrayFiller(), Info,
3839 Subobject, E->getArrayFiller()) && Success;
3842 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3843 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3844 // but sometimes does:
3845 // struct S { constexpr S() : p(&p) {} void *p; };
3847 LValue Subobject = This;
3849 APValue *Value = &Result;
3850 bool HadZeroInit = true;
3851 QualType ElemTy = E->getType();
3852 while (const ConstantArrayType *CAT =
3853 Info.Ctx.getAsConstantArrayType(ElemTy)) {
3854 Subobject.addArray(Info, E, CAT);
3855 HadZeroInit &= !Value->isUninit();
3857 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3858 if (!Value->hasArrayFiller())
3860 Value = &Value->getArrayFiller();
3861 ElemTy = CAT->getElementType();
3864 if (!ElemTy->isRecordType())
3867 const CXXConstructorDecl *FD = E->getConstructor();
3869 bool ZeroInit = E->requiresZeroInitialization();
3870 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3875 ImplicitValueInitExpr VIE(ElemTy);
3876 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
3879 const CXXRecordDecl *RD = FD->getParent();
3881 *Value = APValue((FieldDecl*)0);
3884 APValue(APValue::UninitStruct(), RD->getNumBases(),
3885 std::distance(RD->field_begin(), RD->field_end()));
3889 const FunctionDecl *Definition = 0;
3890 FD->getBody(Definition);
3892 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3895 if (ZeroInit && !HadZeroInit) {
3896 ImplicitValueInitExpr VIE(ElemTy);
3897 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
3901 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3902 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3903 cast<CXXConstructorDecl>(Definition),
3907 //===----------------------------------------------------------------------===//
3908 // Integer Evaluation
3910 // As a GNU extension, we support casting pointers to sufficiently-wide integer
3911 // types and back in constant folding. Integer values are thus represented
3912 // either as an integer-valued APValue, or as an lvalue-valued APValue.
3913 //===----------------------------------------------------------------------===//
3916 class IntExprEvaluator
3917 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3920 IntExprEvaluator(EvalInfo &info, APValue &result)
3921 : ExprEvaluatorBaseTy(info), Result(result) {}
3923 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
3924 assert(E->getType()->isIntegralOrEnumerationType() &&
3925 "Invalid evaluation result.");
3926 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3927 "Invalid evaluation result.");
3928 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3929 "Invalid evaluation result.");
3930 Result = APValue(SI);
3933 bool Success(const llvm::APSInt &SI, const Expr *E) {
3934 return Success(SI, E, Result);
3937 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
3938 assert(E->getType()->isIntegralOrEnumerationType() &&
3939 "Invalid evaluation result.");
3940 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3941 "Invalid evaluation result.");
3942 Result = APValue(APSInt(I));
3943 Result.getInt().setIsUnsigned(
3944 E->getType()->isUnsignedIntegerOrEnumerationType());
3947 bool Success(const llvm::APInt &I, const Expr *E) {
3948 return Success(I, E, Result);
3951 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
3952 assert(E->getType()->isIntegralOrEnumerationType() &&
3953 "Invalid evaluation result.");
3954 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
3957 bool Success(uint64_t Value, const Expr *E) {
3958 return Success(Value, E, Result);
3961 bool Success(CharUnits Size, const Expr *E) {
3962 return Success(Size.getQuantity(), E);
3965 bool Success(const APValue &V, const Expr *E) {
3966 if (V.isLValue() || V.isAddrLabelDiff()) {
3970 return Success(V.getInt(), E);
3973 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
3975 //===--------------------------------------------------------------------===//
3977 //===--------------------------------------------------------------------===//
3979 bool VisitIntegerLiteral(const IntegerLiteral *E) {
3980 return Success(E->getValue(), E);
3982 bool VisitCharacterLiteral(const CharacterLiteral *E) {
3983 return Success(E->getValue(), E);
3986 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3987 bool VisitDeclRefExpr(const DeclRefExpr *E) {
3988 if (CheckReferencedDecl(E, E->getDecl()))
3991 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
3993 bool VisitMemberExpr(const MemberExpr *E) {
3994 if (CheckReferencedDecl(E, E->getMemberDecl())) {
3995 VisitIgnoredValue(E->getBase());
3999 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
4002 bool VisitCallExpr(const CallExpr *E);
4003 bool VisitBinaryOperator(const BinaryOperator *E);
4004 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
4005 bool VisitUnaryOperator(const UnaryOperator *E);
4007 bool VisitCastExpr(const CastExpr* E);
4008 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
4010 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4011 return Success(E->getValue(), E);
4014 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4015 return Success(E->getValue(), E);
4018 // Note, GNU defines __null as an integer, not a pointer.
4019 bool VisitGNUNullExpr(const GNUNullExpr *E) {
4020 return ZeroInitialization(E);
4023 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
4024 return Success(E->getValue(), E);
4027 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4028 return Success(E->getValue(), E);
4031 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4032 return Success(E->getValue(), E);
4035 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4036 return Success(E->getValue(), E);
4039 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4040 return Success(E->getValue(), E);
4043 bool VisitUnaryReal(const UnaryOperator *E);
4044 bool VisitUnaryImag(const UnaryOperator *E);
4046 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
4047 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
4050 CharUnits GetAlignOfExpr(const Expr *E);
4051 CharUnits GetAlignOfType(QualType T);
4052 static QualType GetObjectType(APValue::LValueBase B);
4053 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
4054 // FIXME: Missing: array subscript of vector, member of vector
4056 } // end anonymous namespace
4058 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4059 /// produce either the integer value or a pointer.
4061 /// GCC has a heinous extension which folds casts between pointer types and
4062 /// pointer-sized integral types. We support this by allowing the evaluation of
4063 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4064 /// Some simple arithmetic on such values is supported (they are treated much
4066 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
4068 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
4069 return IntExprEvaluator(Info, Result).Visit(E);
4072 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
4074 if (!EvaluateIntegerOrLValue(E, Val, Info))
4077 // FIXME: It would be better to produce the diagnostic for casting
4078 // a pointer to an integer.
4079 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
4082 Result = Val.getInt();
4086 /// Check whether the given declaration can be directly converted to an integral
4087 /// rvalue. If not, no diagnostic is produced; there are other things we can
4089 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
4090 // Enums are integer constant exprs.
4091 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
4092 // Check for signedness/width mismatches between E type and ECD value.
4093 bool SameSign = (ECD->getInitVal().isSigned()
4094 == E->getType()->isSignedIntegerOrEnumerationType());
4095 bool SameWidth = (ECD->getInitVal().getBitWidth()
4096 == Info.Ctx.getIntWidth(E->getType()));
4097 if (SameSign && SameWidth)
4098 return Success(ECD->getInitVal(), E);
4100 // Get rid of mismatch (otherwise Success assertions will fail)
4101 // by computing a new value matching the type of E.
4102 llvm::APSInt Val = ECD->getInitVal();
4104 Val.setIsSigned(!ECD->getInitVal().isSigned());
4106 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4107 return Success(Val, E);
4113 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4115 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4116 // The following enum mimics the values returned by GCC.
4117 // FIXME: Does GCC differ between lvalue and rvalue references here?
4118 enum gcc_type_class {
4120 void_type_class, integer_type_class, char_type_class,
4121 enumeral_type_class, boolean_type_class,
4122 pointer_type_class, reference_type_class, offset_type_class,
4123 real_type_class, complex_type_class,
4124 function_type_class, method_type_class,
4125 record_type_class, union_type_class,
4126 array_type_class, string_type_class,
4130 // If no argument was supplied, default to "no_type_class". This isn't
4131 // ideal, however it is what gcc does.
4132 if (E->getNumArgs() == 0)
4133 return no_type_class;
4135 QualType ArgTy = E->getArg(0)->getType();
4136 if (ArgTy->isVoidType())
4137 return void_type_class;
4138 else if (ArgTy->isEnumeralType())
4139 return enumeral_type_class;
4140 else if (ArgTy->isBooleanType())
4141 return boolean_type_class;
4142 else if (ArgTy->isCharType())
4143 return string_type_class; // gcc doesn't appear to use char_type_class
4144 else if (ArgTy->isIntegerType())
4145 return integer_type_class;
4146 else if (ArgTy->isPointerType())
4147 return pointer_type_class;
4148 else if (ArgTy->isReferenceType())
4149 return reference_type_class;
4150 else if (ArgTy->isRealType())
4151 return real_type_class;
4152 else if (ArgTy->isComplexType())
4153 return complex_type_class;
4154 else if (ArgTy->isFunctionType())
4155 return function_type_class;
4156 else if (ArgTy->isStructureOrClassType())
4157 return record_type_class;
4158 else if (ArgTy->isUnionType())
4159 return union_type_class;
4160 else if (ArgTy->isArrayType())
4161 return array_type_class;
4162 else if (ArgTy->isUnionType())
4163 return union_type_class;
4164 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
4165 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
4168 /// EvaluateBuiltinConstantPForLValue - Determine the result of
4169 /// __builtin_constant_p when applied to the given lvalue.
4171 /// An lvalue is only "constant" if it is a pointer or reference to the first
4172 /// character of a string literal.
4173 template<typename LValue>
4174 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4175 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
4176 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4179 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4180 /// GCC as we can manage.
4181 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4182 QualType ArgType = Arg->getType();
4184 // __builtin_constant_p always has one operand. The rules which gcc follows
4185 // are not precisely documented, but are as follows:
4187 // - If the operand is of integral, floating, complex or enumeration type,
4188 // and can be folded to a known value of that type, it returns 1.
4189 // - If the operand and can be folded to a pointer to the first character
4190 // of a string literal (or such a pointer cast to an integral type), it
4193 // Otherwise, it returns 0.
4195 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4196 // its support for this does not currently work.
4197 if (ArgType->isIntegralOrEnumerationType()) {
4198 Expr::EvalResult Result;
4199 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4202 APValue &V = Result.Val;
4203 if (V.getKind() == APValue::Int)
4206 return EvaluateBuiltinConstantPForLValue(V);
4207 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4208 return Arg->isEvaluatable(Ctx);
4209 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4211 Expr::EvalStatus Status;
4212 EvalInfo Info(Ctx, Status);
4213 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4214 : EvaluatePointer(Arg, LV, Info)) &&
4215 !Status.HasSideEffects)
4216 return EvaluateBuiltinConstantPForLValue(LV);
4219 // Anything else isn't considered to be sufficiently constant.
4223 /// Retrieves the "underlying object type" of the given expression,
4224 /// as used by __builtin_object_size.
4225 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4226 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4227 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4228 return VD->getType();
4229 } else if (const Expr *E = B.get<const Expr*>()) {
4230 if (isa<CompoundLiteralExpr>(E))
4231 return E->getType();
4237 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
4241 // The operand of __builtin_object_size is never evaluated for side-effects.
4242 // If there are any, but we can determine the pointed-to object anyway, then
4243 // ignore the side-effects.
4244 SpeculativeEvaluationRAII SpeculativeEval(Info);
4245 if (!EvaluatePointer(E->getArg(0), Base, Info))
4249 // If we can prove the base is null, lower to zero now.
4250 if (!Base.getLValueBase()) return Success(0, E);
4252 QualType T = GetObjectType(Base.getLValueBase());
4254 T->isIncompleteType() ||
4255 T->isFunctionType() ||
4256 T->isVariablyModifiedType() ||
4257 T->isDependentType())
4260 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4261 CharUnits Offset = Base.getLValueOffset();
4263 if (!Offset.isNegative() && Offset <= Size)
4266 Size = CharUnits::Zero();
4267 return Success(Size, E);
4270 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
4271 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
4273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4275 case Builtin::BI__builtin_object_size: {
4276 if (TryEvaluateBuiltinObjectSize(E))
4279 // If evaluating the argument has side-effects, we can't determine the size
4280 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4281 // handle all cases where the expression has side-effects.
4282 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
4283 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
4284 return Success(-1ULL, E);
4285 return Success(0, E);
4288 // Expression had no side effects, but we couldn't statically determine the
4289 // size of the referenced object.
4293 case Builtin::BI__builtin_bswap16:
4294 case Builtin::BI__builtin_bswap32:
4295 case Builtin::BI__builtin_bswap64: {
4297 if (!EvaluateInteger(E->getArg(0), Val, Info))
4300 return Success(Val.byteSwap(), E);
4303 case Builtin::BI__builtin_classify_type:
4304 return Success(EvaluateBuiltinClassifyType(E), E);
4306 case Builtin::BI__builtin_constant_p:
4307 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4309 case Builtin::BI__builtin_eh_return_data_regno: {
4310 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4311 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4312 return Success(Operand, E);
4315 case Builtin::BI__builtin_expect:
4316 return Visit(E->getArg(0));
4318 case Builtin::BIstrlen:
4319 // A call to strlen is not a constant expression.
4320 if (Info.getLangOpts().CPlusPlus0x)
4321 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
4322 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4324 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
4326 case Builtin::BI__builtin_strlen:
4327 // As an extension, we support strlen() and __builtin_strlen() as constant
4328 // expressions when the argument is a string literal.
4329 if (const StringLiteral *S
4330 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4331 // The string literal may have embedded null characters. Find the first
4332 // one and truncate there.
4333 StringRef Str = S->getString();
4334 StringRef::size_type Pos = Str.find(0);
4335 if (Pos != StringRef::npos)
4336 Str = Str.substr(0, Pos);
4338 return Success(Str.size(), E);
4343 case Builtin::BI__atomic_always_lock_free:
4344 case Builtin::BI__atomic_is_lock_free:
4345 case Builtin::BI__c11_atomic_is_lock_free: {
4347 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4350 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4351 // of two less than the maximum inline atomic width, we know it is
4352 // lock-free. If the size isn't a power of two, or greater than the
4353 // maximum alignment where we promote atomics, we know it is not lock-free
4354 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4355 // the answer can only be determined at runtime; for example, 16-byte
4356 // atomics have lock-free implementations on some, but not all,
4357 // x86-64 processors.
4359 // Check power-of-two.
4360 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4361 if (Size.isPowerOfTwo()) {
4362 // Check against inlining width.
4363 unsigned InlineWidthBits =
4364 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4365 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4366 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4367 Size == CharUnits::One() ||
4368 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4369 Expr::NPC_NeverValueDependent))
4370 // OK, we will inline appropriately-aligned operations of this size,
4371 // and _Atomic(T) is appropriately-aligned.
4372 return Success(1, E);
4374 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4375 castAs<PointerType>()->getPointeeType();
4376 if (!PointeeType->isIncompleteType() &&
4377 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4378 // OK, we will inline operations on this object.
4379 return Success(1, E);
4384 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4385 Success(0, E) : Error(E);
4390 static bool HasSameBase(const LValue &A, const LValue &B) {
4391 if (!A.getLValueBase())
4392 return !B.getLValueBase();
4393 if (!B.getLValueBase())
4396 if (A.getLValueBase().getOpaqueValue() !=
4397 B.getLValueBase().getOpaqueValue()) {
4398 const Decl *ADecl = GetLValueBaseDecl(A);
4401 const Decl *BDecl = GetLValueBaseDecl(B);
4402 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4406 return IsGlobalLValue(A.getLValueBase()) ||
4407 A.getLValueCallIndex() == B.getLValueCallIndex();
4410 /// Perform the given integer operation, which is known to need at most BitWidth
4411 /// bits, and check for overflow in the original type (if that type was not an
4413 template<typename Operation>
4414 static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4415 const APSInt &LHS, const APSInt &RHS,
4416 unsigned BitWidth, Operation Op) {
4417 if (LHS.isUnsigned())
4418 return Op(LHS, RHS);
4420 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4421 APSInt Result = Value.trunc(LHS.getBitWidth());
4422 if (Result.extend(BitWidth) != Value)
4423 HandleOverflow(Info, E, Value, E->getType());
4429 /// \brief Data recursive integer evaluator of certain binary operators.
4431 /// We use a data recursive algorithm for binary operators so that we are able
4432 /// to handle extreme cases of chained binary operators without causing stack
4434 class DataRecursiveIntBinOpEvaluator {
4439 EvalResult() : Failed(false) { }
4441 void swap(EvalResult &RHS) {
4443 Failed = RHS.Failed;
4450 EvalResult LHSResult; // meaningful only for binary operator expression.
4451 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4453 Job() : StoredInfo(0) { }
4454 void startSpeculativeEval(EvalInfo &Info) {
4455 OldEvalStatus = Info.EvalStatus;
4456 Info.EvalStatus.Diag = 0;
4461 StoredInfo->EvalStatus = OldEvalStatus;
4465 EvalInfo *StoredInfo; // non-null if status changed.
4466 Expr::EvalStatus OldEvalStatus;
4469 SmallVector<Job, 16> Queue;
4471 IntExprEvaluator &IntEval;
4473 APValue &FinalResult;
4476 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4477 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4479 /// \brief True if \param E is a binary operator that we are going to handle
4480 /// data recursively.
4481 /// We handle binary operators that are comma, logical, or that have operands
4482 /// with integral or enumeration type.
4483 static bool shouldEnqueue(const BinaryOperator *E) {
4484 return E->getOpcode() == BO_Comma ||
4486 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4487 E->getRHS()->getType()->isIntegralOrEnumerationType());
4490 bool Traverse(const BinaryOperator *E) {
4492 EvalResult PrevResult;
4493 while (!Queue.empty())
4494 process(PrevResult);
4496 if (PrevResult.Failed) return false;
4498 FinalResult.swap(PrevResult.Val);
4503 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4504 return IntEval.Success(Value, E, Result);
4506 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4507 return IntEval.Success(Value, E, Result);
4509 bool Error(const Expr *E) {
4510 return IntEval.Error(E);
4512 bool Error(const Expr *E, diag::kind D) {
4513 return IntEval.Error(E, D);
4516 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4517 return Info.CCEDiag(E, D);
4520 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4521 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4522 bool &SuppressRHSDiags);
4524 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4525 const BinaryOperator *E, APValue &Result);
4527 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4528 Result.Failed = !Evaluate(Result.Val, Info, E);
4530 Result.Val = APValue();
4533 void process(EvalResult &Result);
4535 void enqueue(const Expr *E) {
4536 E = E->IgnoreParens();
4537 Queue.resize(Queue.size()+1);
4539 Queue.back().Kind = Job::AnyExprKind;
4545 bool DataRecursiveIntBinOpEvaluator::
4546 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
4547 bool &SuppressRHSDiags) {
4548 if (E->getOpcode() == BO_Comma) {
4549 // Ignore LHS but note if we could not evaluate it.
4550 if (LHSResult.Failed)
4551 Info.EvalStatus.HasSideEffects = true;
4555 if (E->isLogicalOp()) {
4557 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
4558 // We were able to evaluate the LHS, see if we can get away with not
4559 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4560 if (lhsResult == (E->getOpcode() == BO_LOr)) {
4561 Success(lhsResult, E, LHSResult.Val);
4562 return false; // Ignore RHS
4565 // Since we weren't able to evaluate the left hand side, it
4566 // must have had side effects.
4567 Info.EvalStatus.HasSideEffects = true;
4569 // We can't evaluate the LHS; however, sometimes the result
4570 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4571 // Don't ignore RHS and suppress diagnostics from this arm.
4572 SuppressRHSDiags = true;
4578 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4579 E->getRHS()->getType()->isIntegralOrEnumerationType());
4581 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
4582 return false; // Ignore RHS;
4587 bool DataRecursiveIntBinOpEvaluator::
4588 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4589 const BinaryOperator *E, APValue &Result) {
4590 if (E->getOpcode() == BO_Comma) {
4591 if (RHSResult.Failed)
4593 Result = RHSResult.Val;
4597 if (E->isLogicalOp()) {
4598 bool lhsResult, rhsResult;
4599 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4600 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4604 if (E->getOpcode() == BO_LOr)
4605 return Success(lhsResult || rhsResult, E, Result);
4607 return Success(lhsResult && rhsResult, E, Result);
4611 // We can't evaluate the LHS; however, sometimes the result
4612 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4613 if (rhsResult == (E->getOpcode() == BO_LOr))
4614 return Success(rhsResult, E, Result);
4621 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4622 E->getRHS()->getType()->isIntegralOrEnumerationType());
4624 if (LHSResult.Failed || RHSResult.Failed)
4627 const APValue &LHSVal = LHSResult.Val;
4628 const APValue &RHSVal = RHSResult.Val;
4630 // Handle cases like (unsigned long)&a + 4.
4631 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4633 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4634 RHSVal.getInt().getZExtValue());
4635 if (E->getOpcode() == BO_Add)
4636 Result.getLValueOffset() += AdditionalOffset;
4638 Result.getLValueOffset() -= AdditionalOffset;
4642 // Handle cases like 4 + (unsigned long)&a
4643 if (E->getOpcode() == BO_Add &&
4644 RHSVal.isLValue() && LHSVal.isInt()) {
4646 Result.getLValueOffset() += CharUnits::fromQuantity(
4647 LHSVal.getInt().getZExtValue());
4651 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4652 // Handle (intptr_t)&&A - (intptr_t)&&B.
4653 if (!LHSVal.getLValueOffset().isZero() ||
4654 !RHSVal.getLValueOffset().isZero())
4656 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4657 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4658 if (!LHSExpr || !RHSExpr)
4660 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4661 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4662 if (!LHSAddrExpr || !RHSAddrExpr)
4664 // Make sure both labels come from the same function.
4665 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4666 RHSAddrExpr->getLabel()->getDeclContext())
4668 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4672 // All the following cases expect both operands to be an integer
4673 if (!LHSVal.isInt() || !RHSVal.isInt())
4676 const APSInt &LHS = LHSVal.getInt();
4677 APSInt RHS = RHSVal.getInt();
4679 switch (E->getOpcode()) {
4683 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4684 LHS.getBitWidth() * 2,
4685 std::multiplies<APSInt>()), E,
4688 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4689 LHS.getBitWidth() + 1,
4690 std::plus<APSInt>()), E, Result);
4692 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4693 LHS.getBitWidth() + 1,
4694 std::minus<APSInt>()), E, Result);
4695 case BO_And: return Success(LHS & RHS, E, Result);
4696 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4697 case BO_Or: return Success(LHS | RHS, E, Result);
4701 return Error(E, diag::note_expr_divide_by_zero);
4702 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4703 // not actually undefined behavior in C++11 due to a language defect.
4704 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4705 LHS.isSigned() && LHS.isMinSignedValue())
4706 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4707 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4710 // During constant-folding, a negative shift is an opposite shift. Such
4711 // a shift is not a constant expression.
4712 if (RHS.isSigned() && RHS.isNegative()) {
4713 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4719 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4720 // the shifted type.
4721 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4723 CCEDiag(E, diag::note_constexpr_large_shift)
4724 << RHS << E->getType() << LHS.getBitWidth();
4725 } else if (LHS.isSigned()) {
4726 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4727 // operand, and must not overflow the corresponding unsigned type.
4728 if (LHS.isNegative())
4729 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4730 else if (LHS.countLeadingZeros() < SA)
4731 CCEDiag(E, diag::note_constexpr_lshift_discards);
4734 return Success(LHS << SA, E, Result);
4737 // During constant-folding, a negative shift is an opposite shift. Such a
4738 // shift is not a constant expression.
4739 if (RHS.isSigned() && RHS.isNegative()) {
4740 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4746 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4748 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4750 CCEDiag(E, diag::note_constexpr_large_shift)
4751 << RHS << E->getType() << LHS.getBitWidth();
4753 return Success(LHS >> SA, E, Result);
4756 case BO_LT: return Success(LHS < RHS, E, Result);
4757 case BO_GT: return Success(LHS > RHS, E, Result);
4758 case BO_LE: return Success(LHS <= RHS, E, Result);
4759 case BO_GE: return Success(LHS >= RHS, E, Result);
4760 case BO_EQ: return Success(LHS == RHS, E, Result);
4761 case BO_NE: return Success(LHS != RHS, E, Result);
4765 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
4766 Job &job = Queue.back();
4769 case Job::AnyExprKind: {
4770 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4771 if (shouldEnqueue(Bop)) {
4772 job.Kind = Job::BinOpKind;
4773 enqueue(Bop->getLHS());
4778 EvaluateExpr(job.E, Result);
4783 case Job::BinOpKind: {
4784 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4785 bool SuppressRHSDiags = false;
4786 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
4790 if (SuppressRHSDiags)
4791 job.startSpeculativeEval(Info);
4792 job.LHSResult.swap(Result);
4793 job.Kind = Job::BinOpVisitedLHSKind;
4794 enqueue(Bop->getRHS());
4798 case Job::BinOpVisitedLHSKind: {
4799 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4802 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
4808 llvm_unreachable("Invalid Job::Kind!");
4811 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4812 if (E->isAssignmentOp())
4815 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4816 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
4818 QualType LHSTy = E->getLHS()->getType();
4819 QualType RHSTy = E->getRHS()->getType();
4821 if (LHSTy->isAnyComplexType()) {
4822 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4823 ComplexValue LHS, RHS;
4825 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4826 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4829 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4832 if (LHS.isComplexFloat()) {
4833 APFloat::cmpResult CR_r =
4834 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4835 APFloat::cmpResult CR_i =
4836 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4838 if (E->getOpcode() == BO_EQ)
4839 return Success((CR_r == APFloat::cmpEqual &&
4840 CR_i == APFloat::cmpEqual), E);
4842 assert(E->getOpcode() == BO_NE &&
4843 "Invalid complex comparison.");
4844 return Success(((CR_r == APFloat::cmpGreaterThan ||
4845 CR_r == APFloat::cmpLessThan ||
4846 CR_r == APFloat::cmpUnordered) ||
4847 (CR_i == APFloat::cmpGreaterThan ||
4848 CR_i == APFloat::cmpLessThan ||
4849 CR_i == APFloat::cmpUnordered)), E);
4852 if (E->getOpcode() == BO_EQ)
4853 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4854 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4856 assert(E->getOpcode() == BO_NE &&
4857 "Invalid compex comparison.");
4858 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4859 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4864 if (LHSTy->isRealFloatingType() &&
4865 RHSTy->isRealFloatingType()) {
4866 APFloat RHS(0.0), LHS(0.0);
4868 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4869 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4872 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4875 APFloat::cmpResult CR = LHS.compare(RHS);
4877 switch (E->getOpcode()) {
4879 llvm_unreachable("Invalid binary operator!");
4881 return Success(CR == APFloat::cmpLessThan, E);
4883 return Success(CR == APFloat::cmpGreaterThan, E);
4885 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4887 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4890 return Success(CR == APFloat::cmpEqual, E);
4892 return Success(CR == APFloat::cmpGreaterThan
4893 || CR == APFloat::cmpLessThan
4894 || CR == APFloat::cmpUnordered, E);
4898 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4899 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4900 LValue LHSValue, RHSValue;
4902 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4903 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4906 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4909 // Reject differing bases from the normal codepath; we special-case
4910 // comparisons to null.
4911 if (!HasSameBase(LHSValue, RHSValue)) {
4912 if (E->getOpcode() == BO_Sub) {
4913 // Handle &&A - &&B.
4914 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4916 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4917 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
4918 if (!LHSExpr || !RHSExpr)
4920 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4921 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4922 if (!LHSAddrExpr || !RHSAddrExpr)
4924 // Make sure both labels come from the same function.
4925 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4926 RHSAddrExpr->getLabel()->getDeclContext())
4928 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4931 // Inequalities and subtractions between unrelated pointers have
4932 // unspecified or undefined behavior.
4933 if (!E->isEqualityOp())
4935 // A constant address may compare equal to the address of a symbol.
4936 // The one exception is that address of an object cannot compare equal
4937 // to a null pointer constant.
4938 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4939 (!RHSValue.Base && !RHSValue.Offset.isZero()))
4941 // It's implementation-defined whether distinct literals will have
4942 // distinct addresses. In clang, the result of such a comparison is
4943 // unspecified, so it is not a constant expression. However, we do know
4944 // that the address of a literal will be non-null.
4945 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4946 LHSValue.Base && RHSValue.Base)
4948 // We can't tell whether weak symbols will end up pointing to the same
4950 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4952 // Pointers with different bases cannot represent the same object.
4953 // (Note that clang defaults to -fmerge-all-constants, which can
4954 // lead to inconsistent results for comparisons involving the address
4955 // of a constant; this generally doesn't matter in practice.)
4956 return Success(E->getOpcode() == BO_NE, E);
4959 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4960 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4962 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4963 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4965 if (E->getOpcode() == BO_Sub) {
4966 // C++11 [expr.add]p6:
4967 // Unless both pointers point to elements of the same array object, or
4968 // one past the last element of the array object, the behavior is
4970 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4971 !AreElementsOfSameArray(getType(LHSValue.Base),
4972 LHSDesignator, RHSDesignator))
4973 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4975 QualType Type = E->getLHS()->getType();
4976 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
4978 CharUnits ElementSize;
4979 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
4982 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4983 // and produce incorrect results when it overflows. Such behavior
4984 // appears to be non-conforming, but is common, so perhaps we should
4985 // assume the standard intended for such cases to be undefined behavior
4986 // and check for them.
4988 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4989 // overflow in the final conversion to ptrdiff_t.
4991 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4993 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4995 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4996 APSInt TrueResult = (LHS - RHS) / ElemSize;
4997 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4999 if (Result.extend(65) != TrueResult)
5000 HandleOverflow(Info, E, TrueResult, E->getType());
5001 return Success(Result, E);
5004 // C++11 [expr.rel]p3:
5005 // Pointers to void (after pointer conversions) can be compared, with a
5006 // result defined as follows: If both pointers represent the same
5007 // address or are both the null pointer value, the result is true if the
5008 // operator is <= or >= and false otherwise; otherwise the result is
5010 // We interpret this as applying to pointers to *cv* void.
5011 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
5012 E->isRelationalOp())
5013 CCEDiag(E, diag::note_constexpr_void_comparison);
5015 // C++11 [expr.rel]p2:
5016 // - If two pointers point to non-static data members of the same object,
5017 // or to subobjects or array elements fo such members, recursively, the
5018 // pointer to the later declared member compares greater provided the
5019 // two members have the same access control and provided their class is
5022 // - Otherwise pointer comparisons are unspecified.
5023 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5024 E->isRelationalOp()) {
5027 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5028 RHSDesignator, WasArrayIndex);
5029 // At the point where the designators diverge, the comparison has a
5030 // specified value if:
5031 // - we are comparing array indices
5032 // - we are comparing fields of a union, or fields with the same access
5033 // Otherwise, the result is unspecified and thus the comparison is not a
5034 // constant expression.
5035 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5036 Mismatch < RHSDesignator.Entries.size()) {
5037 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5038 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5040 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5042 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5043 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5044 << RF->getParent() << RF;
5046 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5047 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5048 << LF->getParent() << LF;
5049 else if (!LF->getParent()->isUnion() &&
5050 LF->getAccess() != RF->getAccess())
5051 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5052 << LF << LF->getAccess() << RF << RF->getAccess()
5057 // The comparison here must be unsigned, and performed with the same
5058 // width as the pointer.
5059 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5060 uint64_t CompareLHS = LHSOffset.getQuantity();
5061 uint64_t CompareRHS = RHSOffset.getQuantity();
5062 assert(PtrSize <= 64 && "Unexpected pointer width");
5063 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5067 // If there is a base and this is a relational operator, we can only
5068 // compare pointers within the object in question; otherwise, the result
5069 // depends on where the object is located in memory.
5070 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5071 QualType BaseTy = getType(LHSValue.Base);
5072 if (BaseTy->isIncompleteType())
5074 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5075 uint64_t OffsetLimit = Size.getQuantity();
5076 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5080 switch (E->getOpcode()) {
5081 default: llvm_unreachable("missing comparison operator");
5082 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5083 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5084 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5085 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5086 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5087 case BO_NE: return Success(CompareLHS != CompareRHS, E);
5092 if (LHSTy->isMemberPointerType()) {
5093 assert(E->isEqualityOp() && "unexpected member pointer operation");
5094 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5096 MemberPtr LHSValue, RHSValue;
5098 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5099 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5102 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5105 // C++11 [expr.eq]p2:
5106 // If both operands are null, they compare equal. Otherwise if only one is
5107 // null, they compare unequal.
5108 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5109 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5110 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5113 // Otherwise if either is a pointer to a virtual member function, the
5114 // result is unspecified.
5115 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5116 if (MD->isVirtual())
5117 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5118 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5119 if (MD->isVirtual())
5120 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5122 // Otherwise they compare equal if and only if they would refer to the
5123 // same member of the same most derived object or the same subobject if
5124 // they were dereferenced with a hypothetical object of the associated
5126 bool Equal = LHSValue == RHSValue;
5127 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5130 if (LHSTy->isNullPtrType()) {
5131 assert(E->isComparisonOp() && "unexpected nullptr operation");
5132 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5133 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5134 // are compared, the result is true of the operator is <=, >= or ==, and
5136 BinaryOperator::Opcode Opcode = E->getOpcode();
5137 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5140 assert((!LHSTy->isIntegralOrEnumerationType() ||
5141 !RHSTy->isIntegralOrEnumerationType()) &&
5142 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5143 // We can't continue from here for non-integral types.
5144 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5147 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
5148 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5149 // result shall be the alignment of the referenced type."
5150 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5151 T = Ref->getPointeeType();
5153 // __alignof is defined to return the preferred alignment.
5154 return Info.Ctx.toCharUnitsFromBits(
5155 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5158 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
5159 E = E->IgnoreParens();
5161 // alignof decl is always accepted, even if it doesn't make sense: we default
5162 // to 1 in those cases.
5163 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5164 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5165 /*RefAsPointee*/true);
5167 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5168 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5169 /*RefAsPointee*/true);
5171 return GetAlignOfType(E->getType());
5175 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5176 /// a result as the expression's type.
5177 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5178 const UnaryExprOrTypeTraitExpr *E) {
5179 switch(E->getKind()) {
5180 case UETT_AlignOf: {
5181 if (E->isArgumentType())
5182 return Success(GetAlignOfType(E->getArgumentType()), E);
5184 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
5187 case UETT_VecStep: {
5188 QualType Ty = E->getTypeOfArgument();
5190 if (Ty->isVectorType()) {
5191 unsigned n = Ty->castAs<VectorType>()->getNumElements();
5193 // The vec_step built-in functions that take a 3-component
5194 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5198 return Success(n, E);
5200 return Success(1, E);
5204 QualType SrcTy = E->getTypeOfArgument();
5205 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5206 // the result is the size of the referenced type."
5207 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5208 SrcTy = Ref->getPointeeType();
5211 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
5213 return Success(Sizeof, E);
5217 llvm_unreachable("unknown expr/type trait");
5220 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
5222 unsigned n = OOE->getNumComponents();
5225 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
5226 for (unsigned i = 0; i != n; ++i) {
5227 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5228 switch (ON.getKind()) {
5229 case OffsetOfExpr::OffsetOfNode::Array: {
5230 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
5232 if (!EvaluateInteger(Idx, IdxResult, Info))
5234 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5237 CurrentType = AT->getElementType();
5238 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5239 Result += IdxResult.getSExtValue() * ElementSize;
5243 case OffsetOfExpr::OffsetOfNode::Field: {
5244 FieldDecl *MemberDecl = ON.getField();
5245 const RecordType *RT = CurrentType->getAs<RecordType>();
5248 RecordDecl *RD = RT->getDecl();
5249 if (RD->isInvalidDecl()) return false;
5250 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5251 unsigned i = MemberDecl->getFieldIndex();
5252 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
5253 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
5254 CurrentType = MemberDecl->getType().getNonReferenceType();
5258 case OffsetOfExpr::OffsetOfNode::Identifier:
5259 llvm_unreachable("dependent __builtin_offsetof");
5261 case OffsetOfExpr::OffsetOfNode::Base: {
5262 CXXBaseSpecifier *BaseSpec = ON.getBase();
5263 if (BaseSpec->isVirtual())
5266 // Find the layout of the class whose base we are looking into.
5267 const RecordType *RT = CurrentType->getAs<RecordType>();
5270 RecordDecl *RD = RT->getDecl();
5271 if (RD->isInvalidDecl()) return false;
5272 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5274 // Find the base class itself.
5275 CurrentType = BaseSpec->getType();
5276 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5280 // Add the offset to the base.
5281 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
5286 return Success(Result, OOE);
5289 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5290 switch (E->getOpcode()) {
5292 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5296 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5297 // If so, we could clear the diagnostic ID.
5298 return Visit(E->getSubExpr());
5300 // The result is just the value.
5301 return Visit(E->getSubExpr());
5303 if (!Visit(E->getSubExpr()))
5305 if (!Result.isInt()) return Error(E);
5306 const APSInt &Value = Result.getInt();
5307 if (Value.isSigned() && Value.isMinSignedValue())
5308 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5310 return Success(-Value, E);
5313 if (!Visit(E->getSubExpr()))
5315 if (!Result.isInt()) return Error(E);
5316 return Success(~Result.getInt(), E);
5320 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
5322 return Success(!bres, E);
5327 /// HandleCast - This is used to evaluate implicit or explicit casts where the
5328 /// result type is integer.
5329 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5330 const Expr *SubExpr = E->getSubExpr();
5331 QualType DestType = E->getType();
5332 QualType SrcType = SubExpr->getType();
5334 switch (E->getCastKind()) {
5335 case CK_BaseToDerived:
5336 case CK_DerivedToBase:
5337 case CK_UncheckedDerivedToBase:
5340 case CK_ArrayToPointerDecay:
5341 case CK_FunctionToPointerDecay:
5342 case CK_NullToPointer:
5343 case CK_NullToMemberPointer:
5344 case CK_BaseToDerivedMemberPointer:
5345 case CK_DerivedToBaseMemberPointer:
5346 case CK_ReinterpretMemberPointer:
5347 case CK_ConstructorConversion:
5348 case CK_IntegralToPointer:
5350 case CK_VectorSplat:
5351 case CK_IntegralToFloating:
5352 case CK_FloatingCast:
5353 case CK_CPointerToObjCPointerCast:
5354 case CK_BlockPointerToObjCPointerCast:
5355 case CK_AnyPointerToBlockPointerCast:
5356 case CK_ObjCObjectLValueCast:
5357 case CK_FloatingRealToComplex:
5358 case CK_FloatingComplexToReal:
5359 case CK_FloatingComplexCast:
5360 case CK_FloatingComplexToIntegralComplex:
5361 case CK_IntegralRealToComplex:
5362 case CK_IntegralComplexCast:
5363 case CK_IntegralComplexToFloatingComplex:
5364 case CK_BuiltinFnToFnPtr:
5365 llvm_unreachable("invalid cast kind for integral value");
5369 case CK_LValueBitCast:
5370 case CK_ARCProduceObject:
5371 case CK_ARCConsumeObject:
5372 case CK_ARCReclaimReturnedObject:
5373 case CK_ARCExtendBlockObject:
5374 case CK_CopyAndAutoreleaseBlockObject:
5377 case CK_UserDefinedConversion:
5378 case CK_LValueToRValue:
5379 case CK_AtomicToNonAtomic:
5380 case CK_NonAtomicToAtomic:
5382 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5384 case CK_MemberPointerToBoolean:
5385 case CK_PointerToBoolean:
5386 case CK_IntegralToBoolean:
5387 case CK_FloatingToBoolean:
5388 case CK_FloatingComplexToBoolean:
5389 case CK_IntegralComplexToBoolean: {
5391 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
5393 return Success(BoolResult, E);
5396 case CK_IntegralCast: {
5397 if (!Visit(SubExpr))
5400 if (!Result.isInt()) {
5401 // Allow casts of address-of-label differences if they are no-ops
5402 // or narrowing. (The narrowing case isn't actually guaranteed to
5403 // be constant-evaluatable except in some narrow cases which are hard
5404 // to detect here. We let it through on the assumption the user knows
5405 // what they are doing.)
5406 if (Result.isAddrLabelDiff())
5407 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
5408 // Only allow casts of lvalues if they are lossless.
5409 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5412 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5413 Result.getInt()), E);
5416 case CK_PointerToIntegral: {
5417 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5420 if (!EvaluatePointer(SubExpr, LV, Info))
5423 if (LV.getLValueBase()) {
5424 // Only allow based lvalue casts if they are lossless.
5425 // FIXME: Allow a larger integer size than the pointer size, and allow
5426 // narrowing back down to pointer width in subsequent integral casts.
5427 // FIXME: Check integer type's active bits, not its type size.
5428 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
5431 LV.Designator.setInvalid();
5432 LV.moveInto(Result);
5436 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5438 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
5441 case CK_IntegralComplexToReal: {
5443 if (!EvaluateComplex(SubExpr, C, Info))
5445 return Success(C.getComplexIntReal(), E);
5448 case CK_FloatingToIntegral: {
5450 if (!EvaluateFloat(SubExpr, F, Info))
5454 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5456 return Success(Value, E);
5460 llvm_unreachable("unknown cast resulting in integral value");
5463 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5464 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5466 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5468 if (!LV.isComplexInt())
5470 return Success(LV.getComplexIntReal(), E);
5473 return Visit(E->getSubExpr());
5476 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5477 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
5479 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5481 if (!LV.isComplexInt())
5483 return Success(LV.getComplexIntImag(), E);
5486 VisitIgnoredValue(E->getSubExpr());
5487 return Success(0, E);
5490 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5491 return Success(E->getPackLength(), E);
5494 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5495 return Success(E->getValue(), E);
5498 //===----------------------------------------------------------------------===//
5500 //===----------------------------------------------------------------------===//
5503 class FloatExprEvaluator
5504 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
5507 FloatExprEvaluator(EvalInfo &info, APFloat &result)
5508 : ExprEvaluatorBaseTy(info), Result(result) {}
5510 bool Success(const APValue &V, const Expr *e) {
5511 Result = V.getFloat();
5515 bool ZeroInitialization(const Expr *E) {
5516 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5520 bool VisitCallExpr(const CallExpr *E);
5522 bool VisitUnaryOperator(const UnaryOperator *E);
5523 bool VisitBinaryOperator(const BinaryOperator *E);
5524 bool VisitFloatingLiteral(const FloatingLiteral *E);
5525 bool VisitCastExpr(const CastExpr *E);
5527 bool VisitUnaryReal(const UnaryOperator *E);
5528 bool VisitUnaryImag(const UnaryOperator *E);
5530 // FIXME: Missing: array subscript of vector, member of vector
5532 } // end anonymous namespace
5534 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
5535 assert(E->isRValue() && E->getType()->isRealFloatingType());
5536 return FloatExprEvaluator(Info, Result).Visit(E);
5539 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
5543 llvm::APFloat &Result) {
5544 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5545 if (!S) return false;
5547 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5551 // Treat empty strings as if they were zero.
5552 if (S->getString().empty())
5553 fill = llvm::APInt(32, 0);
5554 else if (S->getString().getAsInteger(0, fill))
5558 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5560 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5564 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
5565 switch (E->isBuiltinCall()) {
5567 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5569 case Builtin::BI__builtin_huge_val:
5570 case Builtin::BI__builtin_huge_valf:
5571 case Builtin::BI__builtin_huge_vall:
5572 case Builtin::BI__builtin_inf:
5573 case Builtin::BI__builtin_inff:
5574 case Builtin::BI__builtin_infl: {
5575 const llvm::fltSemantics &Sem =
5576 Info.Ctx.getFloatTypeSemantics(E->getType());
5577 Result = llvm::APFloat::getInf(Sem);
5581 case Builtin::BI__builtin_nans:
5582 case Builtin::BI__builtin_nansf:
5583 case Builtin::BI__builtin_nansl:
5584 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5589 case Builtin::BI__builtin_nan:
5590 case Builtin::BI__builtin_nanf:
5591 case Builtin::BI__builtin_nanl:
5592 // If this is __builtin_nan() turn this into a nan, otherwise we
5593 // can't constant fold it.
5594 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5599 case Builtin::BI__builtin_fabs:
5600 case Builtin::BI__builtin_fabsf:
5601 case Builtin::BI__builtin_fabsl:
5602 if (!EvaluateFloat(E->getArg(0), Result, Info))
5605 if (Result.isNegative())
5606 Result.changeSign();
5609 case Builtin::BI__builtin_copysign:
5610 case Builtin::BI__builtin_copysignf:
5611 case Builtin::BI__builtin_copysignl: {
5613 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5614 !EvaluateFloat(E->getArg(1), RHS, Info))
5616 Result.copySign(RHS);
5622 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5623 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5625 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5627 Result = CV.FloatReal;
5631 return Visit(E->getSubExpr());
5634 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5635 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5637 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5639 Result = CV.FloatImag;
5643 VisitIgnoredValue(E->getSubExpr());
5644 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5645 Result = llvm::APFloat::getZero(Sem);
5649 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5650 switch (E->getOpcode()) {
5651 default: return Error(E);
5653 return EvaluateFloat(E->getSubExpr(), Result, Info);
5655 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5657 Result.changeSign();
5662 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5663 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5664 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5667 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5668 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5670 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
5673 switch (E->getOpcode()) {
5674 default: return Error(E);
5676 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
5679 Result.add(RHS, APFloat::rmNearestTiesToEven);
5682 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
5685 Result.divide(RHS, APFloat::rmNearestTiesToEven);
5689 if (Result.isInfinity() || Result.isNaN())
5690 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5694 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5695 Result = E->getValue();
5699 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5700 const Expr* SubExpr = E->getSubExpr();
5702 switch (E->getCastKind()) {
5704 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5706 case CK_IntegralToFloating: {
5708 return EvaluateInteger(SubExpr, IntResult, Info) &&
5709 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5710 E->getType(), Result);
5713 case CK_FloatingCast: {
5714 if (!Visit(SubExpr))
5716 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5720 case CK_FloatingComplexToReal: {
5722 if (!EvaluateComplex(SubExpr, V, Info))
5724 Result = V.getComplexFloatReal();
5730 //===----------------------------------------------------------------------===//
5731 // Complex Evaluation (for float and integer)
5732 //===----------------------------------------------------------------------===//
5735 class ComplexExprEvaluator
5736 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5737 ComplexValue &Result;
5740 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5741 : ExprEvaluatorBaseTy(info), Result(Result) {}
5743 bool Success(const APValue &V, const Expr *e) {
5748 bool ZeroInitialization(const Expr *E);
5750 //===--------------------------------------------------------------------===//
5752 //===--------------------------------------------------------------------===//
5754 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5755 bool VisitCastExpr(const CastExpr *E);
5756 bool VisitBinaryOperator(const BinaryOperator *E);
5757 bool VisitUnaryOperator(const UnaryOperator *E);
5758 bool VisitInitListExpr(const InitListExpr *E);
5760 } // end anonymous namespace
5762 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5764 assert(E->isRValue() && E->getType()->isAnyComplexType());
5765 return ComplexExprEvaluator(Info, Result).Visit(E);
5768 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5769 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
5770 if (ElemTy->isRealFloatingType()) {
5771 Result.makeComplexFloat();
5772 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5773 Result.FloatReal = Zero;
5774 Result.FloatImag = Zero;
5776 Result.makeComplexInt();
5777 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5778 Result.IntReal = Zero;
5779 Result.IntImag = Zero;
5784 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5785 const Expr* SubExpr = E->getSubExpr();
5787 if (SubExpr->getType()->isRealFloatingType()) {
5788 Result.makeComplexFloat();
5789 APFloat &Imag = Result.FloatImag;
5790 if (!EvaluateFloat(SubExpr, Imag, Info))
5793 Result.FloatReal = APFloat(Imag.getSemantics());
5796 assert(SubExpr->getType()->isIntegerType() &&
5797 "Unexpected imaginary literal.");
5799 Result.makeComplexInt();
5800 APSInt &Imag = Result.IntImag;
5801 if (!EvaluateInteger(SubExpr, Imag, Info))
5804 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5809 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5811 switch (E->getCastKind()) {
5813 case CK_BaseToDerived:
5814 case CK_DerivedToBase:
5815 case CK_UncheckedDerivedToBase:
5818 case CK_ArrayToPointerDecay:
5819 case CK_FunctionToPointerDecay:
5820 case CK_NullToPointer:
5821 case CK_NullToMemberPointer:
5822 case CK_BaseToDerivedMemberPointer:
5823 case CK_DerivedToBaseMemberPointer:
5824 case CK_MemberPointerToBoolean:
5825 case CK_ReinterpretMemberPointer:
5826 case CK_ConstructorConversion:
5827 case CK_IntegralToPointer:
5828 case CK_PointerToIntegral:
5829 case CK_PointerToBoolean:
5831 case CK_VectorSplat:
5832 case CK_IntegralCast:
5833 case CK_IntegralToBoolean:
5834 case CK_IntegralToFloating:
5835 case CK_FloatingToIntegral:
5836 case CK_FloatingToBoolean:
5837 case CK_FloatingCast:
5838 case CK_CPointerToObjCPointerCast:
5839 case CK_BlockPointerToObjCPointerCast:
5840 case CK_AnyPointerToBlockPointerCast:
5841 case CK_ObjCObjectLValueCast:
5842 case CK_FloatingComplexToReal:
5843 case CK_FloatingComplexToBoolean:
5844 case CK_IntegralComplexToReal:
5845 case CK_IntegralComplexToBoolean:
5846 case CK_ARCProduceObject:
5847 case CK_ARCConsumeObject:
5848 case CK_ARCReclaimReturnedObject:
5849 case CK_ARCExtendBlockObject:
5850 case CK_CopyAndAutoreleaseBlockObject:
5851 case CK_BuiltinFnToFnPtr:
5852 llvm_unreachable("invalid cast kind for complex value");
5854 case CK_LValueToRValue:
5855 case CK_AtomicToNonAtomic:
5856 case CK_NonAtomicToAtomic:
5858 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5861 case CK_LValueBitCast:
5862 case CK_UserDefinedConversion:
5865 case CK_FloatingRealToComplex: {
5866 APFloat &Real = Result.FloatReal;
5867 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5870 Result.makeComplexFloat();
5871 Result.FloatImag = APFloat(Real.getSemantics());
5875 case CK_FloatingComplexCast: {
5876 if (!Visit(E->getSubExpr()))
5879 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5881 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5883 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5884 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5887 case CK_FloatingComplexToIntegralComplex: {
5888 if (!Visit(E->getSubExpr()))
5891 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5893 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5894 Result.makeComplexInt();
5895 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5896 To, Result.IntReal) &&
5897 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5898 To, Result.IntImag);
5901 case CK_IntegralRealToComplex: {
5902 APSInt &Real = Result.IntReal;
5903 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5906 Result.makeComplexInt();
5907 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5911 case CK_IntegralComplexCast: {
5912 if (!Visit(E->getSubExpr()))
5915 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5917 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5919 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5920 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
5924 case CK_IntegralComplexToFloatingComplex: {
5925 if (!Visit(E->getSubExpr()))
5928 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
5930 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
5931 Result.makeComplexFloat();
5932 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5933 To, Result.FloatReal) &&
5934 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5935 To, Result.FloatImag);
5939 llvm_unreachable("unknown cast resulting in complex value");
5942 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5943 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5944 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5946 bool LHSOK = Visit(E->getLHS());
5947 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5951 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5954 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5955 "Invalid operands to binary operator.");
5956 switch (E->getOpcode()) {
5957 default: return Error(E);
5959 if (Result.isComplexFloat()) {
5960 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5961 APFloat::rmNearestTiesToEven);
5962 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5963 APFloat::rmNearestTiesToEven);
5965 Result.getComplexIntReal() += RHS.getComplexIntReal();
5966 Result.getComplexIntImag() += RHS.getComplexIntImag();
5970 if (Result.isComplexFloat()) {
5971 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5972 APFloat::rmNearestTiesToEven);
5973 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5974 APFloat::rmNearestTiesToEven);
5976 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5977 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5981 if (Result.isComplexFloat()) {
5982 ComplexValue LHS = Result;
5983 APFloat &LHS_r = LHS.getComplexFloatReal();
5984 APFloat &LHS_i = LHS.getComplexFloatImag();
5985 APFloat &RHS_r = RHS.getComplexFloatReal();
5986 APFloat &RHS_i = RHS.getComplexFloatImag();
5988 APFloat Tmp = LHS_r;
5989 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5990 Result.getComplexFloatReal() = Tmp;
5992 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5993 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5996 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5997 Result.getComplexFloatImag() = Tmp;
5999 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6000 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6002 ComplexValue LHS = Result;
6003 Result.getComplexIntReal() =
6004 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6005 LHS.getComplexIntImag() * RHS.getComplexIntImag());
6006 Result.getComplexIntImag() =
6007 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6008 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6012 if (Result.isComplexFloat()) {
6013 ComplexValue LHS = Result;
6014 APFloat &LHS_r = LHS.getComplexFloatReal();
6015 APFloat &LHS_i = LHS.getComplexFloatImag();
6016 APFloat &RHS_r = RHS.getComplexFloatReal();
6017 APFloat &RHS_i = RHS.getComplexFloatImag();
6018 APFloat &Res_r = Result.getComplexFloatReal();
6019 APFloat &Res_i = Result.getComplexFloatImag();
6021 APFloat Den = RHS_r;
6022 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6023 APFloat Tmp = RHS_i;
6024 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6025 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6028 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6030 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6031 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6032 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6035 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6037 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6038 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6039 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6041 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6042 return Error(E, diag::note_expr_divide_by_zero);
6044 ComplexValue LHS = Result;
6045 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6046 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6047 Result.getComplexIntReal() =
6048 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6049 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6050 Result.getComplexIntImag() =
6051 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6052 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6060 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6061 // Get the operand value into 'Result'.
6062 if (!Visit(E->getSubExpr()))
6065 switch (E->getOpcode()) {
6071 // The result is always just the subexpr.
6074 if (Result.isComplexFloat()) {
6075 Result.getComplexFloatReal().changeSign();
6076 Result.getComplexFloatImag().changeSign();
6079 Result.getComplexIntReal() = -Result.getComplexIntReal();
6080 Result.getComplexIntImag() = -Result.getComplexIntImag();
6084 if (Result.isComplexFloat())
6085 Result.getComplexFloatImag().changeSign();
6087 Result.getComplexIntImag() = -Result.getComplexIntImag();
6092 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6093 if (E->getNumInits() == 2) {
6094 if (E->getType()->isComplexType()) {
6095 Result.makeComplexFloat();
6096 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6098 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6101 Result.makeComplexInt();
6102 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6104 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6109 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6112 //===----------------------------------------------------------------------===//
6113 // Void expression evaluation, primarily for a cast to void on the LHS of a
6115 //===----------------------------------------------------------------------===//
6118 class VoidExprEvaluator
6119 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6121 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6123 bool Success(const APValue &V, const Expr *e) { return true; }
6125 bool VisitCastExpr(const CastExpr *E) {
6126 switch (E->getCastKind()) {
6128 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6130 VisitIgnoredValue(E->getSubExpr());
6135 } // end anonymous namespace
6137 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6138 assert(E->isRValue() && E->getType()->isVoidType());
6139 return VoidExprEvaluator(Info).Visit(E);
6142 //===----------------------------------------------------------------------===//
6143 // Top level Expr::EvaluateAsRValue method.
6144 //===----------------------------------------------------------------------===//
6146 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
6147 // In C, function designators are not lvalues, but we evaluate them as if they
6149 if (E->isGLValue() || E->getType()->isFunctionType()) {
6151 if (!EvaluateLValue(E, LV, Info))
6153 LV.moveInto(Result);
6154 } else if (E->getType()->isVectorType()) {
6155 if (!EvaluateVector(E, Result, Info))
6157 } else if (E->getType()->isIntegralOrEnumerationType()) {
6158 if (!IntExprEvaluator(Info, Result).Visit(E))
6160 } else if (E->getType()->hasPointerRepresentation()) {
6162 if (!EvaluatePointer(E, LV, Info))
6164 LV.moveInto(Result);
6165 } else if (E->getType()->isRealFloatingType()) {
6166 llvm::APFloat F(0.0);
6167 if (!EvaluateFloat(E, F, Info))
6169 Result = APValue(F);
6170 } else if (E->getType()->isAnyComplexType()) {
6172 if (!EvaluateComplex(E, C, Info))
6175 } else if (E->getType()->isMemberPointerType()) {
6177 if (!EvaluateMemberPointer(E, P, Info))
6181 } else if (E->getType()->isArrayType()) {
6183 LV.set(E, Info.CurrentCall->Index);
6184 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
6186 Result = Info.CurrentCall->Temporaries[E];
6187 } else if (E->getType()->isRecordType()) {
6189 LV.set(E, Info.CurrentCall->Index);
6190 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6192 Result = Info.CurrentCall->Temporaries[E];
6193 } else if (E->getType()->isVoidType()) {
6194 if (!Info.getLangOpts().CPlusPlus0x)
6195 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
6197 if (!EvaluateVoid(E, Info))
6199 } else if (Info.getLangOpts().CPlusPlus0x) {
6200 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
6203 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
6210 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6211 /// cases, the in-place evaluation is essential, since later initializers for
6212 /// an object can indirectly refer to subobjects which were initialized earlier.
6213 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6214 const Expr *E, CheckConstantExpressionKind CCEK,
6215 bool AllowNonLiteralTypes) {
6216 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
6219 if (E->isRValue()) {
6220 // Evaluate arrays and record types in-place, so that later initializers can
6221 // refer to earlier-initialized members of the object.
6222 if (E->getType()->isArrayType())
6223 return EvaluateArray(E, This, Result, Info);
6224 else if (E->getType()->isRecordType())
6225 return EvaluateRecord(E, This, Result, Info);
6228 // For any other type, in-place evaluation is unimportant.
6229 return Evaluate(Result, Info, E);
6232 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6233 /// lvalue-to-rvalue cast if it is an lvalue.
6234 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
6235 if (!CheckLiteralType(Info, E))
6238 if (!::Evaluate(Result, Info, E))
6241 if (E->isGLValue()) {
6243 LV.setFrom(Info.Ctx, Result);
6244 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
6248 // Check this core constant expression is a constant expression.
6249 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
6252 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
6253 /// any crazy technique (that has nothing to do with language standards) that
6254 /// we want to. If this function returns true, it returns the folded constant
6255 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6256 /// will be applied to the result.
6257 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
6258 // Fast-path evaluations of integer literals, since we sometimes see files
6259 // containing vast quantities of these.
6260 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6261 Result.Val = APValue(APSInt(L->getValue(),
6262 L->getType()->isUnsignedIntegerType()));
6266 // FIXME: Evaluating values of large array and record types can cause
6267 // performance problems. Only do so in C++11 for now.
6268 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6269 !Ctx.getLangOpts().CPlusPlus0x)
6272 EvalInfo Info(Ctx, Result);
6273 return ::EvaluateAsRValue(Info, this, Result.Val);
6276 bool Expr::EvaluateAsBooleanCondition(bool &Result,
6277 const ASTContext &Ctx) const {
6279 return EvaluateAsRValue(Scratch, Ctx) &&
6280 HandleConversionToBool(Scratch.Val, Result);
6283 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6284 SideEffectsKind AllowSideEffects) const {
6285 if (!getType()->isIntegralOrEnumerationType())
6288 EvalResult ExprResult;
6289 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6290 (!AllowSideEffects && ExprResult.HasSideEffects))
6293 Result = ExprResult.Val.getInt();
6297 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
6298 EvalInfo Info(Ctx, Result);
6301 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6302 !CheckLValueConstantExpression(Info, getExprLoc(),
6303 Ctx.getLValueReferenceType(getType()), LV))
6306 LV.moveInto(Result.Val);
6310 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6312 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
6313 // FIXME: Evaluating initializers for large array and record types can cause
6314 // performance problems. Only do so in C++11 for now.
6315 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6316 !Ctx.getLangOpts().CPlusPlus0x)
6319 Expr::EvalStatus EStatus;
6320 EStatus.Diag = &Notes;
6322 EvalInfo InitInfo(Ctx, EStatus);
6323 InitInfo.setEvaluatingDecl(VD, Value);
6328 // C++11 [basic.start.init]p2:
6329 // Variables with static storage duration or thread storage duration shall be
6330 // zero-initialized before any other initialization takes place.
6331 // This behavior is not present in C.
6332 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
6333 !VD->getType()->isReferenceType()) {
6334 ImplicitValueInitExpr VIE(VD->getType());
6335 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6336 /*AllowNonLiteralTypes=*/true))
6340 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6341 /*AllowNonLiteralTypes=*/true) ||
6342 EStatus.HasSideEffects)
6345 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6349 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6350 /// constant folded, but discard the result.
6351 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
6353 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
6356 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
6357 EvalResult EvalResult;
6358 bool Result = EvaluateAsRValue(EvalResult, Ctx);
6360 assert(Result && "Could not evaluate expression");
6361 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
6363 return EvalResult.Val.getInt();
6366 bool Expr::EvalResult::isGlobalLValue() const {
6367 assert(Val.isLValue());
6368 return IsGlobalLValue(Val.getLValueBase());
6372 /// isIntegerConstantExpr - this recursive routine will test if an expression is
6373 /// an integer constant expression.
6375 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6378 /// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6379 /// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6380 /// cast+dereference.
6382 // CheckICE - This function does the fundamental ICE checking: the returned
6383 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6384 // Note that to reduce code duplication, this helper does no evaluation
6385 // itself; the caller checks whether the expression is evaluatable, and
6386 // in the rare cases where CheckICE actually cares about the evaluated
6387 // value, it calls into Evalute.
6390 // 0: This expression is an ICE.
6391 // 1: This expression is not an ICE, but if it isn't evaluated, it's
6392 // a legal subexpression for an ICE. This return value is used to handle
6393 // the comma operator in C99 mode.
6394 // 2: This expression is not an ICE, and is not a legal subexpression for one.
6403 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6404 ICEDiag() : Val(0) {}
6409 static ICEDiag NoDiag() { return ICEDiag(); }
6411 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6412 Expr::EvalResult EVResult;
6413 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
6414 !EVResult.Val.isInt()) {
6415 return ICEDiag(2, E->getLocStart());
6420 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6421 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
6422 if (!E->getType()->isIntegralOrEnumerationType()) {
6423 return ICEDiag(2, E->getLocStart());
6426 switch (E->getStmtClass()) {
6427 #define ABSTRACT_STMT(Node)
6428 #define STMT(Node, Base) case Expr::Node##Class:
6429 #define EXPR(Node, Base)
6430 #include "clang/AST/StmtNodes.inc"
6431 case Expr::PredefinedExprClass:
6432 case Expr::FloatingLiteralClass:
6433 case Expr::ImaginaryLiteralClass:
6434 case Expr::StringLiteralClass:
6435 case Expr::ArraySubscriptExprClass:
6436 case Expr::MemberExprClass:
6437 case Expr::CompoundAssignOperatorClass:
6438 case Expr::CompoundLiteralExprClass:
6439 case Expr::ExtVectorElementExprClass:
6440 case Expr::DesignatedInitExprClass:
6441 case Expr::ImplicitValueInitExprClass:
6442 case Expr::ParenListExprClass:
6443 case Expr::VAArgExprClass:
6444 case Expr::AddrLabelExprClass:
6445 case Expr::StmtExprClass:
6446 case Expr::CXXMemberCallExprClass:
6447 case Expr::CUDAKernelCallExprClass:
6448 case Expr::CXXDynamicCastExprClass:
6449 case Expr::CXXTypeidExprClass:
6450 case Expr::CXXUuidofExprClass:
6451 case Expr::CXXNullPtrLiteralExprClass:
6452 case Expr::UserDefinedLiteralClass:
6453 case Expr::CXXThisExprClass:
6454 case Expr::CXXThrowExprClass:
6455 case Expr::CXXNewExprClass:
6456 case Expr::CXXDeleteExprClass:
6457 case Expr::CXXPseudoDestructorExprClass:
6458 case Expr::UnresolvedLookupExprClass:
6459 case Expr::DependentScopeDeclRefExprClass:
6460 case Expr::CXXConstructExprClass:
6461 case Expr::CXXBindTemporaryExprClass:
6462 case Expr::ExprWithCleanupsClass:
6463 case Expr::CXXTemporaryObjectExprClass:
6464 case Expr::CXXUnresolvedConstructExprClass:
6465 case Expr::CXXDependentScopeMemberExprClass:
6466 case Expr::UnresolvedMemberExprClass:
6467 case Expr::ObjCStringLiteralClass:
6468 case Expr::ObjCBoxedExprClass:
6469 case Expr::ObjCArrayLiteralClass:
6470 case Expr::ObjCDictionaryLiteralClass:
6471 case Expr::ObjCEncodeExprClass:
6472 case Expr::ObjCMessageExprClass:
6473 case Expr::ObjCSelectorExprClass:
6474 case Expr::ObjCProtocolExprClass:
6475 case Expr::ObjCIvarRefExprClass:
6476 case Expr::ObjCPropertyRefExprClass:
6477 case Expr::ObjCSubscriptRefExprClass:
6478 case Expr::ObjCIsaExprClass:
6479 case Expr::ShuffleVectorExprClass:
6480 case Expr::BlockExprClass:
6481 case Expr::NoStmtClass:
6482 case Expr::OpaqueValueExprClass:
6483 case Expr::PackExpansionExprClass:
6484 case Expr::SubstNonTypeTemplateParmPackExprClass:
6485 case Expr::FunctionParmPackExprClass:
6486 case Expr::AsTypeExprClass:
6487 case Expr::ObjCIndirectCopyRestoreExprClass:
6488 case Expr::MaterializeTemporaryExprClass:
6489 case Expr::PseudoObjectExprClass:
6490 case Expr::AtomicExprClass:
6491 case Expr::InitListExprClass:
6492 case Expr::LambdaExprClass:
6493 return ICEDiag(2, E->getLocStart());
6495 case Expr::SizeOfPackExprClass:
6496 case Expr::GNUNullExprClass:
6497 // GCC considers the GNU __null value to be an integral constant expression.
6500 case Expr::SubstNonTypeTemplateParmExprClass:
6502 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6504 case Expr::ParenExprClass:
6505 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
6506 case Expr::GenericSelectionExprClass:
6507 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
6508 case Expr::IntegerLiteralClass:
6509 case Expr::CharacterLiteralClass:
6510 case Expr::ObjCBoolLiteralExprClass:
6511 case Expr::CXXBoolLiteralExprClass:
6512 case Expr::CXXScalarValueInitExprClass:
6513 case Expr::UnaryTypeTraitExprClass:
6514 case Expr::BinaryTypeTraitExprClass:
6515 case Expr::TypeTraitExprClass:
6516 case Expr::ArrayTypeTraitExprClass:
6517 case Expr::ExpressionTraitExprClass:
6518 case Expr::CXXNoexceptExprClass:
6520 case Expr::CallExprClass:
6521 case Expr::CXXOperatorCallExprClass: {
6522 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6523 // constant expressions, but they can never be ICEs because an ICE cannot
6524 // contain an operand of (pointer to) function type.
6525 const CallExpr *CE = cast<CallExpr>(E);
6526 if (CE->isBuiltinCall())
6527 return CheckEvalInICE(E, Ctx);
6528 return ICEDiag(2, E->getLocStart());
6530 case Expr::DeclRefExprClass: {
6531 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6533 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6534 if (Ctx.getLangOpts().CPlusPlus &&
6535 D && IsConstNonVolatile(D->getType())) {
6536 // Parameter variables are never constants. Without this check,
6537 // getAnyInitializer() can find a default argument, which leads
6539 if (isa<ParmVarDecl>(D))
6540 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6543 // A variable of non-volatile const-qualified integral or enumeration
6544 // type initialized by an ICE can be used in ICEs.
6545 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
6546 if (!Dcl->getType()->isIntegralOrEnumerationType())
6547 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6550 // Look for a declaration of this variable that has an initializer, and
6551 // check whether it is an ICE.
6552 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6555 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6558 return ICEDiag(2, E->getLocStart());
6560 case Expr::UnaryOperatorClass: {
6561 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6562 switch (Exp->getOpcode()) {
6569 // C99 6.6/3 allows increment and decrement within unevaluated
6570 // subexpressions of constant expressions, but they can never be ICEs
6571 // because an ICE cannot contain an lvalue operand.
6572 return ICEDiag(2, E->getLocStart());
6580 return CheckICE(Exp->getSubExpr(), Ctx);
6583 // OffsetOf falls through here.
6585 case Expr::OffsetOfExprClass: {
6586 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6587 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6588 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6589 // compliance: we should warn earlier for offsetof expressions with
6590 // array subscripts that aren't ICEs, and if the array subscripts
6591 // are ICEs, the value of the offsetof must be an integer constant.
6592 return CheckEvalInICE(E, Ctx);
6594 case Expr::UnaryExprOrTypeTraitExprClass: {
6595 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6596 if ((Exp->getKind() == UETT_SizeOf) &&
6597 Exp->getTypeOfArgument()->isVariableArrayType())
6598 return ICEDiag(2, E->getLocStart());
6601 case Expr::BinaryOperatorClass: {
6602 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6603 switch (Exp->getOpcode()) {
6617 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6618 // constant expressions, but they can never be ICEs because an ICE cannot
6619 // contain an lvalue operand.
6620 return ICEDiag(2, E->getLocStart());
6639 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6640 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6641 if (Exp->getOpcode() == BO_Div ||
6642 Exp->getOpcode() == BO_Rem) {
6643 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
6644 // we don't evaluate one.
6645 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
6646 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
6648 return ICEDiag(1, E->getLocStart());
6649 if (REval.isSigned() && REval.isAllOnesValue()) {
6650 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
6651 if (LEval.isMinSignedValue())
6652 return ICEDiag(1, E->getLocStart());
6656 if (Exp->getOpcode() == BO_Comma) {
6657 if (Ctx.getLangOpts().C99) {
6658 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6659 // if it isn't evaluated.
6660 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6661 return ICEDiag(1, E->getLocStart());
6663 // In both C89 and C++, commas in ICEs are illegal.
6664 return ICEDiag(2, E->getLocStart());
6667 if (LHSResult.Val >= RHSResult.Val)
6673 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6674 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6675 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6676 // Rare case where the RHS has a comma "side-effect"; we need
6677 // to actually check the condition to see whether the side
6678 // with the comma is evaluated.
6679 if ((Exp->getOpcode() == BO_LAnd) !=
6680 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
6685 if (LHSResult.Val >= RHSResult.Val)
6691 case Expr::ImplicitCastExprClass:
6692 case Expr::CStyleCastExprClass:
6693 case Expr::CXXFunctionalCastExprClass:
6694 case Expr::CXXStaticCastExprClass:
6695 case Expr::CXXReinterpretCastExprClass:
6696 case Expr::CXXConstCastExprClass:
6697 case Expr::ObjCBridgedCastExprClass: {
6698 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
6699 if (isa<ExplicitCastExpr>(E)) {
6700 if (const FloatingLiteral *FL
6701 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6702 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6703 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6704 APSInt IgnoredVal(DestWidth, !DestSigned);
6706 // If the value does not fit in the destination type, the behavior is
6707 // undefined, so we are not required to treat it as a constant
6709 if (FL->getValue().convertToInteger(IgnoredVal,
6710 llvm::APFloat::rmTowardZero,
6711 &Ignored) & APFloat::opInvalidOp)
6712 return ICEDiag(2, E->getLocStart());
6716 switch (cast<CastExpr>(E)->getCastKind()) {
6717 case CK_LValueToRValue:
6718 case CK_AtomicToNonAtomic:
6719 case CK_NonAtomicToAtomic:
6721 case CK_IntegralToBoolean:
6722 case CK_IntegralCast:
6723 return CheckICE(SubExpr, Ctx);
6725 return ICEDiag(2, E->getLocStart());
6728 case Expr::BinaryConditionalOperatorClass: {
6729 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6730 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6731 if (CommonResult.Val == 2) return CommonResult;
6732 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6733 if (FalseResult.Val == 2) return FalseResult;
6734 if (CommonResult.Val == 1) return CommonResult;
6735 if (FalseResult.Val == 1 &&
6736 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6739 case Expr::ConditionalOperatorClass: {
6740 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6741 // If the condition (ignoring parens) is a __builtin_constant_p call,
6742 // then only the true side is actually considered in an integer constant
6743 // expression, and it is fully evaluated. This is an important GNU
6744 // extension. See GCC PR38377 for discussion.
6745 if (const CallExpr *CallCE
6746 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6747 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6748 return CheckEvalInICE(E, Ctx);
6749 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6750 if (CondResult.Val == 2)
6753 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6754 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6756 if (TrueResult.Val == 2)
6758 if (FalseResult.Val == 2)
6760 if (CondResult.Val == 1)
6762 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6764 // Rare case where the diagnostics depend on which side is evaluated
6765 // Note that if we get here, CondResult is 0, and at least one of
6766 // TrueResult and FalseResult is non-zero.
6767 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6772 case Expr::CXXDefaultArgExprClass:
6773 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6774 case Expr::ChooseExprClass: {
6775 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6779 llvm_unreachable("Invalid StmtClass!");
6782 /// Evaluate an expression as a C++11 integral constant expression.
6783 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6785 llvm::APSInt *Value,
6786 SourceLocation *Loc) {
6787 if (!E->getType()->isIntegralOrEnumerationType()) {
6788 if (Loc) *Loc = E->getExprLoc();
6793 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6796 assert(Result.isInt() && "pointer cast to int is not an ICE");
6797 if (Value) *Value = Result.getInt();
6801 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6802 if (Ctx.getLangOpts().CPlusPlus0x)
6803 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6805 ICEDiag d = CheckICE(this, Ctx);
6807 if (Loc) *Loc = d.Loc;
6813 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6814 SourceLocation *Loc, bool isEvaluated) const {
6815 if (Ctx.getLangOpts().CPlusPlus0x)
6816 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6818 if (!isIntegerConstantExpr(Ctx, Loc))
6820 if (!EvaluateAsInt(Value, Ctx))
6821 llvm_unreachable("ICE cannot be evaluated!");
6825 bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6826 return CheckICE(this, Ctx).Val == 0;
6829 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6830 SourceLocation *Loc) const {
6831 // We support this checking in C++98 mode in order to diagnose compatibility
6833 assert(Ctx.getLangOpts().CPlusPlus);
6835 // Build evaluation settings.
6836 Expr::EvalStatus Status;
6837 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6838 Status.Diag = &Diags;
6839 EvalInfo Info(Ctx, Status);
6842 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6844 if (!Diags.empty()) {
6845 IsConstExpr = false;
6846 if (Loc) *Loc = Diags[0].first;
6847 } else if (!IsConstExpr) {
6848 // FIXME: This shouldn't happen.
6849 if (Loc) *Loc = getExprLoc();
6855 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6856 llvm::SmallVectorImpl<
6857 PartialDiagnosticAt> &Diags) {
6858 // FIXME: It would be useful to check constexpr function templates, but at the
6859 // moment the constant expression evaluator cannot cope with the non-rigorous
6860 // ASTs which we build for dependent expressions.
6861 if (FD->isDependentContext())
6864 Expr::EvalStatus Status;
6865 Status.Diag = &Diags;
6867 EvalInfo Info(FD->getASTContext(), Status);
6868 Info.CheckingPotentialConstantExpression = true;
6870 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6871 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6873 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6874 // is a temporary being used as the 'this' pointer.
6876 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6877 This.set(&VIE, Info.CurrentCall->Index);
6879 ArrayRef<const Expr*> Args;
6881 SourceLocation Loc = FD->getLocation();
6884 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
6885 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6887 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6888 Args, FD->getBody(), Info, Scratch);
6890 return Diags.empty();