blob: ee8952917690d0e7b25830e09fd92754f664c49f [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Richard Smith0b0a0b62011-10-29 20:57:55 +000031static bool IsParamLValue(const Expr *E);
32
Chris Lattnercdf34e72008-07-11 22:52:41 +000033/// EvalInfo - This is a private struct used by the evaluator to capture
34/// information about a subexpression as it is folded. It retains information
35/// about the AST context, but also maintains information about the folded
36/// expression.
37///
38/// If an expression could be evaluated, it is still possible it is not a C
39/// "integer constant expression" or constant expression. If not, this struct
40/// captures information about how and why not.
41///
42/// One bit of information passed *into* the request for constant folding
43/// indicates whether the subexpression is "evaluated" or not according to C
44/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
45/// evaluate the expression regardless of what the RHS is, but C only allows
46/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000047namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000048 struct CallStackFrame;
49
Richard Smith0b0a0b62011-10-29 20:57:55 +000050 /// A core constant value. This can be the value of any constant expression,
51 /// or a pointer or reference to a non-static object or function parameter.
52 class CCValue : public APValue {
53 typedef llvm::APSInt APSInt;
54 typedef llvm::APFloat APFloat;
55 /// If the value is a DeclRefExpr lvalue referring to a ParmVarDecl, this is
56 /// the index of the corresponding function call.
57 unsigned CallIndex;
58 public:
59 CCValue() {}
60 explicit CCValue(const APSInt &I) : APValue(I) {}
61 explicit CCValue(const APFloat &F) : APValue(F) {}
62 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
63 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
64 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
65 CCValue(const CCValue &V) : APValue(V), CallIndex(V.CallIndex) {}
66 CCValue(const Expr *B, const CharUnits &O, unsigned I) :
67 APValue(B, O), CallIndex(I) {}
68 CCValue(const APValue &V, unsigned CallIndex) :
69 APValue(V), CallIndex(CallIndex) {}
70
71 enum { NoCallIndex = (unsigned)-1 };
72
73 unsigned getLValueCallIndex() const {
74 assert(getKind() == LValue);
75 return CallIndex;
76 }
77 };
78
Benjamin Kramer024e6192011-03-04 13:12:48 +000079 struct EvalInfo {
80 const ASTContext &Ctx;
81
Richard Smith725810a2011-10-16 21:26:27 +000082 /// EvalStatus - Contains information about the evaluation.
83 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000084
Richard Smith254a73d2011-10-28 22:34:42 +000085 /// CurrentCall - The top of the constexpr call stack.
86 const CallStackFrame *CurrentCall;
87
88 /// NumCalls - The number of calls we've evaluated so far.
89 unsigned NumCalls;
90
91 /// CallStackDepth - The number of calls in the call stack right now.
92 unsigned CallStackDepth;
93
Richard Smith0b0a0b62011-10-29 20:57:55 +000094 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
Benjamin Kramer024e6192011-03-04 13:12:48 +000095 MapTy OpaqueValues;
Richard Smith0b0a0b62011-10-29 20:57:55 +000096 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Benjamin Kramer024e6192011-03-04 13:12:48 +000097 MapTy::const_iterator i = OpaqueValues.find(e);
98 if (i == OpaqueValues.end()) return 0;
99 return &i->second;
100 }
101
Richard Smith0b0a0b62011-10-29 20:57:55 +0000102 unsigned getCurrentCallIndex() const;
103 const CCValue *getCallValue(unsigned CallIndex, unsigned ArgIndex) const;
104
Richard Smith725810a2011-10-16 21:26:27 +0000105 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith254a73d2011-10-28 22:34:42 +0000106 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0) {}
Richard Smith4ce706a2011-10-11 21:43:33 +0000107
108 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +0000109 };
110
Richard Smith254a73d2011-10-28 22:34:42 +0000111 /// A stack frame in the constexpr call stack.
112 struct CallStackFrame {
113 EvalInfo &Info;
114
115 /// Parent - The caller of this stack frame.
116 const CallStackFrame *Caller;
117
118 /// ParmBindings - Parameter bindings for this function call, indexed by
119 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000120 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000121
122 /// CallIndex - The index of the current call. This is used to match lvalues
123 /// referring to parameters up with the corresponding stack frame, and to
124 /// detect when the parameter is no longer in scope.
125 unsigned CallIndex;
126
Richard Smith0b0a0b62011-10-29 20:57:55 +0000127 CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smith254a73d2011-10-28 22:34:42 +0000128 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments),
129 CallIndex(Info.NumCalls++) {
130 Info.CurrentCall = this;
131 ++Info.CallStackDepth;
132 }
133 ~CallStackFrame() {
134 assert(Info.CurrentCall == this && "calls retired out of order");
135 --Info.CallStackDepth;
136 Info.CurrentCall = Caller;
137 }
138 };
139
Richard Smith0b0a0b62011-10-29 20:57:55 +0000140 unsigned EvalInfo::getCurrentCallIndex() const {
141 return CurrentCall ? CurrentCall->CallIndex : CCValue::NoCallIndex;
142 }
143
144 const CCValue *EvalInfo::getCallValue(unsigned CallIndex,
145 unsigned ArgIndex) const {
146 for (const CallStackFrame *Frame = CurrentCall;
147 Frame && Frame->CallIndex >= CallIndex; Frame = Frame->Caller)
148 if (Frame->CallIndex == CallIndex)
149 return Frame->Arguments + ArgIndex;
150 return 0;
151 }
152
John McCall93d91dc2010-05-07 17:22:02 +0000153 struct ComplexValue {
154 private:
155 bool IsInt;
156
157 public:
158 APSInt IntReal, IntImag;
159 APFloat FloatReal, FloatImag;
160
161 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
162
163 void makeComplexFloat() { IsInt = false; }
164 bool isComplexFloat() const { return !IsInt; }
165 APFloat &getComplexFloatReal() { return FloatReal; }
166 APFloat &getComplexFloatImag() { return FloatImag; }
167
168 void makeComplexInt() { IsInt = true; }
169 bool isComplexInt() const { return IsInt; }
170 APSInt &getComplexIntReal() { return IntReal; }
171 APSInt &getComplexIntImag() { return IntImag; }
172
Richard Smith0b0a0b62011-10-29 20:57:55 +0000173 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000174 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000175 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000176 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000177 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000178 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000179 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000180 assert(v.isComplexFloat() || v.isComplexInt());
181 if (v.isComplexFloat()) {
182 makeComplexFloat();
183 FloatReal = v.getComplexFloatReal();
184 FloatImag = v.getComplexFloatImag();
185 } else {
186 makeComplexInt();
187 IntReal = v.getComplexIntReal();
188 IntImag = v.getComplexIntImag();
189 }
190 }
John McCall93d91dc2010-05-07 17:22:02 +0000191 };
John McCall45d55e42010-05-07 21:00:08 +0000192
193 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000194 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000195 CharUnits Offset;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000196 unsigned CallIndex;
John McCall45d55e42010-05-07 21:00:08 +0000197
Richard Smith8b3497e2011-10-31 01:37:14 +0000198 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000199 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000200 const CharUnits &getLValueOffset() const { return Offset; }
201 unsigned getLValueCallIndex() const { return CallIndex; }
John McCall45d55e42010-05-07 21:00:08 +0000202
Richard Smith0b0a0b62011-10-29 20:57:55 +0000203 void moveInto(CCValue &V) const {
204 V = CCValue(Base, Offset, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000205 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000206 void setFrom(const CCValue &V) {
207 assert(V.isLValue());
208 Base = V.getLValueBase();
209 Offset = V.getLValueOffset();
210 CallIndex = V.getLValueCallIndex();
John McCallc07a0c72011-02-17 10:25:35 +0000211 }
John McCall45d55e42010-05-07 21:00:08 +0000212 };
John McCall93d91dc2010-05-07 17:22:02 +0000213}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000214
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000216static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
217static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000218static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000219static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000220 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000221static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000222static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000223
224//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000225// Misc utilities
226//===----------------------------------------------------------------------===//
227
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000228static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000229 if (!E) return true;
230
231 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
232 if (isa<FunctionDecl>(DRE->getDecl()))
233 return true;
234 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
235 return VD->hasGlobalStorage();
236 return false;
237 }
238
239 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
240 return CLE->isFileScope();
241
Richard Smith11562c52011-10-28 17:51:58 +0000242 if (isa<MemberExpr>(E))
243 return false;
244
John McCall95007602010-05-10 23:27:23 +0000245 return true;
246}
247
Richard Smith0b0a0b62011-10-29 20:57:55 +0000248static bool IsParamLValue(const Expr *E) {
249 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
250 return isa<ParmVarDecl>(DRE->getDecl());
251 return false;
252}
253
254/// Check that this core constant expression value is a valid value for a
255/// constant expression.
256static bool CheckConstantExpression(const CCValue &Value) {
257 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
258}
259
Richard Smith11562c52011-10-28 17:51:58 +0000260static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000261 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000262
John McCalleb3e4f32010-05-07 21:34:32 +0000263 // A null base expression indicates a null pointer. These are always
264 // evaluatable, and they are false unless the offset is zero.
265 if (!Base) {
266 Result = !Value.Offset.isZero();
267 return true;
268 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000269
John McCall95007602010-05-10 23:27:23 +0000270 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000271 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000272 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000273
John McCalleb3e4f32010-05-07 21:34:32 +0000274 // We have a non-null base expression. These are generally known to
275 // be true, but if it'a decl-ref to a weak symbol it can be null at
276 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000277 Result = true;
278
279 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000280 if (!DeclRef)
281 return true;
282
John McCalleb3e4f32010-05-07 21:34:32 +0000283 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000284 const ValueDecl* Decl = DeclRef->getDecl();
285 if (Decl->hasAttr<WeakAttr>() ||
286 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000287 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000288 return false;
289
Eli Friedman334046a2009-06-14 02:17:33 +0000290 return true;
291}
292
Richard Smith0b0a0b62011-10-29 20:57:55 +0000293static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000294 switch (Val.getKind()) {
295 case APValue::Uninitialized:
296 return false;
297 case APValue::Int:
298 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000299 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000300 case APValue::Float:
301 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000302 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000303 case APValue::ComplexInt:
304 Result = Val.getComplexIntReal().getBoolValue() ||
305 Val.getComplexIntImag().getBoolValue();
306 return true;
307 case APValue::ComplexFloat:
308 Result = !Val.getComplexFloatReal().isZero() ||
309 !Val.getComplexFloatImag().isZero();
310 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000311 case APValue::LValue: {
312 LValue PointerResult;
313 PointerResult.setFrom(Val);
314 return EvalPointerValueAsBool(PointerResult, Result);
315 }
Richard Smith11562c52011-10-28 17:51:58 +0000316 case APValue::Vector:
317 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000318 }
319
Richard Smith11562c52011-10-28 17:51:58 +0000320 llvm_unreachable("unknown APValue kind");
321}
322
323static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
324 EvalInfo &Info) {
325 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000326 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000327 if (!Evaluate(Val, Info, E))
328 return false;
329 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000330}
331
Mike Stump11289f42009-09-09 15:08:12 +0000332static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000333 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000334 unsigned DestWidth = Ctx.getIntWidth(DestType);
335 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000336 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000337
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000338 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000339 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000340 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000341 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
342 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000343}
344
Mike Stump11289f42009-09-09 15:08:12 +0000345static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000346 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000347 bool ignored;
348 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000349 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000350 APFloat::rmNearestTiesToEven, &ignored);
351 return Result;
352}
353
Mike Stump11289f42009-09-09 15:08:12 +0000354static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000355 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000356 unsigned DestWidth = Ctx.getIntWidth(DestType);
357 APSInt Result = Value;
358 // Figure out if this is a truncate, extend or noop cast.
359 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000360 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000361 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000362 return Result;
363}
364
Mike Stump11289f42009-09-09 15:08:12 +0000365static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000366 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000367
368 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
369 Result.convertFromAPInt(Value, Value.isSigned(),
370 APFloat::rmNearestTiesToEven);
371 return Result;
372}
373
Richard Smith27908702011-10-24 17:54:18 +0000374/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000375static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
376 unsigned CallIndex, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000377 // If this is a parameter to an active constexpr function call, perform
378 // argument substitution.
379 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000380 if (const CCValue *ArgValue =
381 Info.getCallValue(CallIndex, PVD->getFunctionScopeIndex())) {
382 Result = *ArgValue;
383 return true;
384 }
385 return false;
Richard Smith254a73d2011-10-28 22:34:42 +0000386 }
Richard Smith27908702011-10-24 17:54:18 +0000387
388 const Expr *Init = VD->getAnyInitializer();
389 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000390 return false;
Richard Smith27908702011-10-24 17:54:18 +0000391
Richard Smith0b0a0b62011-10-29 20:57:55 +0000392 if (APValue *V = VD->getEvaluatedValue()) {
393 Result = CCValue(*V, CCValue::NoCallIndex);
394 return !Result.isUninit();
395 }
Richard Smith27908702011-10-24 17:54:18 +0000396
397 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000398 return false;
Richard Smith27908702011-10-24 17:54:18 +0000399
400 VD->setEvaluatingValue();
401
Richard Smith0b0a0b62011-10-29 20:57:55 +0000402 Expr::EvalStatus EStatus;
403 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000404 // FIXME: The caller will need to know whether the value was a constant
405 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000406 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000407 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000408 return false;
409 }
Richard Smith27908702011-10-24 17:54:18 +0000410
Richard Smith0b0a0b62011-10-29 20:57:55 +0000411 VD->setEvaluatedValue(Result);
412 return true;
Richard Smith27908702011-10-24 17:54:18 +0000413}
414
Richard Smith11562c52011-10-28 17:51:58 +0000415static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000416 Qualifiers Quals = T.getQualifiers();
417 return Quals.hasConst() && !Quals.hasVolatile();
418}
419
Richard Smith8b3497e2011-10-31 01:37:14 +0000420const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
421 if (!LVal.Base)
422 return 0;
423
424 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
425 return DRE->getDecl();
426
427 // FIXME: Static data members accessed via a MemberExpr are represented as
428 // that MemberExpr. We should use the Decl directly instead.
429 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
430 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
431 return ME->getMemberDecl();
432 }
433
434 return 0;
435}
436
Richard Smith11562c52011-10-28 17:51:58 +0000437bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000438 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000439 const Expr *Base = LVal.Base;
440
441 // FIXME: Indirection through a null pointer deserves a diagnostic.
442 if (!Base)
443 return false;
444
445 // FIXME: Support accessing subobjects of objects of literal types. A simple
446 // byte offset is insufficient for C++11 semantics: we need to know how the
447 // reference was formed (which union member was named, for instance).
448 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
449 if (!LVal.Offset.isZero())
450 return false;
451
Richard Smith8b3497e2011-10-31 01:37:14 +0000452 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000453 // If the lvalue has been cast to some other type, don't try to read it.
454 // FIXME: Could simulate a bitcast here.
Richard Smith8b3497e2011-10-31 01:37:14 +0000455 if (!Info.Ctx.hasSameUnqualifiedType(Type, D->getType()))
456 return 0;
Richard Smith11562c52011-10-28 17:51:58 +0000457
Richard Smith11562c52011-10-28 17:51:58 +0000458 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
459 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000460 // expressions are constant expressions too. Inside constexpr functions,
461 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000462 // In C, such things can also be folded, although they are not ICEs.
463 //
Richard Smith254a73d2011-10-28 22:34:42 +0000464 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
465 // interpretation of C++11 suggests that volatile parameters are OK if
466 // they're never read (there's no prohibition against constructing volatile
467 // objects in constant expressions), but lvalue-to-rvalue conversions on
468 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000469 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000470 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith35a1f852011-10-29 21:53:17 +0000471 !Type->isLiteralType() ||
Richard Smith0b0a0b62011-10-29 20:57:55 +0000472 !EvaluateVarDeclInit(Info, VD, LVal.CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000473 return false;
474
Richard Smith0b0a0b62011-10-29 20:57:55 +0000475 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000476 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000477
478 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
479 // conversion. This happens when the declaration and the lvalue should be
480 // considered synonymous, for instance when initializing an array of char
481 // from a string literal. Continue as if the initializer lvalue was the
482 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000483 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000484 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000485 Base = RVal.getLValueBase();
Richard Smith11562c52011-10-28 17:51:58 +0000486 }
487
488 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
489 // here.
490
491 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
492 // initializer until now for such expressions. Such an expression can't be
493 // an ICE in C, so this only matters for fold.
494 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
495 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
496 return Evaluate(RVal, Info, CLE->getInitializer());
497 }
498
499 return false;
500}
501
Mike Stump876387b2009-10-27 22:09:17 +0000502namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000503enum EvalStmtResult {
504 /// Evaluation failed.
505 ESR_Failed,
506 /// Hit a 'return' statement.
507 ESR_Returned,
508 /// Evaluation succeeded.
509 ESR_Succeeded
510};
511}
512
513// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000514static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000515 const Stmt *S) {
516 switch (S->getStmtClass()) {
517 default:
518 return ESR_Failed;
519
520 case Stmt::NullStmtClass:
521 case Stmt::DeclStmtClass:
522 return ESR_Succeeded;
523
524 case Stmt::ReturnStmtClass:
525 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
526 return ESR_Returned;
527 return ESR_Failed;
528
529 case Stmt::CompoundStmtClass: {
530 const CompoundStmt *CS = cast<CompoundStmt>(S);
531 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
532 BE = CS->body_end(); BI != BE; ++BI) {
533 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
534 if (ESR != ESR_Succeeded)
535 return ESR;
536 }
537 return ESR_Succeeded;
538 }
539 }
540}
541
542/// Evaluate a function call.
543static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000544 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000545 // FIXME: Implement a proper call limit, along with a command-line flag.
546 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
547 return false;
548
Richard Smith0b0a0b62011-10-29 20:57:55 +0000549 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000550 // FIXME: Deal with default arguments and 'this'.
551 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
552 I != E; ++I)
553 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
554 return false;
555
556 CallStackFrame Frame(Info, ArgValues.data());
557 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
558}
559
560namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000561class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000562 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000563 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000564public:
565
Richard Smith725810a2011-10-16 21:26:27 +0000566 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000567
568 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000569 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000570 return true;
571 }
572
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
574 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000575 return Visit(E->getResultExpr());
576 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000577 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000578 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000579 return true;
580 return false;
581 }
John McCall31168b02011-06-15 23:02:42 +0000582 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000583 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000584 return true;
585 return false;
586 }
587 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000588 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000589 return true;
590 return false;
591 }
592
Mike Stump876387b2009-10-27 22:09:17 +0000593 // We don't want to evaluate BlockExprs multiple times, as they generate
594 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000595 bool VisitBlockExpr(const BlockExpr *E) { return true; }
596 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
597 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000598 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000599 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
600 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
601 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
602 bool VisitStringLiteral(const StringLiteral *E) { return false; }
603 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
604 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000605 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000607 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000608 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000609 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000610 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
611 bool VisitBinAssign(const BinaryOperator *E) { return true; }
612 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
613 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000614 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000615 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
616 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
617 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
618 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
619 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000620 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000621 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000622 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000623 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000624 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000625
626 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000627 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000628 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
629 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000630 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000631 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000632 return false;
633 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000634
Peter Collingbournee9200682011-05-13 03:29:01 +0000635 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000636};
637
John McCallc07a0c72011-02-17 10:25:35 +0000638class OpaqueValueEvaluation {
639 EvalInfo &info;
640 OpaqueValueExpr *opaqueValue;
641
642public:
643 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
644 Expr *value)
645 : info(info), opaqueValue(opaqueValue) {
646
647 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000648 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000649 this->opaqueValue = 0;
650 return;
651 }
John McCallc07a0c72011-02-17 10:25:35 +0000652 }
653
654 bool hasError() const { return opaqueValue == 0; }
655
656 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000657 // FIXME: This will not work for recursive constexpr functions using opaque
658 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000659 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
660 }
661};
662
Mike Stump876387b2009-10-27 22:09:17 +0000663} // end anonymous namespace
664
Eli Friedman9a156e52008-11-12 09:44:48 +0000665//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000666// Generic Evaluation
667//===----------------------------------------------------------------------===//
668namespace {
669
670template <class Derived, typename RetTy=void>
671class ExprEvaluatorBase
672 : public ConstStmtVisitor<Derived, RetTy> {
673private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000674 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000675 return static_cast<Derived*>(this)->Success(V, E);
676 }
677 RetTy DerivedError(const Expr *E) {
678 return static_cast<Derived*>(this)->Error(E);
679 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000680 RetTy DerivedValueInitialization(const Expr *E) {
681 return static_cast<Derived*>(this)->ValueInitialization(E);
682 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000683
684protected:
685 EvalInfo &Info;
686 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
687 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
688
Richard Smith4ce706a2011-10-11 21:43:33 +0000689 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
690
Peter Collingbournee9200682011-05-13 03:29:01 +0000691public:
692 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
693
694 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000695 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000696 }
697 RetTy VisitExpr(const Expr *E) {
698 return DerivedError(E);
699 }
700
701 RetTy VisitParenExpr(const ParenExpr *E)
702 { return StmtVisitorTy::Visit(E->getSubExpr()); }
703 RetTy VisitUnaryExtension(const UnaryOperator *E)
704 { return StmtVisitorTy::Visit(E->getSubExpr()); }
705 RetTy VisitUnaryPlus(const UnaryOperator *E)
706 { return StmtVisitorTy::Visit(E->getSubExpr()); }
707 RetTy VisitChooseExpr(const ChooseExpr *E)
708 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
709 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
710 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000711 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
712 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000713
714 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
715 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
716 if (opaque.hasError())
717 return DerivedError(E);
718
719 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000720 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000721 return DerivedError(E);
722
723 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
724 }
725
726 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
727 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000728 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000729 return DerivedError(E);
730
Richard Smith11562c52011-10-28 17:51:58 +0000731 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000732 return StmtVisitorTy::Visit(EvalExpr);
733 }
734
735 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000736 const CCValue *Value = Info.getOpaqueValue(E);
737 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000738 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
739 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000740 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000741 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000742
Richard Smith254a73d2011-10-28 22:34:42 +0000743 RetTy VisitCallExpr(const CallExpr *E) {
744 const Expr *Callee = E->getCallee();
745 QualType CalleeType = Callee->getType();
746
747 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
748 // non-static member function.
749 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
750 return DerivedError(E);
751
752 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
753 return DerivedError(E);
754
Richard Smith0b0a0b62011-10-29 20:57:55 +0000755 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000756 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
757 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
758 return DerivedError(Callee);
759
760 const FunctionDecl *FD = 0;
761 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
762 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
763 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
764 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
765 if (!FD)
766 return DerivedError(Callee);
767
768 // Don't call function pointers which have been cast to some other type.
769 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
770 return DerivedError(E);
771
772 const FunctionDecl *Definition;
773 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000774 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000775 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
776
777 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
778 HandleFunctionCall(Args, Body, Info, Result))
779 return DerivedSuccess(Result, E);
780
781 return DerivedError(E);
782 }
783
Richard Smith11562c52011-10-28 17:51:58 +0000784 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
785 return StmtVisitorTy::Visit(E->getInitializer());
786 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000787 RetTy VisitInitListExpr(const InitListExpr *E) {
788 if (Info.getLangOpts().CPlusPlus0x) {
789 if (E->getNumInits() == 0)
790 return DerivedValueInitialization(E);
791 if (E->getNumInits() == 1)
792 return StmtVisitorTy::Visit(E->getInit(0));
793 }
794 return DerivedError(E);
795 }
796 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
797 return DerivedValueInitialization(E);
798 }
799 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
800 return DerivedValueInitialization(E);
801 }
802
Richard Smith11562c52011-10-28 17:51:58 +0000803 RetTy VisitCastExpr(const CastExpr *E) {
804 switch (E->getCastKind()) {
805 default:
806 break;
807
808 case CK_NoOp:
809 return StmtVisitorTy::Visit(E->getSubExpr());
810
811 case CK_LValueToRValue: {
812 LValue LVal;
813 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000814 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000815 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
816 return DerivedSuccess(RVal, E);
817 }
818 break;
819 }
820 }
821
822 return DerivedError(E);
823 }
824
Richard Smith4a678122011-10-24 18:44:57 +0000825 /// Visit a value which is evaluated, but whose value is ignored.
826 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000827 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000828 if (!Evaluate(Scratch, Info, E))
829 Info.EvalStatus.HasSideEffects = true;
830 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000831};
832
833}
834
835//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000836// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000837//
838// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
839// function designators (in C), decl references to void objects (in C), and
840// temporaries (if building with -Wno-address-of-temporary).
841//
842// LValue evaluation produces values comprising a base expression of one of the
843// following types:
844// * DeclRefExpr
845// * MemberExpr for a static member
846// * CompoundLiteralExpr in C
847// * StringLiteral
848// * PredefinedExpr
849// * ObjCEncodeExpr
850// * AddrLabelExpr
851// * BlockExpr
852// * CallExpr for a MakeStringConstant builtin
853// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000854//===----------------------------------------------------------------------===//
855namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000856class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000857 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000858 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000859 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000860
Peter Collingbournee9200682011-05-13 03:29:01 +0000861 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000862 Result.Base = E;
863 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000864 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000865 return true;
866 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000867public:
Mike Stump11289f42009-09-09 15:08:12 +0000868
John McCall45d55e42010-05-07 21:00:08 +0000869 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000870 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000871
Richard Smith0b0a0b62011-10-29 20:57:55 +0000872 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000873 Result.setFrom(V);
874 return true;
875 }
876 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000877 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000878 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000879
Richard Smith11562c52011-10-28 17:51:58 +0000880 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
881
Peter Collingbournee9200682011-05-13 03:29:01 +0000882 bool VisitDeclRefExpr(const DeclRefExpr *E);
883 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
884 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
885 bool VisitMemberExpr(const MemberExpr *E);
886 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
887 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
888 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
889 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000890
Peter Collingbournee9200682011-05-13 03:29:01 +0000891 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000892 switch (E->getCastKind()) {
893 default:
Richard Smith11562c52011-10-28 17:51:58 +0000894 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000895
Eli Friedmance3e02a2011-10-11 00:13:24 +0000896 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000897 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000898
Richard Smith11562c52011-10-28 17:51:58 +0000899 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
900 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000901 }
902 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000903
Eli Friedman449fe542009-03-23 04:56:01 +0000904 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000905
Eli Friedman9a156e52008-11-12 09:44:48 +0000906};
907} // end anonymous namespace
908
Richard Smith11562c52011-10-28 17:51:58 +0000909/// Evaluate an expression as an lvalue. This can be legitimately called on
910/// expressions which are not glvalues, in a few cases:
911/// * function designators in C,
912/// * "extern void" objects,
913/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000914static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000915 assert((E->isGLValue() || E->getType()->isFunctionType() ||
916 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
917 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000918 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000919}
920
Peter Collingbournee9200682011-05-13 03:29:01 +0000921bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000922 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000923 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000924 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
925 return VisitVarDecl(E, VD);
926 return Error(E);
927}
Richard Smith733237d2011-10-24 23:14:33 +0000928
Richard Smith11562c52011-10-28 17:51:58 +0000929bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
930 if (!VD->getType()->isReferenceType())
931 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000932
Richard Smith0b0a0b62011-10-29 20:57:55 +0000933 CCValue V;
934 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
935 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000936
937 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000938}
939
Peter Collingbournee9200682011-05-13 03:29:01 +0000940bool
941LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000942 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
943 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
944 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000945 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000946}
947
Peter Collingbournee9200682011-05-13 03:29:01 +0000948bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000949 // Handle static data members.
950 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
951 VisitIgnoredValue(E->getBase());
952 return VisitVarDecl(E, VD);
953 }
954
Richard Smith254a73d2011-10-28 22:34:42 +0000955 // Handle static member functions.
956 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
957 if (MD->isStatic()) {
958 VisitIgnoredValue(E->getBase());
959 return Success(E);
960 }
961 }
962
Eli Friedman9a156e52008-11-12 09:44:48 +0000963 QualType Ty;
964 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000965 if (!EvaluatePointer(E->getBase(), Result, Info))
966 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000967 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000968 } else {
John McCall45d55e42010-05-07 21:00:08 +0000969 if (!Visit(E->getBase()))
970 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000971 Ty = E->getBase()->getType();
972 }
973
Peter Collingbournee9200682011-05-13 03:29:01 +0000974 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000975 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000976
Peter Collingbournee9200682011-05-13 03:29:01 +0000977 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000978 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000979 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000980
981 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000982 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000983
Eli Friedmana3c122d2011-07-07 01:54:01 +0000984 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000985 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000986 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000987}
988
Peter Collingbournee9200682011-05-13 03:29:01 +0000989bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000990 // FIXME: Deal with vectors as array subscript bases.
991 if (E->getBase()->getType()->isVectorType())
992 return false;
993
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000994 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000995 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000996
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000997 APSInt Index;
998 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000999 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001000
Ken Dyck40775002010-01-11 17:06:35 +00001001 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001002 Result.Offset += Index.getSExtValue() * ElementSize;
1003 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001004}
Eli Friedman9a156e52008-11-12 09:44:48 +00001005
Peter Collingbournee9200682011-05-13 03:29:01 +00001006bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001007 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001008}
1009
Eli Friedman9a156e52008-11-12 09:44:48 +00001010//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001011// Pointer Evaluation
1012//===----------------------------------------------------------------------===//
1013
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001014namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001015class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001016 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001017 LValue &Result;
1018
Peter Collingbournee9200682011-05-13 03:29:01 +00001019 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001020 Result.Base = E;
1021 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001022 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001023 return true;
1024 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001025public:
Mike Stump11289f42009-09-09 15:08:12 +00001026
John McCall45d55e42010-05-07 21:00:08 +00001027 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001028 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001029
Richard Smith0b0a0b62011-10-29 20:57:55 +00001030 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001031 Result.setFrom(V);
1032 return true;
1033 }
1034 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001035 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001036 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001037 bool ValueInitialization(const Expr *E) {
1038 return Success((Expr*)0);
1039 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001040
John McCall45d55e42010-05-07 21:00:08 +00001041 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001042 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001043 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001044 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001045 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001046 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001047 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001048 bool VisitCallExpr(const CallExpr *E);
1049 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001050 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001051 return Success(E);
1052 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001053 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001054 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001055 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001056
Eli Friedman449fe542009-03-23 04:56:01 +00001057 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001058};
Chris Lattner05706e882008-07-11 18:11:29 +00001059} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001060
John McCall45d55e42010-05-07 21:00:08 +00001061static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001062 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001063 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001064}
1065
John McCall45d55e42010-05-07 21:00:08 +00001066bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001067 if (E->getOpcode() != BO_Add &&
1068 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001069 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001070
Chris Lattner05706e882008-07-11 18:11:29 +00001071 const Expr *PExp = E->getLHS();
1072 const Expr *IExp = E->getRHS();
1073 if (IExp->getType()->isPointerType())
1074 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001075
John McCall45d55e42010-05-07 21:00:08 +00001076 if (!EvaluatePointer(PExp, Result, Info))
1077 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001078
John McCall45d55e42010-05-07 21:00:08 +00001079 llvm::APSInt Offset;
1080 if (!EvaluateInteger(IExp, Offset, Info))
1081 return false;
1082 int64_t AdditionalOffset
1083 = Offset.isSigned() ? Offset.getSExtValue()
1084 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001085
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001086 // Compute the new offset in the appropriate width.
1087
1088 QualType PointeeType =
1089 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001090 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlssonef56fba2009-02-19 04:55:58 +00001092 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1093 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001094 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001095 else
John McCall45d55e42010-05-07 21:00:08 +00001096 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001097
John McCalle3027922010-08-25 11:45:40 +00001098 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001099 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001100 else
John McCall45d55e42010-05-07 21:00:08 +00001101 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001102
John McCall45d55e42010-05-07 21:00:08 +00001103 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001104}
Eli Friedman9a156e52008-11-12 09:44:48 +00001105
John McCall45d55e42010-05-07 21:00:08 +00001106bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1107 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001108}
Mike Stump11289f42009-09-09 15:08:12 +00001109
Chris Lattner05706e882008-07-11 18:11:29 +00001110
Peter Collingbournee9200682011-05-13 03:29:01 +00001111bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1112 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001113
Eli Friedman847a2bc2009-12-27 05:43:15 +00001114 switch (E->getCastKind()) {
1115 default:
1116 break;
1117
John McCalle3027922010-08-25 11:45:40 +00001118 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001119 case CK_CPointerToObjCPointerCast:
1120 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001121 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001122 return Visit(SubExpr);
1123
Anders Carlsson18275092010-10-31 20:41:46 +00001124 case CK_DerivedToBase:
1125 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001126 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001127 return false;
1128
1129 // Now figure out the necessary offset to add to the baseLV to get from
1130 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001131 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001132
1133 QualType Ty = E->getSubExpr()->getType();
1134 const CXXRecordDecl *DerivedDecl =
1135 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1136
1137 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1138 PathE = E->path_end(); PathI != PathE; ++PathI) {
1139 const CXXBaseSpecifier *Base = *PathI;
1140
1141 // FIXME: If the base is virtual, we'd need to determine the type of the
1142 // most derived class and we don't support that right now.
1143 if (Base->isVirtual())
1144 return false;
1145
1146 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1147 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1148
Richard Smith0b0a0b62011-10-29 20:57:55 +00001149 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001150 DerivedDecl = BaseDecl;
1151 }
1152
Anders Carlsson18275092010-10-31 20:41:46 +00001153 return true;
1154 }
1155
Richard Smith0b0a0b62011-10-29 20:57:55 +00001156 case CK_NullToPointer:
1157 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001158
John McCalle3027922010-08-25 11:45:40 +00001159 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001160 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001161 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001162 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001163
John McCall45d55e42010-05-07 21:00:08 +00001164 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001165 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1166 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001167 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001168 Result.Offset = CharUnits::fromQuantity(N);
1169 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001170 return true;
1171 } else {
1172 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001173 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001174 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001175 }
1176 }
John McCalle3027922010-08-25 11:45:40 +00001177 case CK_ArrayToPointerDecay:
1178 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001179 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001180 }
1181
Richard Smith11562c52011-10-28 17:51:58 +00001182 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001183}
Chris Lattner05706e882008-07-11 18:11:29 +00001184
Peter Collingbournee9200682011-05-13 03:29:01 +00001185bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001186 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001187 Builtin::BI__builtin___CFStringMakeConstantString ||
1188 E->isBuiltinCall(Info.Ctx) ==
1189 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001190 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001191
Peter Collingbournee9200682011-05-13 03:29:01 +00001192 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001193}
Chris Lattner05706e882008-07-11 18:11:29 +00001194
1195//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001196// Vector Evaluation
1197//===----------------------------------------------------------------------===//
1198
1199namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001200 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001201 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1202 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001203 public:
Mike Stump11289f42009-09-09 15:08:12 +00001204
Richard Smith2d406342011-10-22 21:10:00 +00001205 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1206 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001207
Richard Smith2d406342011-10-22 21:10:00 +00001208 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1209 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1210 // FIXME: remove this APValue copy.
1211 Result = APValue(V.data(), V.size());
1212 return true;
1213 }
1214 bool Success(const APValue &V, const Expr *E) {
1215 Result = V;
1216 return true;
1217 }
1218 bool Error(const Expr *E) { return false; }
1219 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001220
Richard Smith2d406342011-10-22 21:10:00 +00001221 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001222 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001223 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001224 bool VisitInitListExpr(const InitListExpr *E);
1225 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001226 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001227 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001228 // shufflevector, ExtVectorElementExpr
1229 // (Note that these require implementing conversions
1230 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001231 };
1232} // end anonymous namespace
1233
1234static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001235 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001236 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001237}
1238
Richard Smith2d406342011-10-22 21:10:00 +00001239bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1240 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001241 QualType EltTy = VTy->getElementType();
1242 unsigned NElts = VTy->getNumElements();
1243 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001244
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001245 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001246 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001247
Eli Friedmanc757de22011-03-25 00:43:55 +00001248 switch (E->getCastKind()) {
1249 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001250 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001251 if (SETy->isIntegerType()) {
1252 APSInt IntResult;
1253 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001254 return Error(E);
1255 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001256 } else if (SETy->isRealFloatingType()) {
1257 APFloat F(0.0);
1258 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001259 return Error(E);
1260 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001261 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001262 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001263 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001264
1265 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001266 SmallVector<APValue, 4> Elts(NElts, Val);
1267 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001268 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001269 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001270 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001271 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001272 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001273
Eli Friedmanc757de22011-03-25 00:43:55 +00001274 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001275 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001276
Eli Friedmanc757de22011-03-25 00:43:55 +00001277 APSInt Init;
1278 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001279 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001280
Eli Friedmanc757de22011-03-25 00:43:55 +00001281 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1282 "Vectors must be composed of ints or floats");
1283
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001284 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001285 for (unsigned i = 0; i != NElts; ++i) {
1286 APSInt Tmp = Init.extOrTrunc(EltWidth);
1287
1288 if (EltTy->isIntegerType())
1289 Elts.push_back(APValue(Tmp));
1290 else
1291 Elts.push_back(APValue(APFloat(Tmp)));
1292
1293 Init >>= EltWidth;
1294 }
Richard Smith2d406342011-10-22 21:10:00 +00001295 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001296 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001297 default:
Richard Smith11562c52011-10-28 17:51:58 +00001298 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001299 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001300}
1301
Richard Smith2d406342011-10-22 21:10:00 +00001302bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001303VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001304 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001305 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001306 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001307
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001308 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001309 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001310
John McCall875679e2010-06-11 17:54:15 +00001311 // If a vector is initialized with a single element, that value
1312 // becomes every element of the vector, not just the first.
1313 // This is the behavior described in the IBM AltiVec documentation.
1314 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001315
1316 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001317 // vector (OpenCL 6.1.6).
1318 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001319 return Visit(E->getInit(0));
1320
John McCall875679e2010-06-11 17:54:15 +00001321 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001322 if (EltTy->isIntegerType()) {
1323 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001324 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001325 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001326 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001327 } else {
1328 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001329 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001330 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001331 InitValue = APValue(f);
1332 }
1333 for (unsigned i = 0; i < NumElements; i++) {
1334 Elements.push_back(InitValue);
1335 }
1336 } else {
1337 for (unsigned i = 0; i < NumElements; i++) {
1338 if (EltTy->isIntegerType()) {
1339 llvm::APSInt sInt(32);
1340 if (i < NumInits) {
1341 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001342 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001343 } else {
1344 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1345 }
1346 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001347 } else {
John McCall875679e2010-06-11 17:54:15 +00001348 llvm::APFloat f(0.0);
1349 if (i < NumInits) {
1350 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001351 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001352 } else {
1353 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1354 }
1355 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001356 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001357 }
1358 }
Richard Smith2d406342011-10-22 21:10:00 +00001359 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001360}
1361
Richard Smith2d406342011-10-22 21:10:00 +00001362bool
1363VectorExprEvaluator::ValueInitialization(const Expr *E) {
1364 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001365 QualType EltTy = VT->getElementType();
1366 APValue ZeroElement;
1367 if (EltTy->isIntegerType())
1368 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1369 else
1370 ZeroElement =
1371 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1372
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001373 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001374 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001375}
1376
Richard Smith2d406342011-10-22 21:10:00 +00001377bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001378 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001379 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001380}
1381
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001382//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001383// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001384//
1385// As a GNU extension, we support casting pointers to sufficiently-wide integer
1386// types and back in constant folding. Integer values are thus represented
1387// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001388//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001389
1390namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001391class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001392 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001393 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001394public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001395 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001396 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001397
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001398 bool Success(const llvm::APSInt &SI, const Expr *E) {
1399 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001400 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001401 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001402 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001403 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001404 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001405 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001406 return true;
1407 }
1408
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001409 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001410 assert(E->getType()->isIntegralOrEnumerationType() &&
1411 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001412 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001413 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001414 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001415 Result.getInt().setIsUnsigned(
1416 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001417 return true;
1418 }
1419
1420 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001421 assert(E->getType()->isIntegralOrEnumerationType() &&
1422 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001423 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001424 return true;
1425 }
1426
Ken Dyckdbc01912011-03-11 02:13:43 +00001427 bool Success(CharUnits Size, const Expr *E) {
1428 return Success(Size.getQuantity(), E);
1429 }
1430
1431
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001432 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001433 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001434 if (Info.EvalStatus.Diag == 0) {
1435 Info.EvalStatus.DiagLoc = L;
1436 Info.EvalStatus.Diag = D;
1437 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001438 }
Chris Lattner99415702008-07-12 00:14:42 +00001439 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Richard Smith0b0a0b62011-10-29 20:57:55 +00001442 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001443 if (V.isLValue()) {
1444 Result = V;
1445 return true;
1446 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001447 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001448 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001449 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001450 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001451 }
Mike Stump11289f42009-09-09 15:08:12 +00001452
Richard Smith4ce706a2011-10-11 21:43:33 +00001453 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1454
Peter Collingbournee9200682011-05-13 03:29:01 +00001455 //===--------------------------------------------------------------------===//
1456 // Visitor Methods
1457 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001458
Chris Lattner7174bf32008-07-12 00:38:25 +00001459 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001460 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001461 }
1462 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001463 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001464 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001465
1466 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1467 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001468 if (CheckReferencedDecl(E, E->getDecl()))
1469 return true;
1470
1471 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001472 }
1473 bool VisitMemberExpr(const MemberExpr *E) {
1474 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001475 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001476 return true;
1477 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001478
1479 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001480 }
1481
Peter Collingbournee9200682011-05-13 03:29:01 +00001482 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001483 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001484 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001485 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001486
Peter Collingbournee9200682011-05-13 03:29:01 +00001487 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001488 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001489
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001490 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001491 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001492 }
Mike Stump11289f42009-09-09 15:08:12 +00001493
Richard Smith4ce706a2011-10-11 21:43:33 +00001494 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001495 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001496 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001497 }
1498
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001499 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001500 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001501 }
1502
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001503 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1504 return Success(E->getValue(), E);
1505 }
1506
John Wiegley6242b6a2011-04-28 00:16:57 +00001507 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1508 return Success(E->getValue(), E);
1509 }
1510
John Wiegleyf9f65842011-04-25 06:54:41 +00001511 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1512 return Success(E->getValue(), E);
1513 }
1514
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001515 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001516 bool VisitUnaryImag(const UnaryOperator *E);
1517
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001518 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001519 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001520
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001521private:
Ken Dyck160146e2010-01-27 17:10:57 +00001522 CharUnits GetAlignOfExpr(const Expr *E);
1523 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001524 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001525 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001526 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001527};
Chris Lattner05706e882008-07-11 18:11:29 +00001528} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001529
Richard Smith11562c52011-10-28 17:51:58 +00001530/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1531/// produce either the integer value or a pointer.
1532///
1533/// GCC has a heinous extension which folds casts between pointer types and
1534/// pointer-sized integral types. We support this by allowing the evaluation of
1535/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1536/// Some simple arithmetic on such values is supported (they are treated much
1537/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001538static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1539 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001540 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001541 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001542}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001543
Daniel Dunbarce399542009-02-20 18:22:23 +00001544static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001545 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001546 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1547 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001548 Result = Val.getInt();
1549 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001550}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001551
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001552bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001553 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001554 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001555 // Check for signedness/width mismatches between E type and ECD value.
1556 bool SameSign = (ECD->getInitVal().isSigned()
1557 == E->getType()->isSignedIntegerOrEnumerationType());
1558 bool SameWidth = (ECD->getInitVal().getBitWidth()
1559 == Info.Ctx.getIntWidth(E->getType()));
1560 if (SameSign && SameWidth)
1561 return Success(ECD->getInitVal(), E);
1562 else {
1563 // Get rid of mismatch (otherwise Success assertions will fail)
1564 // by computing a new value matching the type of E.
1565 llvm::APSInt Val = ECD->getInitVal();
1566 if (!SameSign)
1567 Val.setIsSigned(!ECD->getInitVal().isSigned());
1568 if (!SameWidth)
1569 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1570 return Success(Val, E);
1571 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001572 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001573 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001574}
1575
Chris Lattner86ee2862008-10-06 06:40:35 +00001576/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1577/// as GCC.
1578static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1579 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001580 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001581 enum gcc_type_class {
1582 no_type_class = -1,
1583 void_type_class, integer_type_class, char_type_class,
1584 enumeral_type_class, boolean_type_class,
1585 pointer_type_class, reference_type_class, offset_type_class,
1586 real_type_class, complex_type_class,
1587 function_type_class, method_type_class,
1588 record_type_class, union_type_class,
1589 array_type_class, string_type_class,
1590 lang_type_class
1591 };
Mike Stump11289f42009-09-09 15:08:12 +00001592
1593 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001594 // ideal, however it is what gcc does.
1595 if (E->getNumArgs() == 0)
1596 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001597
Chris Lattner86ee2862008-10-06 06:40:35 +00001598 QualType ArgTy = E->getArg(0)->getType();
1599 if (ArgTy->isVoidType())
1600 return void_type_class;
1601 else if (ArgTy->isEnumeralType())
1602 return enumeral_type_class;
1603 else if (ArgTy->isBooleanType())
1604 return boolean_type_class;
1605 else if (ArgTy->isCharType())
1606 return string_type_class; // gcc doesn't appear to use char_type_class
1607 else if (ArgTy->isIntegerType())
1608 return integer_type_class;
1609 else if (ArgTy->isPointerType())
1610 return pointer_type_class;
1611 else if (ArgTy->isReferenceType())
1612 return reference_type_class;
1613 else if (ArgTy->isRealType())
1614 return real_type_class;
1615 else if (ArgTy->isComplexType())
1616 return complex_type_class;
1617 else if (ArgTy->isFunctionType())
1618 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001619 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001620 return record_type_class;
1621 else if (ArgTy->isUnionType())
1622 return union_type_class;
1623 else if (ArgTy->isArrayType())
1624 return array_type_class;
1625 else if (ArgTy->isUnionType())
1626 return union_type_class;
1627 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001628 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001629 return -1;
1630}
1631
John McCall95007602010-05-10 23:27:23 +00001632/// Retrieves the "underlying object type" of the given expression,
1633/// as used by __builtin_object_size.
1634QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1635 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1636 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1637 return VD->getType();
1638 } else if (isa<CompoundLiteralExpr>(E)) {
1639 return E->getType();
1640 }
1641
1642 return QualType();
1643}
1644
Peter Collingbournee9200682011-05-13 03:29:01 +00001645bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001646 // TODO: Perhaps we should let LLVM lower this?
1647 LValue Base;
1648 if (!EvaluatePointer(E->getArg(0), Base, Info))
1649 return false;
1650
1651 // If we can prove the base is null, lower to zero now.
1652 const Expr *LVBase = Base.getLValueBase();
1653 if (!LVBase) return Success(0, E);
1654
1655 QualType T = GetObjectType(LVBase);
1656 if (T.isNull() ||
1657 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001658 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001659 T->isVariablyModifiedType() ||
1660 T->isDependentType())
1661 return false;
1662
1663 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1664 CharUnits Offset = Base.getLValueOffset();
1665
1666 if (!Offset.isNegative() && Offset <= Size)
1667 Size -= Offset;
1668 else
1669 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001670 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001671}
1672
Peter Collingbournee9200682011-05-13 03:29:01 +00001673bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001674 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001675 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001676 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001677
1678 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001679 if (TryEvaluateBuiltinObjectSize(E))
1680 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001681
Eric Christopher99469702010-01-19 22:58:35 +00001682 // If evaluating the argument has side-effects we can't determine
1683 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001684 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001685 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001686 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001687 return Success(0, E);
1688 }
Mike Stump876387b2009-10-27 22:09:17 +00001689
Mike Stump722cedf2009-10-26 18:35:08 +00001690 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1691 }
1692
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001693 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001694 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001695
Anders Carlsson4c76e932008-11-24 04:21:33 +00001696 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001697 // __builtin_constant_p always has one operand: it returns true if that
1698 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001699 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001700
1701 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001702 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001703 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001704 return Success(Operand, E);
1705 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001706
1707 case Builtin::BI__builtin_expect:
1708 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001709
1710 case Builtin::BIstrlen:
1711 case Builtin::BI__builtin_strlen:
1712 // As an extension, we support strlen() and __builtin_strlen() as constant
1713 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001714 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001715 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1716 // The string literal may have embedded null characters. Find the first
1717 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001718 StringRef Str = S->getString();
1719 StringRef::size_type Pos = Str.find(0);
1720 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001721 Str = Str.substr(0, Pos);
1722
1723 return Success(Str.size(), E);
1724 }
1725
1726 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001727
1728 case Builtin::BI__atomic_is_lock_free: {
1729 APSInt SizeVal;
1730 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1731 return false;
1732
1733 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1734 // of two less than the maximum inline atomic width, we know it is
1735 // lock-free. If the size isn't a power of two, or greater than the
1736 // maximum alignment where we promote atomics, we know it is not lock-free
1737 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1738 // the answer can only be determined at runtime; for example, 16-byte
1739 // atomics have lock-free implementations on some, but not all,
1740 // x86-64 processors.
1741
1742 // Check power-of-two.
1743 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1744 if (!Size.isPowerOfTwo())
1745#if 0
1746 // FIXME: Suppress this folding until the ABI for the promotion width
1747 // settles.
1748 return Success(0, E);
1749#else
1750 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1751#endif
1752
1753#if 0
1754 // Check against promotion width.
1755 // FIXME: Suppress this folding until the ABI for the promotion width
1756 // settles.
1757 unsigned PromoteWidthBits =
1758 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1759 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1760 return Success(0, E);
1761#endif
1762
1763 // Check against inlining width.
1764 unsigned InlineWidthBits =
1765 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1766 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1767 return Success(1, E);
1768
1769 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1770 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001771 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001772}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001773
Richard Smith8b3497e2011-10-31 01:37:14 +00001774static bool HasSameBase(const LValue &A, const LValue &B) {
1775 if (!A.getLValueBase())
1776 return !B.getLValueBase();
1777 if (!B.getLValueBase())
1778 return false;
1779
1780 if (A.getLValueBase() != B.getLValueBase()) {
1781 const Decl *ADecl = GetLValueBaseDecl(A);
1782 if (!ADecl)
1783 return false;
1784 const Decl *BDecl = GetLValueBaseDecl(B);
1785 if (ADecl != BDecl)
1786 return false;
1787 }
1788
1789 return IsGlobalLValue(A.getLValueBase()) ||
1790 A.getLValueCallIndex() == B.getLValueCallIndex();
1791}
1792
Chris Lattnere13042c2008-07-11 19:10:17 +00001793bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001794 if (E->isAssignmentOp())
1795 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1796
John McCalle3027922010-08-25 11:45:40 +00001797 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001798 VisitIgnoredValue(E->getLHS());
1799 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001800 }
1801
1802 if (E->isLogicalOp()) {
1803 // These need to be handled specially because the operands aren't
1804 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001805 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001806
Richard Smith11562c52011-10-28 17:51:58 +00001807 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001808 // We were able to evaluate the LHS, see if we can get away with not
1809 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001810 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001811 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001812
Richard Smith11562c52011-10-28 17:51:58 +00001813 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001814 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001815 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001816 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001817 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001818 }
1819 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001820 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001821 // We can't evaluate the LHS; however, sometimes the result
1822 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001823 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1824 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001825 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001826 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001827 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001828
1829 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001830 }
1831 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001832 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001833
Eli Friedman5a332ea2008-11-13 06:09:17 +00001834 return false;
1835 }
1836
Anders Carlssonacc79812008-11-16 07:17:21 +00001837 QualType LHSTy = E->getLHS()->getType();
1838 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001839
1840 if (LHSTy->isAnyComplexType()) {
1841 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001842 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001843
1844 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1845 return false;
1846
1847 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1848 return false;
1849
1850 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001851 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001852 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001853 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001854 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1855
John McCalle3027922010-08-25 11:45:40 +00001856 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001857 return Success((CR_r == APFloat::cmpEqual &&
1858 CR_i == APFloat::cmpEqual), E);
1859 else {
John McCalle3027922010-08-25 11:45:40 +00001860 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001861 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001862 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001863 CR_r == APFloat::cmpLessThan ||
1864 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001865 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001866 CR_i == APFloat::cmpLessThan ||
1867 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001868 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001869 } else {
John McCalle3027922010-08-25 11:45:40 +00001870 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001871 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1872 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1873 else {
John McCalle3027922010-08-25 11:45:40 +00001874 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001875 "Invalid compex comparison.");
1876 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1877 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1878 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001879 }
1880 }
Mike Stump11289f42009-09-09 15:08:12 +00001881
Anders Carlssonacc79812008-11-16 07:17:21 +00001882 if (LHSTy->isRealFloatingType() &&
1883 RHSTy->isRealFloatingType()) {
1884 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001885
Anders Carlssonacc79812008-11-16 07:17:21 +00001886 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1887 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001888
Anders Carlssonacc79812008-11-16 07:17:21 +00001889 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1890 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001891
Anders Carlssonacc79812008-11-16 07:17:21 +00001892 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001893
Anders Carlssonacc79812008-11-16 07:17:21 +00001894 switch (E->getOpcode()) {
1895 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001896 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001897 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001898 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001899 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001900 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001901 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001902 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001903 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001904 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001905 E);
John McCalle3027922010-08-25 11:45:40 +00001906 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001907 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001908 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001909 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001910 || CR == APFloat::cmpLessThan
1911 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001912 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Eli Friedmana38da572009-04-28 19:17:36 +00001915 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00001916 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001917 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001918 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1919 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001920
John McCall45d55e42010-05-07 21:00:08 +00001921 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001922 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1923 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001924
Richard Smith8b3497e2011-10-31 01:37:14 +00001925 // Reject differing bases from the normal codepath; we special-case
1926 // comparisons to null.
1927 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman334046a2009-06-14 02:17:33 +00001928 if (!E->isEqualityOp())
1929 return false;
Richard Smith8b3497e2011-10-31 01:37:14 +00001930 if ((LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())&&
1931 (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero()))
Eli Friedman334046a2009-06-14 02:17:33 +00001932 return false;
Richard Smith8b3497e2011-10-31 01:37:14 +00001933 LValue &NonNull = LHSValue.getLValueBase() ? LHSValue : RHSValue;
Eli Friedman334046a2009-06-14 02:17:33 +00001934 bool bres;
Richard Smith8b3497e2011-10-31 01:37:14 +00001935 if (!EvalPointerValueAsBool(NonNull, bres))
Eli Friedman334046a2009-06-14 02:17:33 +00001936 return false;
John McCalle3027922010-08-25 11:45:40 +00001937 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001938 }
Eli Friedman64004332009-03-23 04:38:34 +00001939
John McCalle3027922010-08-25 11:45:40 +00001940 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001941 QualType Type = E->getLHS()->getType();
1942 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001943
Ken Dyck02990832010-01-15 12:37:54 +00001944 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001945 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001946 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001947
Ken Dyck02990832010-01-15 12:37:54 +00001948 CharUnits Diff = LHSValue.getLValueOffset() -
1949 RHSValue.getLValueOffset();
1950 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001951 }
Richard Smith8b3497e2011-10-31 01:37:14 +00001952
1953 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
1954 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
1955 switch (E->getOpcode()) {
1956 default: llvm_unreachable("missing comparison operator");
1957 case BO_LT: return Success(LHSOffset < RHSOffset, E);
1958 case BO_GT: return Success(LHSOffset > RHSOffset, E);
1959 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
1960 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
1961 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
1962 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001963 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001964 }
1965 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001966 if (!LHSTy->isIntegralOrEnumerationType() ||
1967 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001968 // We can't continue from here for non-integral types, and they
1969 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001970 return false;
1971 }
1972
Anders Carlsson9c181652008-07-08 14:35:21 +00001973 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001974 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00001975 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001976 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001977
Richard Smith11562c52011-10-28 17:51:58 +00001978 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001979 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001980 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001981
1982 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001983 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001984 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1985 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001986 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00001987 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001988 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00001989 LHSVal.getLValueOffset() -= AdditionalOffset;
1990 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00001991 return true;
1992 }
1993
1994 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001995 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001996 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001997 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
1998 LHSVal.getInt().getZExtValue());
1999 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002000 return true;
2001 }
2002
2003 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002004 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002005 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002006
Richard Smith11562c52011-10-28 17:51:58 +00002007 APSInt &LHS = LHSVal.getInt();
2008 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002009
Anders Carlsson9c181652008-07-08 14:35:21 +00002010 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002011 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002012 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002013 case BO_Mul: return Success(LHS * RHS, E);
2014 case BO_Add: return Success(LHS + RHS, E);
2015 case BO_Sub: return Success(LHS - RHS, E);
2016 case BO_And: return Success(LHS & RHS, E);
2017 case BO_Xor: return Success(LHS ^ RHS, E);
2018 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002019 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002020 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002021 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002022 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002023 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002024 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002025 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002026 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002027 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002028 // During constant-folding, a negative shift is an opposite shift.
2029 if (RHS.isSigned() && RHS.isNegative()) {
2030 RHS = -RHS;
2031 goto shift_right;
2032 }
2033
2034 shift_left:
2035 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002036 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2037 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002038 }
John McCalle3027922010-08-25 11:45:40 +00002039 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002040 // During constant-folding, a negative shift is an opposite shift.
2041 if (RHS.isSigned() && RHS.isNegative()) {
2042 RHS = -RHS;
2043 goto shift_left;
2044 }
2045
2046 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002047 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002048 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2049 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
Richard Smith11562c52011-10-28 17:51:58 +00002052 case BO_LT: return Success(LHS < RHS, E);
2053 case BO_GT: return Success(LHS > RHS, E);
2054 case BO_LE: return Success(LHS <= RHS, E);
2055 case BO_GE: return Success(LHS >= RHS, E);
2056 case BO_EQ: return Success(LHS == RHS, E);
2057 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002058 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002059}
2060
Ken Dyck160146e2010-01-27 17:10:57 +00002061CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002062 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2063 // the result is the size of the referenced type."
2064 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2065 // result shall be the alignment of the referenced type."
2066 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2067 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002068
2069 // __alignof is defined to return the preferred alignment.
2070 return Info.Ctx.toCharUnitsFromBits(
2071 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002072}
2073
Ken Dyck160146e2010-01-27 17:10:57 +00002074CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002075 E = E->IgnoreParens();
2076
2077 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002078 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002079 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002080 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2081 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002082
Chris Lattner68061312009-01-24 21:53:27 +00002083 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002084 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2085 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002086
Chris Lattner24aeeab2009-01-24 21:09:06 +00002087 return GetAlignOfType(E->getType());
2088}
2089
2090
Peter Collingbournee190dee2011-03-11 19:24:49 +00002091/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2092/// a result as the expression's type.
2093bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2094 const UnaryExprOrTypeTraitExpr *E) {
2095 switch(E->getKind()) {
2096 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002097 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002098 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002099 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002100 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002101 }
Eli Friedman64004332009-03-23 04:38:34 +00002102
Peter Collingbournee190dee2011-03-11 19:24:49 +00002103 case UETT_VecStep: {
2104 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002105
Peter Collingbournee190dee2011-03-11 19:24:49 +00002106 if (Ty->isVectorType()) {
2107 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002108
Peter Collingbournee190dee2011-03-11 19:24:49 +00002109 // The vec_step built-in functions that take a 3-component
2110 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2111 if (n == 3)
2112 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002113
Peter Collingbournee190dee2011-03-11 19:24:49 +00002114 return Success(n, E);
2115 } else
2116 return Success(1, E);
2117 }
2118
2119 case UETT_SizeOf: {
2120 QualType SrcTy = E->getTypeOfArgument();
2121 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2122 // the result is the size of the referenced type."
2123 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2124 // result shall be the alignment of the referenced type."
2125 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2126 SrcTy = Ref->getPointeeType();
2127
2128 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2129 // extension.
2130 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2131 return Success(1, E);
2132
2133 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2134 if (!SrcTy->isConstantSizeType())
2135 return false;
2136
2137 // Get information about the size.
2138 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2139 }
2140 }
2141
2142 llvm_unreachable("unknown expr/type trait");
2143 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002144}
2145
Peter Collingbournee9200682011-05-13 03:29:01 +00002146bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002147 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002148 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002149 if (n == 0)
2150 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002151 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002152 for (unsigned i = 0; i != n; ++i) {
2153 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2154 switch (ON.getKind()) {
2155 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002156 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002157 APSInt IdxResult;
2158 if (!EvaluateInteger(Idx, IdxResult, Info))
2159 return false;
2160 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2161 if (!AT)
2162 return false;
2163 CurrentType = AT->getElementType();
2164 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2165 Result += IdxResult.getSExtValue() * ElementSize;
2166 break;
2167 }
2168
2169 case OffsetOfExpr::OffsetOfNode::Field: {
2170 FieldDecl *MemberDecl = ON.getField();
2171 const RecordType *RT = CurrentType->getAs<RecordType>();
2172 if (!RT)
2173 return false;
2174 RecordDecl *RD = RT->getDecl();
2175 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002176 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002177 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002178 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002179 CurrentType = MemberDecl->getType().getNonReferenceType();
2180 break;
2181 }
2182
2183 case OffsetOfExpr::OffsetOfNode::Identifier:
2184 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002185 return false;
2186
2187 case OffsetOfExpr::OffsetOfNode::Base: {
2188 CXXBaseSpecifier *BaseSpec = ON.getBase();
2189 if (BaseSpec->isVirtual())
2190 return false;
2191
2192 // Find the layout of the class whose base we are looking into.
2193 const RecordType *RT = CurrentType->getAs<RecordType>();
2194 if (!RT)
2195 return false;
2196 RecordDecl *RD = RT->getDecl();
2197 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2198
2199 // Find the base class itself.
2200 CurrentType = BaseSpec->getType();
2201 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2202 if (!BaseRT)
2203 return false;
2204
2205 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002206 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002207 break;
2208 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002209 }
2210 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002211 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002212}
2213
Chris Lattnere13042c2008-07-11 19:10:17 +00002214bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002215 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002216 // LNot's operand isn't necessarily an integer, so we handle it specially.
2217 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002218 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002219 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002220 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002221 }
2222
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002223 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002224 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002225 return false;
2226
Richard Smith11562c52011-10-28 17:51:58 +00002227 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002228 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002229 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002230 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002231
Chris Lattnerf09ad162008-07-11 22:15:16 +00002232 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002233 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002234 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2235 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002236 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002237 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002238 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2239 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002240 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002241 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002242 // The result is just the value.
2243 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002244 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002245 if (!Val.isInt()) return false;
2246 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002247 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002248 if (!Val.isInt()) return false;
2249 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002250 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002251}
Mike Stump11289f42009-09-09 15:08:12 +00002252
Chris Lattner477c4be2008-07-12 01:15:53 +00002253/// HandleCast - This is used to evaluate implicit or explicit casts where the
2254/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002255bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2256 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002257 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002258 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002259
Eli Friedmanc757de22011-03-25 00:43:55 +00002260 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002261 case CK_BaseToDerived:
2262 case CK_DerivedToBase:
2263 case CK_UncheckedDerivedToBase:
2264 case CK_Dynamic:
2265 case CK_ToUnion:
2266 case CK_ArrayToPointerDecay:
2267 case CK_FunctionToPointerDecay:
2268 case CK_NullToPointer:
2269 case CK_NullToMemberPointer:
2270 case CK_BaseToDerivedMemberPointer:
2271 case CK_DerivedToBaseMemberPointer:
2272 case CK_ConstructorConversion:
2273 case CK_IntegralToPointer:
2274 case CK_ToVoid:
2275 case CK_VectorSplat:
2276 case CK_IntegralToFloating:
2277 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002278 case CK_CPointerToObjCPointerCast:
2279 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002280 case CK_AnyPointerToBlockPointerCast:
2281 case CK_ObjCObjectLValueCast:
2282 case CK_FloatingRealToComplex:
2283 case CK_FloatingComplexToReal:
2284 case CK_FloatingComplexCast:
2285 case CK_FloatingComplexToIntegralComplex:
2286 case CK_IntegralRealToComplex:
2287 case CK_IntegralComplexCast:
2288 case CK_IntegralComplexToFloatingComplex:
2289 llvm_unreachable("invalid cast kind for integral value");
2290
Eli Friedman9faf2f92011-03-25 19:07:11 +00002291 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002292 case CK_Dependent:
2293 case CK_GetObjCProperty:
2294 case CK_LValueBitCast:
2295 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002296 case CK_ARCProduceObject:
2297 case CK_ARCConsumeObject:
2298 case CK_ARCReclaimReturnedObject:
2299 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002300 return false;
2301
2302 case CK_LValueToRValue:
2303 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002304 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002305
2306 case CK_MemberPointerToBoolean:
2307 case CK_PointerToBoolean:
2308 case CK_IntegralToBoolean:
2309 case CK_FloatingToBoolean:
2310 case CK_FloatingComplexToBoolean:
2311 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002312 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002313 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002314 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002315 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002316 }
2317
Eli Friedmanc757de22011-03-25 00:43:55 +00002318 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002319 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002320 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002321
Eli Friedman742421e2009-02-20 01:15:07 +00002322 if (!Result.isInt()) {
2323 // Only allow casts of lvalues if they are lossless.
2324 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2325 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002326
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002327 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002328 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002329 }
Mike Stump11289f42009-09-09 15:08:12 +00002330
Eli Friedmanc757de22011-03-25 00:43:55 +00002331 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002332 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002333 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002334 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002335
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002336 if (LV.getLValueBase()) {
2337 // Only allow based lvalue casts if they are lossless.
2338 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2339 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002340
John McCall45d55e42010-05-07 21:00:08 +00002341 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002342 return true;
2343 }
2344
Ken Dyck02990832010-01-15 12:37:54 +00002345 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2346 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002347 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002348 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002349
Eli Friedmanc757de22011-03-25 00:43:55 +00002350 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002351 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002352 if (!EvaluateComplex(SubExpr, C, Info))
2353 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002354 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002355 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002356
Eli Friedmanc757de22011-03-25 00:43:55 +00002357 case CK_FloatingToIntegral: {
2358 APFloat F(0.0);
2359 if (!EvaluateFloat(SubExpr, F, Info))
2360 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002361
Eli Friedmanc757de22011-03-25 00:43:55 +00002362 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2363 }
2364 }
Mike Stump11289f42009-09-09 15:08:12 +00002365
Eli Friedmanc757de22011-03-25 00:43:55 +00002366 llvm_unreachable("unknown cast resulting in integral value");
2367 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002368}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002369
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002370bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2371 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002372 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002373 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2374 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2375 return Success(LV.getComplexIntReal(), E);
2376 }
2377
2378 return Visit(E->getSubExpr());
2379}
2380
Eli Friedman4e7a2412009-02-27 04:45:43 +00002381bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002382 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002383 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002384 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2385 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2386 return Success(LV.getComplexIntImag(), E);
2387 }
2388
Richard Smith4a678122011-10-24 18:44:57 +00002389 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002390 return Success(0, E);
2391}
2392
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002393bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2394 return Success(E->getPackLength(), E);
2395}
2396
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002397bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2398 return Success(E->getValue(), E);
2399}
2400
Chris Lattner05706e882008-07-11 18:11:29 +00002401//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002402// Float Evaluation
2403//===----------------------------------------------------------------------===//
2404
2405namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002406class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002407 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002408 APFloat &Result;
2409public:
2410 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002411 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002412
Richard Smith0b0a0b62011-10-29 20:57:55 +00002413 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002414 Result = V.getFloat();
2415 return true;
2416 }
2417 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002418 return false;
2419 }
2420
Richard Smith4ce706a2011-10-11 21:43:33 +00002421 bool ValueInitialization(const Expr *E) {
2422 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2423 return true;
2424 }
2425
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002426 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002427
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002428 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002429 bool VisitBinaryOperator(const BinaryOperator *E);
2430 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002431 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002432
John McCallb1fb0d32010-05-07 22:08:54 +00002433 bool VisitUnaryReal(const UnaryOperator *E);
2434 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002435
John McCallb1fb0d32010-05-07 22:08:54 +00002436 // FIXME: Missing: array subscript of vector, member of vector,
2437 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002438};
2439} // end anonymous namespace
2440
2441static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002442 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002443 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002444}
2445
Jay Foad39c79802011-01-12 09:06:06 +00002446static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002447 QualType ResultTy,
2448 const Expr *Arg,
2449 bool SNaN,
2450 llvm::APFloat &Result) {
2451 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2452 if (!S) return false;
2453
2454 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2455
2456 llvm::APInt fill;
2457
2458 // Treat empty strings as if they were zero.
2459 if (S->getString().empty())
2460 fill = llvm::APInt(32, 0);
2461 else if (S->getString().getAsInteger(0, fill))
2462 return false;
2463
2464 if (SNaN)
2465 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2466 else
2467 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2468 return true;
2469}
2470
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002471bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002472 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002473 default:
2474 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2475
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002476 case Builtin::BI__builtin_huge_val:
2477 case Builtin::BI__builtin_huge_valf:
2478 case Builtin::BI__builtin_huge_vall:
2479 case Builtin::BI__builtin_inf:
2480 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002481 case Builtin::BI__builtin_infl: {
2482 const llvm::fltSemantics &Sem =
2483 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002484 Result = llvm::APFloat::getInf(Sem);
2485 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
John McCall16291492010-02-28 13:00:19 +00002488 case Builtin::BI__builtin_nans:
2489 case Builtin::BI__builtin_nansf:
2490 case Builtin::BI__builtin_nansl:
2491 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2492 true, Result);
2493
Chris Lattner0b7282e2008-10-06 06:31:58 +00002494 case Builtin::BI__builtin_nan:
2495 case Builtin::BI__builtin_nanf:
2496 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002497 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002498 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002499 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2500 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002501
2502 case Builtin::BI__builtin_fabs:
2503 case Builtin::BI__builtin_fabsf:
2504 case Builtin::BI__builtin_fabsl:
2505 if (!EvaluateFloat(E->getArg(0), Result, Info))
2506 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002507
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002508 if (Result.isNegative())
2509 Result.changeSign();
2510 return true;
2511
Mike Stump11289f42009-09-09 15:08:12 +00002512 case Builtin::BI__builtin_copysign:
2513 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002514 case Builtin::BI__builtin_copysignl: {
2515 APFloat RHS(0.);
2516 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2517 !EvaluateFloat(E->getArg(1), RHS, Info))
2518 return false;
2519 Result.copySign(RHS);
2520 return true;
2521 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002522 }
2523}
2524
John McCallb1fb0d32010-05-07 22:08:54 +00002525bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002526 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2527 ComplexValue CV;
2528 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2529 return false;
2530 Result = CV.FloatReal;
2531 return true;
2532 }
2533
2534 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002535}
2536
2537bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002538 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2539 ComplexValue CV;
2540 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2541 return false;
2542 Result = CV.FloatImag;
2543 return true;
2544 }
2545
Richard Smith4a678122011-10-24 18:44:57 +00002546 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002547 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2548 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002549 return true;
2550}
2551
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002552bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002553 switch (E->getOpcode()) {
2554 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002555 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002556 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002557 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002558 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2559 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002560 Result.changeSign();
2561 return true;
2562 }
2563}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002564
Eli Friedman24c01542008-08-22 00:06:13 +00002565bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002566 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002567 VisitIgnoredValue(E->getLHS());
2568 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002569 }
2570
Richard Smith472d4952011-10-28 23:26:52 +00002571 // We can't evaluate pointer-to-member operations or assignments.
2572 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002573 return false;
2574
Eli Friedman24c01542008-08-22 00:06:13 +00002575 // FIXME: Diagnostics? I really don't understand how the warnings
2576 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002577 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002578 if (!EvaluateFloat(E->getLHS(), Result, Info))
2579 return false;
2580 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2581 return false;
2582
2583 switch (E->getOpcode()) {
2584 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002585 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002586 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2587 return true;
John McCalle3027922010-08-25 11:45:40 +00002588 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002589 Result.add(RHS, APFloat::rmNearestTiesToEven);
2590 return true;
John McCalle3027922010-08-25 11:45:40 +00002591 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002592 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2593 return true;
John McCalle3027922010-08-25 11:45:40 +00002594 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002595 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2596 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002597 }
2598}
2599
2600bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2601 Result = E->getValue();
2602 return true;
2603}
2604
Peter Collingbournee9200682011-05-13 03:29:01 +00002605bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2606 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002607
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002608 switch (E->getCastKind()) {
2609 default:
Richard Smith11562c52011-10-28 17:51:58 +00002610 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002611
2612 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002613 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002614 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002615 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002616 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002617 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002618 return true;
2619 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002620
2621 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002622 if (!Visit(SubExpr))
2623 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002624 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2625 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002626 return true;
2627 }
John McCalld7646252010-11-14 08:17:51 +00002628
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002629 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002630 ComplexValue V;
2631 if (!EvaluateComplex(SubExpr, V, Info))
2632 return false;
2633 Result = V.getComplexFloatReal();
2634 return true;
2635 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002636 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002637
2638 return false;
2639}
2640
Eli Friedman24c01542008-08-22 00:06:13 +00002641//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002642// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002643//===----------------------------------------------------------------------===//
2644
2645namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002646class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002647 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002648 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002649
Anders Carlsson537969c2008-11-16 20:27:53 +00002650public:
John McCall93d91dc2010-05-07 17:22:02 +00002651 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002652 : ExprEvaluatorBaseTy(info), Result(Result) {}
2653
Richard Smith0b0a0b62011-10-29 20:57:55 +00002654 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002655 Result.setFrom(V);
2656 return true;
2657 }
2658 bool Error(const Expr *E) {
2659 return false;
2660 }
Mike Stump11289f42009-09-09 15:08:12 +00002661
Anders Carlsson537969c2008-11-16 20:27:53 +00002662 //===--------------------------------------------------------------------===//
2663 // Visitor Methods
2664 //===--------------------------------------------------------------------===//
2665
Peter Collingbournee9200682011-05-13 03:29:01 +00002666 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002667
Peter Collingbournee9200682011-05-13 03:29:01 +00002668 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002669
John McCall93d91dc2010-05-07 17:22:02 +00002670 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002671 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002672 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002673};
2674} // end anonymous namespace
2675
John McCall93d91dc2010-05-07 17:22:02 +00002676static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2677 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002678 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002679 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002680}
2681
Peter Collingbournee9200682011-05-13 03:29:01 +00002682bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2683 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002684
2685 if (SubExpr->getType()->isRealFloatingType()) {
2686 Result.makeComplexFloat();
2687 APFloat &Imag = Result.FloatImag;
2688 if (!EvaluateFloat(SubExpr, Imag, Info))
2689 return false;
2690
2691 Result.FloatReal = APFloat(Imag.getSemantics());
2692 return true;
2693 } else {
2694 assert(SubExpr->getType()->isIntegerType() &&
2695 "Unexpected imaginary literal.");
2696
2697 Result.makeComplexInt();
2698 APSInt &Imag = Result.IntImag;
2699 if (!EvaluateInteger(SubExpr, Imag, Info))
2700 return false;
2701
2702 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2703 return true;
2704 }
2705}
2706
Peter Collingbournee9200682011-05-13 03:29:01 +00002707bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002708
John McCallfcef3cf2010-12-14 17:51:41 +00002709 switch (E->getCastKind()) {
2710 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002711 case CK_BaseToDerived:
2712 case CK_DerivedToBase:
2713 case CK_UncheckedDerivedToBase:
2714 case CK_Dynamic:
2715 case CK_ToUnion:
2716 case CK_ArrayToPointerDecay:
2717 case CK_FunctionToPointerDecay:
2718 case CK_NullToPointer:
2719 case CK_NullToMemberPointer:
2720 case CK_BaseToDerivedMemberPointer:
2721 case CK_DerivedToBaseMemberPointer:
2722 case CK_MemberPointerToBoolean:
2723 case CK_ConstructorConversion:
2724 case CK_IntegralToPointer:
2725 case CK_PointerToIntegral:
2726 case CK_PointerToBoolean:
2727 case CK_ToVoid:
2728 case CK_VectorSplat:
2729 case CK_IntegralCast:
2730 case CK_IntegralToBoolean:
2731 case CK_IntegralToFloating:
2732 case CK_FloatingToIntegral:
2733 case CK_FloatingToBoolean:
2734 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002735 case CK_CPointerToObjCPointerCast:
2736 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002737 case CK_AnyPointerToBlockPointerCast:
2738 case CK_ObjCObjectLValueCast:
2739 case CK_FloatingComplexToReal:
2740 case CK_FloatingComplexToBoolean:
2741 case CK_IntegralComplexToReal:
2742 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002743 case CK_ARCProduceObject:
2744 case CK_ARCConsumeObject:
2745 case CK_ARCReclaimReturnedObject:
2746 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002747 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002748
John McCallfcef3cf2010-12-14 17:51:41 +00002749 case CK_LValueToRValue:
2750 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002751 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002752
2753 case CK_Dependent:
2754 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002755 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002756 case CK_UserDefinedConversion:
2757 return false;
2758
2759 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002760 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002761 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002762 return false;
2763
John McCallfcef3cf2010-12-14 17:51:41 +00002764 Result.makeComplexFloat();
2765 Result.FloatImag = APFloat(Real.getSemantics());
2766 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002767 }
2768
John McCallfcef3cf2010-12-14 17:51:41 +00002769 case CK_FloatingComplexCast: {
2770 if (!Visit(E->getSubExpr()))
2771 return false;
2772
2773 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2774 QualType From
2775 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2776
2777 Result.FloatReal
2778 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2779 Result.FloatImag
2780 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2781 return true;
2782 }
2783
2784 case CK_FloatingComplexToIntegralComplex: {
2785 if (!Visit(E->getSubExpr()))
2786 return false;
2787
2788 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2789 QualType From
2790 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2791 Result.makeComplexInt();
2792 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2793 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2794 return true;
2795 }
2796
2797 case CK_IntegralRealToComplex: {
2798 APSInt &Real = Result.IntReal;
2799 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2800 return false;
2801
2802 Result.makeComplexInt();
2803 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2804 return true;
2805 }
2806
2807 case CK_IntegralComplexCast: {
2808 if (!Visit(E->getSubExpr()))
2809 return false;
2810
2811 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2812 QualType From
2813 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2814
2815 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2816 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2817 return true;
2818 }
2819
2820 case CK_IntegralComplexToFloatingComplex: {
2821 if (!Visit(E->getSubExpr()))
2822 return false;
2823
2824 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2825 QualType From
2826 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2827 Result.makeComplexFloat();
2828 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2829 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2830 return true;
2831 }
2832 }
2833
2834 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002835 return false;
2836}
2837
John McCall93d91dc2010-05-07 17:22:02 +00002838bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002839 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002840 VisitIgnoredValue(E->getLHS());
2841 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002842 }
John McCall93d91dc2010-05-07 17:22:02 +00002843 if (!Visit(E->getLHS()))
2844 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002845
John McCall93d91dc2010-05-07 17:22:02 +00002846 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002847 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002848 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002849
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002850 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2851 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002852 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002853 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002854 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002855 if (Result.isComplexFloat()) {
2856 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2857 APFloat::rmNearestTiesToEven);
2858 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2859 APFloat::rmNearestTiesToEven);
2860 } else {
2861 Result.getComplexIntReal() += RHS.getComplexIntReal();
2862 Result.getComplexIntImag() += RHS.getComplexIntImag();
2863 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002864 break;
John McCalle3027922010-08-25 11:45:40 +00002865 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002866 if (Result.isComplexFloat()) {
2867 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2868 APFloat::rmNearestTiesToEven);
2869 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2870 APFloat::rmNearestTiesToEven);
2871 } else {
2872 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2873 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2874 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002875 break;
John McCalle3027922010-08-25 11:45:40 +00002876 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002877 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002878 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002879 APFloat &LHS_r = LHS.getComplexFloatReal();
2880 APFloat &LHS_i = LHS.getComplexFloatImag();
2881 APFloat &RHS_r = RHS.getComplexFloatReal();
2882 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002883
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002884 APFloat Tmp = LHS_r;
2885 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2886 Result.getComplexFloatReal() = Tmp;
2887 Tmp = LHS_i;
2888 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2889 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2890
2891 Tmp = LHS_r;
2892 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2893 Result.getComplexFloatImag() = Tmp;
2894 Tmp = LHS_i;
2895 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2896 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2897 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002898 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002899 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002900 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2901 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002902 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002903 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2904 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2905 }
2906 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002907 case BO_Div:
2908 if (Result.isComplexFloat()) {
2909 ComplexValue LHS = Result;
2910 APFloat &LHS_r = LHS.getComplexFloatReal();
2911 APFloat &LHS_i = LHS.getComplexFloatImag();
2912 APFloat &RHS_r = RHS.getComplexFloatReal();
2913 APFloat &RHS_i = RHS.getComplexFloatImag();
2914 APFloat &Res_r = Result.getComplexFloatReal();
2915 APFloat &Res_i = Result.getComplexFloatImag();
2916
2917 APFloat Den = RHS_r;
2918 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2919 APFloat Tmp = RHS_i;
2920 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2921 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2922
2923 Res_r = LHS_r;
2924 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2925 Tmp = LHS_i;
2926 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2927 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2928 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2929
2930 Res_i = LHS_i;
2931 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2932 Tmp = LHS_r;
2933 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2934 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2935 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2936 } else {
2937 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2938 // FIXME: what about diagnostics?
2939 return false;
2940 }
2941 ComplexValue LHS = Result;
2942 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2943 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2944 Result.getComplexIntReal() =
2945 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2946 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2947 Result.getComplexIntImag() =
2948 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2949 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2950 }
2951 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002952 }
2953
John McCall93d91dc2010-05-07 17:22:02 +00002954 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002955}
2956
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002957bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2958 // Get the operand value into 'Result'.
2959 if (!Visit(E->getSubExpr()))
2960 return false;
2961
2962 switch (E->getOpcode()) {
2963 default:
2964 // FIXME: what about diagnostics?
2965 return false;
2966 case UO_Extension:
2967 return true;
2968 case UO_Plus:
2969 // The result is always just the subexpr.
2970 return true;
2971 case UO_Minus:
2972 if (Result.isComplexFloat()) {
2973 Result.getComplexFloatReal().changeSign();
2974 Result.getComplexFloatImag().changeSign();
2975 }
2976 else {
2977 Result.getComplexIntReal() = -Result.getComplexIntReal();
2978 Result.getComplexIntImag() = -Result.getComplexIntImag();
2979 }
2980 return true;
2981 case UO_Not:
2982 if (Result.isComplexFloat())
2983 Result.getComplexFloatImag().changeSign();
2984 else
2985 Result.getComplexIntImag() = -Result.getComplexIntImag();
2986 return true;
2987 }
2988}
2989
Anders Carlsson537969c2008-11-16 20:27:53 +00002990//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00002991// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00002992//===----------------------------------------------------------------------===//
2993
Richard Smith0b0a0b62011-10-29 20:57:55 +00002994static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002995 // In C, function designators are not lvalues, but we evaluate them as if they
2996 // are.
2997 if (E->isGLValue() || E->getType()->isFunctionType()) {
2998 LValue LV;
2999 if (!EvaluateLValue(E, LV, Info))
3000 return false;
3001 LV.moveInto(Result);
3002 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003003 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003004 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003005 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003006 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003007 return false;
John McCall45d55e42010-05-07 21:00:08 +00003008 } else if (E->getType()->hasPointerRepresentation()) {
3009 LValue LV;
3010 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003011 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003012 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003013 } else if (E->getType()->isRealFloatingType()) {
3014 llvm::APFloat F(0.0);
3015 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003016 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003017 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003018 } else if (E->getType()->isAnyComplexType()) {
3019 ComplexValue C;
3020 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003021 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003022 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003023 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003024 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003025
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003026 return true;
3027}
3028
Richard Smith11562c52011-10-28 17:51:58 +00003029
Richard Smith7b553f12011-10-29 00:50:52 +00003030/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003031/// any crazy technique (that has nothing to do with language standards) that
3032/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003033/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3034/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003035bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003036 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003037
Richard Smith0b0a0b62011-10-29 20:57:55 +00003038 CCValue Value;
3039 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003040 return false;
3041
3042 if (isGLValue()) {
3043 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003044 LV.setFrom(Value);
3045 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3046 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003047 }
3048
Richard Smith0b0a0b62011-10-29 20:57:55 +00003049 // Check this core constant expression is a constant expression, and if so,
3050 // slice it down to one.
3051 if (!CheckConstantExpression(Value))
3052 return false;
3053 Result.Val = Value;
3054 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003055}
3056
Jay Foad39c79802011-01-12 09:06:06 +00003057bool Expr::EvaluateAsBooleanCondition(bool &Result,
3058 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003059 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003060 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003061 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3062 Result);
John McCall1be1c632010-01-05 23:42:56 +00003063}
3064
Richard Smithcaf33902011-10-10 18:28:20 +00003065bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003066 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003067 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003068 !ExprResult.Val.isInt()) {
3069 return false;
3070 }
3071 Result = ExprResult.Val.getInt();
3072 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003073}
3074
Jay Foad39c79802011-01-12 09:06:06 +00003075bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003076 EvalInfo Info(Ctx, Result);
3077
John McCall45d55e42010-05-07 21:00:08 +00003078 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003079 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003080 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003081 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003082 return true;
3083 }
3084 return false;
3085}
3086
Jay Foad39c79802011-01-12 09:06:06 +00003087bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3088 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003089 EvalInfo Info(Ctx, Result);
3090
3091 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003092 // Don't allow references to out-of-scope function parameters to escape.
3093 if (EvaluateLValue(this, LV, Info) &&
3094 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3095 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003096 return true;
3097 }
3098 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003099}
3100
Richard Smith7b553f12011-10-29 00:50:52 +00003101/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3102/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003103bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003104 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003105 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003106}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003107
Jay Foad39c79802011-01-12 09:06:06 +00003108bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003109 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003110}
3111
Richard Smithcaf33902011-10-10 18:28:20 +00003112APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003113 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003114 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003115 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003116 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003117 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003118
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003119 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003120}
John McCall864e3962010-05-07 05:32:02 +00003121
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003122 bool Expr::EvalResult::isGlobalLValue() const {
3123 assert(Val.isLValue());
3124 return IsGlobalLValue(Val.getLValueBase());
3125 }
3126
3127
John McCall864e3962010-05-07 05:32:02 +00003128/// isIntegerConstantExpr - this recursive routine will test if an expression is
3129/// an integer constant expression.
3130
3131/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3132/// comma, etc
3133///
3134/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3135/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3136/// cast+dereference.
3137
3138// CheckICE - This function does the fundamental ICE checking: the returned
3139// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3140// Note that to reduce code duplication, this helper does no evaluation
3141// itself; the caller checks whether the expression is evaluatable, and
3142// in the rare cases where CheckICE actually cares about the evaluated
3143// value, it calls into Evalute.
3144//
3145// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003146// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003147// 1: This expression is not an ICE, but if it isn't evaluated, it's
3148// a legal subexpression for an ICE. This return value is used to handle
3149// the comma operator in C99 mode.
3150// 2: This expression is not an ICE, and is not a legal subexpression for one.
3151
Dan Gohman28ade552010-07-26 21:25:24 +00003152namespace {
3153
John McCall864e3962010-05-07 05:32:02 +00003154struct ICEDiag {
3155 unsigned Val;
3156 SourceLocation Loc;
3157
3158 public:
3159 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3160 ICEDiag() : Val(0) {}
3161};
3162
Dan Gohman28ade552010-07-26 21:25:24 +00003163}
3164
3165static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003166
3167static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3168 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003169 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003170 !EVResult.Val.isInt()) {
3171 return ICEDiag(2, E->getLocStart());
3172 }
3173 return NoDiag();
3174}
3175
3176static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3177 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003178 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003179 return ICEDiag(2, E->getLocStart());
3180 }
3181
3182 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003183#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003184#define STMT(Node, Base) case Expr::Node##Class:
3185#define EXPR(Node, Base)
3186#include "clang/AST/StmtNodes.inc"
3187 case Expr::PredefinedExprClass:
3188 case Expr::FloatingLiteralClass:
3189 case Expr::ImaginaryLiteralClass:
3190 case Expr::StringLiteralClass:
3191 case Expr::ArraySubscriptExprClass:
3192 case Expr::MemberExprClass:
3193 case Expr::CompoundAssignOperatorClass:
3194 case Expr::CompoundLiteralExprClass:
3195 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003196 case Expr::DesignatedInitExprClass:
3197 case Expr::ImplicitValueInitExprClass:
3198 case Expr::ParenListExprClass:
3199 case Expr::VAArgExprClass:
3200 case Expr::AddrLabelExprClass:
3201 case Expr::StmtExprClass:
3202 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003203 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003204 case Expr::CXXDynamicCastExprClass:
3205 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003206 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003207 case Expr::CXXNullPtrLiteralExprClass:
3208 case Expr::CXXThisExprClass:
3209 case Expr::CXXThrowExprClass:
3210 case Expr::CXXNewExprClass:
3211 case Expr::CXXDeleteExprClass:
3212 case Expr::CXXPseudoDestructorExprClass:
3213 case Expr::UnresolvedLookupExprClass:
3214 case Expr::DependentScopeDeclRefExprClass:
3215 case Expr::CXXConstructExprClass:
3216 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003217 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003218 case Expr::CXXTemporaryObjectExprClass:
3219 case Expr::CXXUnresolvedConstructExprClass:
3220 case Expr::CXXDependentScopeMemberExprClass:
3221 case Expr::UnresolvedMemberExprClass:
3222 case Expr::ObjCStringLiteralClass:
3223 case Expr::ObjCEncodeExprClass:
3224 case Expr::ObjCMessageExprClass:
3225 case Expr::ObjCSelectorExprClass:
3226 case Expr::ObjCProtocolExprClass:
3227 case Expr::ObjCIvarRefExprClass:
3228 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003229 case Expr::ObjCIsaExprClass:
3230 case Expr::ShuffleVectorExprClass:
3231 case Expr::BlockExprClass:
3232 case Expr::BlockDeclRefExprClass:
3233 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003234 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003235 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003236 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003237 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003238 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003239 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003240 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003241 return ICEDiag(2, E->getLocStart());
3242
Sebastian Redl12757ab2011-09-24 17:48:14 +00003243 case Expr::InitListExprClass:
3244 if (Ctx.getLangOptions().CPlusPlus0x) {
3245 const InitListExpr *ILE = cast<InitListExpr>(E);
3246 if (ILE->getNumInits() == 0)
3247 return NoDiag();
3248 if (ILE->getNumInits() == 1)
3249 return CheckICE(ILE->getInit(0), Ctx);
3250 // Fall through for more than 1 expression.
3251 }
3252 return ICEDiag(2, E->getLocStart());
3253
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003254 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003255 case Expr::GNUNullExprClass:
3256 // GCC considers the GNU __null value to be an integral constant expression.
3257 return NoDiag();
3258
John McCall7c454bb2011-07-15 05:09:51 +00003259 case Expr::SubstNonTypeTemplateParmExprClass:
3260 return
3261 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3262
John McCall864e3962010-05-07 05:32:02 +00003263 case Expr::ParenExprClass:
3264 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003265 case Expr::GenericSelectionExprClass:
3266 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003267 case Expr::IntegerLiteralClass:
3268 case Expr::CharacterLiteralClass:
3269 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003270 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003271 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003272 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003273 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003274 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003275 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003276 return NoDiag();
3277 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003278 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003279 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3280 // constant expressions, but they can never be ICEs because an ICE cannot
3281 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003282 const CallExpr *CE = cast<CallExpr>(E);
3283 if (CE->isBuiltinCall(Ctx))
3284 return CheckEvalInICE(E, Ctx);
3285 return ICEDiag(2, E->getLocStart());
3286 }
3287 case Expr::DeclRefExprClass:
3288 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3289 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003290 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003291 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3292
3293 // Parameter variables are never constants. Without this check,
3294 // getAnyInitializer() can find a default argument, which leads
3295 // to chaos.
3296 if (isa<ParmVarDecl>(D))
3297 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3298
3299 // C++ 7.1.5.1p2
3300 // A variable of non-volatile const-qualified integral or enumeration
3301 // type initialized by an ICE can be used in ICEs.
3302 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003303 // Look for a declaration of this variable that has an initializer.
3304 const VarDecl *ID = 0;
3305 const Expr *Init = Dcl->getAnyInitializer(ID);
3306 if (Init) {
3307 if (ID->isInitKnownICE()) {
3308 // We have already checked whether this subexpression is an
3309 // integral constant expression.
3310 if (ID->isInitICE())
3311 return NoDiag();
3312 else
3313 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3314 }
3315
3316 // It's an ICE whether or not the definition we found is
3317 // out-of-line. See DR 721 and the discussion in Clang PR
3318 // 6206 for details.
3319
3320 if (Dcl->isCheckingICE()) {
3321 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3322 }
3323
3324 Dcl->setCheckingICE();
3325 ICEDiag Result = CheckICE(Init, Ctx);
3326 // Cache the result of the ICE test.
3327 Dcl->setInitKnownICE(Result.Val == 0);
3328 return Result;
3329 }
3330 }
3331 }
3332 return ICEDiag(2, E->getLocStart());
3333 case Expr::UnaryOperatorClass: {
3334 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3335 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003336 case UO_PostInc:
3337 case UO_PostDec:
3338 case UO_PreInc:
3339 case UO_PreDec:
3340 case UO_AddrOf:
3341 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003342 // C99 6.6/3 allows increment and decrement within unevaluated
3343 // subexpressions of constant expressions, but they can never be ICEs
3344 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003345 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003346 case UO_Extension:
3347 case UO_LNot:
3348 case UO_Plus:
3349 case UO_Minus:
3350 case UO_Not:
3351 case UO_Real:
3352 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003353 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003354 }
3355
3356 // OffsetOf falls through here.
3357 }
3358 case Expr::OffsetOfExprClass: {
3359 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003360 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003361 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003362 // compliance: we should warn earlier for offsetof expressions with
3363 // array subscripts that aren't ICEs, and if the array subscripts
3364 // are ICEs, the value of the offsetof must be an integer constant.
3365 return CheckEvalInICE(E, Ctx);
3366 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003367 case Expr::UnaryExprOrTypeTraitExprClass: {
3368 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3369 if ((Exp->getKind() == UETT_SizeOf) &&
3370 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003371 return ICEDiag(2, E->getLocStart());
3372 return NoDiag();
3373 }
3374 case Expr::BinaryOperatorClass: {
3375 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3376 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003377 case BO_PtrMemD:
3378 case BO_PtrMemI:
3379 case BO_Assign:
3380 case BO_MulAssign:
3381 case BO_DivAssign:
3382 case BO_RemAssign:
3383 case BO_AddAssign:
3384 case BO_SubAssign:
3385 case BO_ShlAssign:
3386 case BO_ShrAssign:
3387 case BO_AndAssign:
3388 case BO_XorAssign:
3389 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003390 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3391 // constant expressions, but they can never be ICEs because an ICE cannot
3392 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003393 return ICEDiag(2, E->getLocStart());
3394
John McCalle3027922010-08-25 11:45:40 +00003395 case BO_Mul:
3396 case BO_Div:
3397 case BO_Rem:
3398 case BO_Add:
3399 case BO_Sub:
3400 case BO_Shl:
3401 case BO_Shr:
3402 case BO_LT:
3403 case BO_GT:
3404 case BO_LE:
3405 case BO_GE:
3406 case BO_EQ:
3407 case BO_NE:
3408 case BO_And:
3409 case BO_Xor:
3410 case BO_Or:
3411 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003412 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3413 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003414 if (Exp->getOpcode() == BO_Div ||
3415 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003416 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003417 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003418 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003419 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003420 if (REval == 0)
3421 return ICEDiag(1, E->getLocStart());
3422 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003423 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003424 if (LEval.isMinSignedValue())
3425 return ICEDiag(1, E->getLocStart());
3426 }
3427 }
3428 }
John McCalle3027922010-08-25 11:45:40 +00003429 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003430 if (Ctx.getLangOptions().C99) {
3431 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3432 // if it isn't evaluated.
3433 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3434 return ICEDiag(1, E->getLocStart());
3435 } else {
3436 // In both C89 and C++, commas in ICEs are illegal.
3437 return ICEDiag(2, E->getLocStart());
3438 }
3439 }
3440 if (LHSResult.Val >= RHSResult.Val)
3441 return LHSResult;
3442 return RHSResult;
3443 }
John McCalle3027922010-08-25 11:45:40 +00003444 case BO_LAnd:
3445 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003446 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003447
3448 // C++0x [expr.const]p2:
3449 // [...] subexpressions of logical AND (5.14), logical OR
3450 // (5.15), and condi- tional (5.16) operations that are not
3451 // evaluated are not considered.
3452 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3453 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003454 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003455 return LHSResult;
3456
3457 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003458 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003459 return LHSResult;
3460 }
3461
John McCall864e3962010-05-07 05:32:02 +00003462 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3463 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3464 // Rare case where the RHS has a comma "side-effect"; we need
3465 // to actually check the condition to see whether the side
3466 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003467 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003468 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003469 return RHSResult;
3470 return NoDiag();
3471 }
3472
3473 if (LHSResult.Val >= RHSResult.Val)
3474 return LHSResult;
3475 return RHSResult;
3476 }
3477 }
3478 }
3479 case Expr::ImplicitCastExprClass:
3480 case Expr::CStyleCastExprClass:
3481 case Expr::CXXFunctionalCastExprClass:
3482 case Expr::CXXStaticCastExprClass:
3483 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003484 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003485 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003486 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003487 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003488 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3489 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003490 switch (cast<CastExpr>(E)->getCastKind()) {
3491 case CK_LValueToRValue:
3492 case CK_NoOp:
3493 case CK_IntegralToBoolean:
3494 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003495 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003496 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003497 return ICEDiag(2, E->getLocStart());
3498 }
John McCall864e3962010-05-07 05:32:02 +00003499 }
John McCallc07a0c72011-02-17 10:25:35 +00003500 case Expr::BinaryConditionalOperatorClass: {
3501 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3502 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3503 if (CommonResult.Val == 2) return CommonResult;
3504 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3505 if (FalseResult.Val == 2) return FalseResult;
3506 if (CommonResult.Val == 1) return CommonResult;
3507 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003508 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003509 return FalseResult;
3510 }
John McCall864e3962010-05-07 05:32:02 +00003511 case Expr::ConditionalOperatorClass: {
3512 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3513 // If the condition (ignoring parens) is a __builtin_constant_p call,
3514 // then only the true side is actually considered in an integer constant
3515 // expression, and it is fully evaluated. This is an important GNU
3516 // extension. See GCC PR38377 for discussion.
3517 if (const CallExpr *CallCE
3518 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3519 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3520 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003521 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003522 !EVResult.Val.isInt()) {
3523 return ICEDiag(2, E->getLocStart());
3524 }
3525 return NoDiag();
3526 }
3527 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003528 if (CondResult.Val == 2)
3529 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003530
3531 // C++0x [expr.const]p2:
3532 // subexpressions of [...] conditional (5.16) operations that
3533 // are not evaluated are not considered
3534 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003535 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003536 : false;
3537 ICEDiag TrueResult = NoDiag();
3538 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3539 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3540 ICEDiag FalseResult = NoDiag();
3541 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3542 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3543
John McCall864e3962010-05-07 05:32:02 +00003544 if (TrueResult.Val == 2)
3545 return TrueResult;
3546 if (FalseResult.Val == 2)
3547 return FalseResult;
3548 if (CondResult.Val == 1)
3549 return CondResult;
3550 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3551 return NoDiag();
3552 // Rare case where the diagnostics depend on which side is evaluated
3553 // Note that if we get here, CondResult is 0, and at least one of
3554 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003555 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003556 return FalseResult;
3557 }
3558 return TrueResult;
3559 }
3560 case Expr::CXXDefaultArgExprClass:
3561 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3562 case Expr::ChooseExprClass: {
3563 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3564 }
3565 }
3566
3567 // Silence a GCC warning
3568 return ICEDiag(2, E->getLocStart());
3569}
3570
3571bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3572 SourceLocation *Loc, bool isEvaluated) const {
3573 ICEDiag d = CheckICE(this, Ctx);
3574 if (d.Val != 0) {
3575 if (Loc) *Loc = d.Loc;
3576 return false;
3577 }
Richard Smith11562c52011-10-28 17:51:58 +00003578 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003579 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003580 return true;
3581}