blob: 31fddb62485923458b160dc65af2bbfbba44d6ee [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
Peter Collingbournee9200682011-05-13 03:29:01 +0000198 const Expr *getLValueBase() { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000199 CharUnits &getLValueOffset() { return Offset; }
200 unsigned getLValueCallIndex() { return CallIndex; }
John McCall45d55e42010-05-07 21:00:08 +0000201
Richard Smith0b0a0b62011-10-29 20:57:55 +0000202 void moveInto(CCValue &V) const {
203 V = CCValue(Base, Offset, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000204 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000205 void setFrom(const CCValue &V) {
206 assert(V.isLValue());
207 Base = V.getLValueBase();
208 Offset = V.getLValueOffset();
209 CallIndex = V.getLValueCallIndex();
John McCallc07a0c72011-02-17 10:25:35 +0000210 }
John McCall45d55e42010-05-07 21:00:08 +0000211 };
John McCall93d91dc2010-05-07 17:22:02 +0000212}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000213
Richard Smith0b0a0b62011-10-29 20:57:55 +0000214static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000215static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
216static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000217static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000218static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000219 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000220static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000221static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000222
223//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000224// Misc utilities
225//===----------------------------------------------------------------------===//
226
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000227static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000228 if (!E) return true;
229
230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
231 if (isa<FunctionDecl>(DRE->getDecl()))
232 return true;
233 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
234 return VD->hasGlobalStorage();
235 return false;
236 }
237
238 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
239 return CLE->isFileScope();
240
Richard Smith11562c52011-10-28 17:51:58 +0000241 if (isa<MemberExpr>(E))
242 return false;
243
John McCall95007602010-05-10 23:27:23 +0000244 return true;
245}
246
Richard Smith0b0a0b62011-10-29 20:57:55 +0000247static bool IsParamLValue(const Expr *E) {
248 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
249 return isa<ParmVarDecl>(DRE->getDecl());
250 return false;
251}
252
253/// Check that this core constant expression value is a valid value for a
254/// constant expression.
255static bool CheckConstantExpression(const CCValue &Value) {
256 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
257}
258
Richard Smith11562c52011-10-28 17:51:58 +0000259static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000260 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000261
John McCalleb3e4f32010-05-07 21:34:32 +0000262 // A null base expression indicates a null pointer. These are always
263 // evaluatable, and they are false unless the offset is zero.
264 if (!Base) {
265 Result = !Value.Offset.isZero();
266 return true;
267 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000268
John McCall95007602010-05-10 23:27:23 +0000269 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000270 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000271 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000272
John McCalleb3e4f32010-05-07 21:34:32 +0000273 // We have a non-null base expression. These are generally known to
274 // be true, but if it'a decl-ref to a weak symbol it can be null at
275 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000276 Result = true;
277
278 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000279 if (!DeclRef)
280 return true;
281
John McCalleb3e4f32010-05-07 21:34:32 +0000282 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000283 const ValueDecl* Decl = DeclRef->getDecl();
284 if (Decl->hasAttr<WeakAttr>() ||
285 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000286 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000287 return false;
288
Eli Friedman334046a2009-06-14 02:17:33 +0000289 return true;
290}
291
Richard Smith0b0a0b62011-10-29 20:57:55 +0000292static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000293 switch (Val.getKind()) {
294 case APValue::Uninitialized:
295 return false;
296 case APValue::Int:
297 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000298 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000299 case APValue::Float:
300 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000301 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000302 case APValue::ComplexInt:
303 Result = Val.getComplexIntReal().getBoolValue() ||
304 Val.getComplexIntImag().getBoolValue();
305 return true;
306 case APValue::ComplexFloat:
307 Result = !Val.getComplexFloatReal().isZero() ||
308 !Val.getComplexFloatImag().isZero();
309 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000310 case APValue::LValue: {
311 LValue PointerResult;
312 PointerResult.setFrom(Val);
313 return EvalPointerValueAsBool(PointerResult, Result);
314 }
Richard Smith11562c52011-10-28 17:51:58 +0000315 case APValue::Vector:
316 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000317 }
318
Richard Smith11562c52011-10-28 17:51:58 +0000319 llvm_unreachable("unknown APValue kind");
320}
321
322static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
323 EvalInfo &Info) {
324 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000325 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000326 if (!Evaluate(Val, Info, E))
327 return false;
328 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000329}
330
Mike Stump11289f42009-09-09 15:08:12 +0000331static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000332 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000333 unsigned DestWidth = Ctx.getIntWidth(DestType);
334 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000335 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000336
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000337 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000338 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000339 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000340 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
341 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000342}
343
Mike Stump11289f42009-09-09 15:08:12 +0000344static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000345 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000346 bool ignored;
347 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000348 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000349 APFloat::rmNearestTiesToEven, &ignored);
350 return Result;
351}
352
Mike Stump11289f42009-09-09 15:08:12 +0000353static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000354 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000355 unsigned DestWidth = Ctx.getIntWidth(DestType);
356 APSInt Result = Value;
357 // Figure out if this is a truncate, extend or noop cast.
358 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000359 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000360 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000361 return Result;
362}
363
Mike Stump11289f42009-09-09 15:08:12 +0000364static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000365 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000366
367 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
368 Result.convertFromAPInt(Value, Value.isSigned(),
369 APFloat::rmNearestTiesToEven);
370 return Result;
371}
372
Richard Smith27908702011-10-24 17:54:18 +0000373/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000374static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
375 unsigned CallIndex, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000376 // If this is a parameter to an active constexpr function call, perform
377 // argument substitution.
378 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000379 if (const CCValue *ArgValue =
380 Info.getCallValue(CallIndex, PVD->getFunctionScopeIndex())) {
381 Result = *ArgValue;
382 return true;
383 }
384 return false;
Richard Smith254a73d2011-10-28 22:34:42 +0000385 }
Richard Smith27908702011-10-24 17:54:18 +0000386
387 const Expr *Init = VD->getAnyInitializer();
388 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000389 return false;
Richard Smith27908702011-10-24 17:54:18 +0000390
Richard Smith0b0a0b62011-10-29 20:57:55 +0000391 if (APValue *V = VD->getEvaluatedValue()) {
392 Result = CCValue(*V, CCValue::NoCallIndex);
393 return !Result.isUninit();
394 }
Richard Smith27908702011-10-24 17:54:18 +0000395
396 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000397 return false;
Richard Smith27908702011-10-24 17:54:18 +0000398
399 VD->setEvaluatingValue();
400
Richard Smith0b0a0b62011-10-29 20:57:55 +0000401 Expr::EvalStatus EStatus;
402 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000403 // FIXME: The caller will need to know whether the value was a constant
404 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000405 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000406 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000407 return false;
408 }
Richard Smith27908702011-10-24 17:54:18 +0000409
Richard Smith0b0a0b62011-10-29 20:57:55 +0000410 VD->setEvaluatedValue(Result);
411 return true;
Richard Smith27908702011-10-24 17:54:18 +0000412}
413
Richard Smith11562c52011-10-28 17:51:58 +0000414static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000415 Qualifiers Quals = T.getQualifiers();
416 return Quals.hasConst() && !Quals.hasVolatile();
417}
418
Richard Smith11562c52011-10-28 17:51:58 +0000419bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000420 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000421 const Expr *Base = LVal.Base;
422
423 // FIXME: Indirection through a null pointer deserves a diagnostic.
424 if (!Base)
425 return false;
426
427 // FIXME: Support accessing subobjects of objects of literal types. A simple
428 // byte offset is insufficient for C++11 semantics: we need to know how the
429 // reference was formed (which union member was named, for instance).
430 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
431 if (!LVal.Offset.isZero())
432 return false;
433
434 const Decl *D = 0;
435
436 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
437 // If the lvalue has been cast to some other type, don't try to read it.
438 // FIXME: Could simulate a bitcast here.
439 if (!Info.Ctx.hasSameUnqualifiedType(Type, DRE->getType()))
440 return false;
441 D = DRE->getDecl();
442 }
443
444 // FIXME: Static data members accessed via a MemberExpr are represented as
445 // that MemberExpr. We should use the Decl directly instead.
446 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
447 if (!Info.Ctx.hasSameUnqualifiedType(Type, ME->getType()))
448 return false;
449 D = ME->getMemberDecl();
450 assert(!isa<FieldDecl>(D) && "shouldn't see fields here");
451 }
452
453 if (D) {
454 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
455 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000456 // expressions are constant expressions too. Inside constexpr functions,
457 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000458 // In C, such things can also be folded, although they are not ICEs.
459 //
460 // FIXME: Allow folding any const variable of literal type initialized with
461 // a constant expression. For now, we only allow variables with integral and
462 // floating types to be folded.
Richard Smith254a73d2011-10-28 22:34:42 +0000463 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
464 // interpretation of C++11 suggests that volatile parameters are OK if
465 // they're never read (there's no prohibition against constructing volatile
466 // objects in constant expressions), but lvalue-to-rvalue conversions on
467 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000468 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000469 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith0b0a0b62011-10-29 20:57:55 +0000470 !(Type->isIntegralOrEnumerationType() || Type->isRealFloatingType()) ||
471 !EvaluateVarDeclInit(Info, VD, LVal.CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000472 return false;
473
Richard Smith0b0a0b62011-10-29 20:57:55 +0000474 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000475 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000476
477 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
478 // conversion. This happens when the declaration and the lvalue should be
479 // considered synonymous, for instance when initializing an array of char
480 // from a string literal. Continue as if the initializer lvalue was the
481 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000482 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000483 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000484 Base = RVal.getLValueBase();
Richard Smith11562c52011-10-28 17:51:58 +0000485 }
486
487 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
488 // here.
489
490 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
491 // initializer until now for such expressions. Such an expression can't be
492 // an ICE in C, so this only matters for fold.
493 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
494 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
495 return Evaluate(RVal, Info, CLE->getInitializer());
496 }
497
498 return false;
499}
500
Mike Stump876387b2009-10-27 22:09:17 +0000501namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000502enum EvalStmtResult {
503 /// Evaluation failed.
504 ESR_Failed,
505 /// Hit a 'return' statement.
506 ESR_Returned,
507 /// Evaluation succeeded.
508 ESR_Succeeded
509};
510}
511
512// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000513static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000514 const Stmt *S) {
515 switch (S->getStmtClass()) {
516 default:
517 return ESR_Failed;
518
519 case Stmt::NullStmtClass:
520 case Stmt::DeclStmtClass:
521 return ESR_Succeeded;
522
523 case Stmt::ReturnStmtClass:
524 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
525 return ESR_Returned;
526 return ESR_Failed;
527
528 case Stmt::CompoundStmtClass: {
529 const CompoundStmt *CS = cast<CompoundStmt>(S);
530 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
531 BE = CS->body_end(); BI != BE; ++BI) {
532 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
533 if (ESR != ESR_Succeeded)
534 return ESR;
535 }
536 return ESR_Succeeded;
537 }
538 }
539}
540
541/// Evaluate a function call.
542static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000543 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000544 // FIXME: Implement a proper call limit, along with a command-line flag.
545 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
546 return false;
547
Richard Smith0b0a0b62011-10-29 20:57:55 +0000548 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000549 // FIXME: Deal with default arguments and 'this'.
550 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
551 I != E; ++I)
552 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
553 return false;
554
555 CallStackFrame Frame(Info, ArgValues.data());
556 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
557}
558
559namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000560class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000561 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000562 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000563public:
564
Richard Smith725810a2011-10-16 21:26:27 +0000565 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000566
567 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000568 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000569 return true;
570 }
571
Peter Collingbournee9200682011-05-13 03:29:01 +0000572 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
573 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000574 return Visit(E->getResultExpr());
575 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000576 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000577 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000578 return true;
579 return false;
580 }
John McCall31168b02011-06-15 23:02:42 +0000581 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000582 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000583 return true;
584 return false;
585 }
586 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000587 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000588 return true;
589 return false;
590 }
591
Mike Stump876387b2009-10-27 22:09:17 +0000592 // We don't want to evaluate BlockExprs multiple times, as they generate
593 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000594 bool VisitBlockExpr(const BlockExpr *E) { return true; }
595 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
596 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000597 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000598 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
599 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
600 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
601 bool VisitStringLiteral(const StringLiteral *E) { return false; }
602 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
603 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000604 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000605 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000606 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000607 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000608 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000609 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
610 bool VisitBinAssign(const BinaryOperator *E) { return true; }
611 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
612 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000613 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
615 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
616 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
617 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
618 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000619 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000620 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000621 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000622 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000623 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000624
625 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000626 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000627 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
628 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000629 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000630 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000631 return false;
632 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000633
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000635};
636
John McCallc07a0c72011-02-17 10:25:35 +0000637class OpaqueValueEvaluation {
638 EvalInfo &info;
639 OpaqueValueExpr *opaqueValue;
640
641public:
642 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
643 Expr *value)
644 : info(info), opaqueValue(opaqueValue) {
645
646 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000647 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000648 this->opaqueValue = 0;
649 return;
650 }
John McCallc07a0c72011-02-17 10:25:35 +0000651 }
652
653 bool hasError() const { return opaqueValue == 0; }
654
655 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000656 // FIXME: This will not work for recursive constexpr functions using opaque
657 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000658 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
659 }
660};
661
Mike Stump876387b2009-10-27 22:09:17 +0000662} // end anonymous namespace
663
Eli Friedman9a156e52008-11-12 09:44:48 +0000664//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000665// Generic Evaluation
666//===----------------------------------------------------------------------===//
667namespace {
668
669template <class Derived, typename RetTy=void>
670class ExprEvaluatorBase
671 : public ConstStmtVisitor<Derived, RetTy> {
672private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000673 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000674 return static_cast<Derived*>(this)->Success(V, E);
675 }
676 RetTy DerivedError(const Expr *E) {
677 return static_cast<Derived*>(this)->Error(E);
678 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000679 RetTy DerivedValueInitialization(const Expr *E) {
680 return static_cast<Derived*>(this)->ValueInitialization(E);
681 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000682
683protected:
684 EvalInfo &Info;
685 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
686 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
687
Richard Smith4ce706a2011-10-11 21:43:33 +0000688 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
689
Peter Collingbournee9200682011-05-13 03:29:01 +0000690public:
691 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
692
693 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000694 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000695 }
696 RetTy VisitExpr(const Expr *E) {
697 return DerivedError(E);
698 }
699
700 RetTy VisitParenExpr(const ParenExpr *E)
701 { return StmtVisitorTy::Visit(E->getSubExpr()); }
702 RetTy VisitUnaryExtension(const UnaryOperator *E)
703 { return StmtVisitorTy::Visit(E->getSubExpr()); }
704 RetTy VisitUnaryPlus(const UnaryOperator *E)
705 { return StmtVisitorTy::Visit(E->getSubExpr()); }
706 RetTy VisitChooseExpr(const ChooseExpr *E)
707 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
708 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
709 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000710 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
711 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000712
713 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
714 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
715 if (opaque.hasError())
716 return DerivedError(E);
717
718 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000719 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000720 return DerivedError(E);
721
722 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
723 }
724
725 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
726 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000727 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000728 return DerivedError(E);
729
Richard Smith11562c52011-10-28 17:51:58 +0000730 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000731 return StmtVisitorTy::Visit(EvalExpr);
732 }
733
734 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000735 const CCValue *Value = Info.getOpaqueValue(E);
736 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000737 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
738 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000739 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000740 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000741
Richard Smith254a73d2011-10-28 22:34:42 +0000742 RetTy VisitCallExpr(const CallExpr *E) {
743 const Expr *Callee = E->getCallee();
744 QualType CalleeType = Callee->getType();
745
746 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
747 // non-static member function.
748 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
749 return DerivedError(E);
750
751 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
752 return DerivedError(E);
753
Richard Smith0b0a0b62011-10-29 20:57:55 +0000754 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000755 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
756 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
757 return DerivedError(Callee);
758
759 const FunctionDecl *FD = 0;
760 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
761 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
762 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
763 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
764 if (!FD)
765 return DerivedError(Callee);
766
767 // Don't call function pointers which have been cast to some other type.
768 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
769 return DerivedError(E);
770
771 const FunctionDecl *Definition;
772 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000773 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000774 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
775
776 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
777 HandleFunctionCall(Args, Body, Info, Result))
778 return DerivedSuccess(Result, E);
779
780 return DerivedError(E);
781 }
782
Richard Smith11562c52011-10-28 17:51:58 +0000783 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
784 return StmtVisitorTy::Visit(E->getInitializer());
785 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000786 RetTy VisitInitListExpr(const InitListExpr *E) {
787 if (Info.getLangOpts().CPlusPlus0x) {
788 if (E->getNumInits() == 0)
789 return DerivedValueInitialization(E);
790 if (E->getNumInits() == 1)
791 return StmtVisitorTy::Visit(E->getInit(0));
792 }
793 return DerivedError(E);
794 }
795 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
796 return DerivedValueInitialization(E);
797 }
798 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
799 return DerivedValueInitialization(E);
800 }
801
Richard Smith11562c52011-10-28 17:51:58 +0000802 RetTy VisitCastExpr(const CastExpr *E) {
803 switch (E->getCastKind()) {
804 default:
805 break;
806
807 case CK_NoOp:
808 return StmtVisitorTy::Visit(E->getSubExpr());
809
810 case CK_LValueToRValue: {
811 LValue LVal;
812 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000813 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000814 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
815 return DerivedSuccess(RVal, E);
816 }
817 break;
818 }
819 }
820
821 return DerivedError(E);
822 }
823
Richard Smith4a678122011-10-24 18:44:57 +0000824 /// Visit a value which is evaluated, but whose value is ignored.
825 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000826 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000827 if (!Evaluate(Scratch, Info, E))
828 Info.EvalStatus.HasSideEffects = true;
829 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000830};
831
832}
833
834//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000835// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000836//
837// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
838// function designators (in C), decl references to void objects (in C), and
839// temporaries (if building with -Wno-address-of-temporary).
840//
841// LValue evaluation produces values comprising a base expression of one of the
842// following types:
843// * DeclRefExpr
844// * MemberExpr for a static member
845// * CompoundLiteralExpr in C
846// * StringLiteral
847// * PredefinedExpr
848// * ObjCEncodeExpr
849// * AddrLabelExpr
850// * BlockExpr
851// * CallExpr for a MakeStringConstant builtin
852// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000853//===----------------------------------------------------------------------===//
854namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000855class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000856 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000857 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000858 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000859
Peter Collingbournee9200682011-05-13 03:29:01 +0000860 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000861 Result.Base = E;
862 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000863 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000864 return true;
865 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000866public:
Mike Stump11289f42009-09-09 15:08:12 +0000867
John McCall45d55e42010-05-07 21:00:08 +0000868 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000869 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000870
Richard Smith0b0a0b62011-10-29 20:57:55 +0000871 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000872 Result.setFrom(V);
873 return true;
874 }
875 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000876 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000877 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000878
Richard Smith11562c52011-10-28 17:51:58 +0000879 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
880
Peter Collingbournee9200682011-05-13 03:29:01 +0000881 bool VisitDeclRefExpr(const DeclRefExpr *E);
882 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
883 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
884 bool VisitMemberExpr(const MemberExpr *E);
885 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
886 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
887 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
888 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000889
Peter Collingbournee9200682011-05-13 03:29:01 +0000890 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000891 switch (E->getCastKind()) {
892 default:
Richard Smith11562c52011-10-28 17:51:58 +0000893 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000894
Eli Friedmance3e02a2011-10-11 00:13:24 +0000895 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000896 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000897
Richard Smith11562c52011-10-28 17:51:58 +0000898 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
899 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000900 }
901 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000902
Eli Friedman449fe542009-03-23 04:56:01 +0000903 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000904
Eli Friedman9a156e52008-11-12 09:44:48 +0000905};
906} // end anonymous namespace
907
Richard Smith11562c52011-10-28 17:51:58 +0000908/// Evaluate an expression as an lvalue. This can be legitimately called on
909/// expressions which are not glvalues, in a few cases:
910/// * function designators in C,
911/// * "extern void" objects,
912/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000913static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000914 assert((E->isGLValue() || E->getType()->isFunctionType() ||
915 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
916 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000917 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000918}
919
Peter Collingbournee9200682011-05-13 03:29:01 +0000920bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000921 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000922 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000923 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
924 return VisitVarDecl(E, VD);
925 return Error(E);
926}
Richard Smith733237d2011-10-24 23:14:33 +0000927
Richard Smith11562c52011-10-28 17:51:58 +0000928bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
929 if (!VD->getType()->isReferenceType())
930 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000931
Richard Smith0b0a0b62011-10-29 20:57:55 +0000932 CCValue V;
933 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
934 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000935
936 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000937}
938
Peter Collingbournee9200682011-05-13 03:29:01 +0000939bool
940LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000941 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
942 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
943 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000944 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000945}
946
Peter Collingbournee9200682011-05-13 03:29:01 +0000947bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000948 // Handle static data members.
949 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
950 VisitIgnoredValue(E->getBase());
951 return VisitVarDecl(E, VD);
952 }
953
Richard Smith254a73d2011-10-28 22:34:42 +0000954 // Handle static member functions.
955 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
956 if (MD->isStatic()) {
957 VisitIgnoredValue(E->getBase());
958 return Success(E);
959 }
960 }
961
Eli Friedman9a156e52008-11-12 09:44:48 +0000962 QualType Ty;
963 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000964 if (!EvaluatePointer(E->getBase(), Result, Info))
965 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000966 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000967 } else {
John McCall45d55e42010-05-07 21:00:08 +0000968 if (!Visit(E->getBase()))
969 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000970 Ty = E->getBase()->getType();
971 }
972
Peter Collingbournee9200682011-05-13 03:29:01 +0000973 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000974 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000975
Peter Collingbournee9200682011-05-13 03:29:01 +0000976 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000977 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000978 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000979
980 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000981 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000982
Eli Friedmana3c122d2011-07-07 01:54:01 +0000983 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000984 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000985 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000986}
987
Peter Collingbournee9200682011-05-13 03:29:01 +0000988bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000989 // FIXME: Deal with vectors as array subscript bases.
990 if (E->getBase()->getType()->isVectorType())
991 return false;
992
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000993 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000994 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000995
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000996 APSInt Index;
997 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000998 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000999
Ken Dyck40775002010-01-11 17:06:35 +00001000 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001001 Result.Offset += Index.getSExtValue() * ElementSize;
1002 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001003}
Eli Friedman9a156e52008-11-12 09:44:48 +00001004
Peter Collingbournee9200682011-05-13 03:29:01 +00001005bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001006 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001007}
1008
Eli Friedman9a156e52008-11-12 09:44:48 +00001009//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001010// Pointer Evaluation
1011//===----------------------------------------------------------------------===//
1012
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001013namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001014class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001015 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001016 LValue &Result;
1017
Peter Collingbournee9200682011-05-13 03:29:01 +00001018 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001019 Result.Base = E;
1020 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001021 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001022 return true;
1023 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001024public:
Mike Stump11289f42009-09-09 15:08:12 +00001025
John McCall45d55e42010-05-07 21:00:08 +00001026 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001027 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001028
Richard Smith0b0a0b62011-10-29 20:57:55 +00001029 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001030 Result.setFrom(V);
1031 return true;
1032 }
1033 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001034 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001035 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001036 bool ValueInitialization(const Expr *E) {
1037 return Success((Expr*)0);
1038 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001039
John McCall45d55e42010-05-07 21:00:08 +00001040 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001041 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001042 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001043 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001044 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001045 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001046 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001047 bool VisitCallExpr(const CallExpr *E);
1048 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001049 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001050 return Success(E);
1051 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001052 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001053 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001054 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001055
Eli Friedman449fe542009-03-23 04:56:01 +00001056 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001057};
Chris Lattner05706e882008-07-11 18:11:29 +00001058} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001059
John McCall45d55e42010-05-07 21:00:08 +00001060static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001061 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001062 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001063}
1064
John McCall45d55e42010-05-07 21:00:08 +00001065bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001066 if (E->getOpcode() != BO_Add &&
1067 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001068 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001069
Chris Lattner05706e882008-07-11 18:11:29 +00001070 const Expr *PExp = E->getLHS();
1071 const Expr *IExp = E->getRHS();
1072 if (IExp->getType()->isPointerType())
1073 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001074
John McCall45d55e42010-05-07 21:00:08 +00001075 if (!EvaluatePointer(PExp, Result, Info))
1076 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001077
John McCall45d55e42010-05-07 21:00:08 +00001078 llvm::APSInt Offset;
1079 if (!EvaluateInteger(IExp, Offset, Info))
1080 return false;
1081 int64_t AdditionalOffset
1082 = Offset.isSigned() ? Offset.getSExtValue()
1083 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001084
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001085 // Compute the new offset in the appropriate width.
1086
1087 QualType PointeeType =
1088 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001089 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001090
Anders Carlssonef56fba2009-02-19 04:55:58 +00001091 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1092 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001093 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001094 else
John McCall45d55e42010-05-07 21:00:08 +00001095 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001096
John McCalle3027922010-08-25 11:45:40 +00001097 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001098 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001099 else
John McCall45d55e42010-05-07 21:00:08 +00001100 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001101
John McCall45d55e42010-05-07 21:00:08 +00001102 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001103}
Eli Friedman9a156e52008-11-12 09:44:48 +00001104
John McCall45d55e42010-05-07 21:00:08 +00001105bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1106 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001107}
Mike Stump11289f42009-09-09 15:08:12 +00001108
Chris Lattner05706e882008-07-11 18:11:29 +00001109
Peter Collingbournee9200682011-05-13 03:29:01 +00001110bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1111 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001112
Eli Friedman847a2bc2009-12-27 05:43:15 +00001113 switch (E->getCastKind()) {
1114 default:
1115 break;
1116
John McCalle3027922010-08-25 11:45:40 +00001117 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001118 case CK_CPointerToObjCPointerCast:
1119 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001120 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001121 return Visit(SubExpr);
1122
Anders Carlsson18275092010-10-31 20:41:46 +00001123 case CK_DerivedToBase:
1124 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001125 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001126 return false;
1127
1128 // Now figure out the necessary offset to add to the baseLV to get from
1129 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001130 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001131
1132 QualType Ty = E->getSubExpr()->getType();
1133 const CXXRecordDecl *DerivedDecl =
1134 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1135
1136 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1137 PathE = E->path_end(); PathI != PathE; ++PathI) {
1138 const CXXBaseSpecifier *Base = *PathI;
1139
1140 // FIXME: If the base is virtual, we'd need to determine the type of the
1141 // most derived class and we don't support that right now.
1142 if (Base->isVirtual())
1143 return false;
1144
1145 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1146 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1147
Richard Smith0b0a0b62011-10-29 20:57:55 +00001148 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001149 DerivedDecl = BaseDecl;
1150 }
1151
Anders Carlsson18275092010-10-31 20:41:46 +00001152 return true;
1153 }
1154
Richard Smith0b0a0b62011-10-29 20:57:55 +00001155 case CK_NullToPointer:
1156 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001157
John McCalle3027922010-08-25 11:45:40 +00001158 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001159 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001160 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001161 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001162
John McCall45d55e42010-05-07 21:00:08 +00001163 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001164 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1165 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001166 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001167 Result.Offset = CharUnits::fromQuantity(N);
1168 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001169 return true;
1170 } else {
1171 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001172 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001173 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001174 }
1175 }
John McCalle3027922010-08-25 11:45:40 +00001176 case CK_ArrayToPointerDecay:
1177 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001178 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001179 }
1180
Richard Smith11562c52011-10-28 17:51:58 +00001181 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001182}
Chris Lattner05706e882008-07-11 18:11:29 +00001183
Peter Collingbournee9200682011-05-13 03:29:01 +00001184bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001185 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001186 Builtin::BI__builtin___CFStringMakeConstantString ||
1187 E->isBuiltinCall(Info.Ctx) ==
1188 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001189 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001190
Peter Collingbournee9200682011-05-13 03:29:01 +00001191 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001192}
Chris Lattner05706e882008-07-11 18:11:29 +00001193
1194//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001195// Vector Evaluation
1196//===----------------------------------------------------------------------===//
1197
1198namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001199 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001200 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1201 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001202 public:
Mike Stump11289f42009-09-09 15:08:12 +00001203
Richard Smith2d406342011-10-22 21:10:00 +00001204 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1205 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001206
Richard Smith2d406342011-10-22 21:10:00 +00001207 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1208 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1209 // FIXME: remove this APValue copy.
1210 Result = APValue(V.data(), V.size());
1211 return true;
1212 }
1213 bool Success(const APValue &V, const Expr *E) {
1214 Result = V;
1215 return true;
1216 }
1217 bool Error(const Expr *E) { return false; }
1218 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001219
Richard Smith2d406342011-10-22 21:10:00 +00001220 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001221 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001222 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001223 bool VisitInitListExpr(const InitListExpr *E);
1224 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001225 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001226 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001227 // shufflevector, ExtVectorElementExpr
1228 // (Note that these require implementing conversions
1229 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001230 };
1231} // end anonymous namespace
1232
1233static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001234 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001235 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001236}
1237
Richard Smith2d406342011-10-22 21:10:00 +00001238bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1239 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001240 QualType EltTy = VTy->getElementType();
1241 unsigned NElts = VTy->getNumElements();
1242 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001244 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001245 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001246
Eli Friedmanc757de22011-03-25 00:43:55 +00001247 switch (E->getCastKind()) {
1248 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001249 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001250 if (SETy->isIntegerType()) {
1251 APSInt IntResult;
1252 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001253 return Error(E);
1254 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001255 } else if (SETy->isRealFloatingType()) {
1256 APFloat F(0.0);
1257 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001258 return Error(E);
1259 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001260 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001261 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001262 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001263
1264 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001265 SmallVector<APValue, 4> Elts(NElts, Val);
1266 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001267 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001268 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001269 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001270 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001271 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001272
Eli Friedmanc757de22011-03-25 00:43:55 +00001273 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001274 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001275
Eli Friedmanc757de22011-03-25 00:43:55 +00001276 APSInt Init;
1277 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001278 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001279
Eli Friedmanc757de22011-03-25 00:43:55 +00001280 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1281 "Vectors must be composed of ints or floats");
1282
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001283 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001284 for (unsigned i = 0; i != NElts; ++i) {
1285 APSInt Tmp = Init.extOrTrunc(EltWidth);
1286
1287 if (EltTy->isIntegerType())
1288 Elts.push_back(APValue(Tmp));
1289 else
1290 Elts.push_back(APValue(APFloat(Tmp)));
1291
1292 Init >>= EltWidth;
1293 }
Richard Smith2d406342011-10-22 21:10:00 +00001294 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001295 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001296 default:
Richard Smith11562c52011-10-28 17:51:58 +00001297 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001298 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001299}
1300
Richard Smith2d406342011-10-22 21:10:00 +00001301bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001302VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001303 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001304 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001305 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001306
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001307 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001308 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001309
John McCall875679e2010-06-11 17:54:15 +00001310 // If a vector is initialized with a single element, that value
1311 // becomes every element of the vector, not just the first.
1312 // This is the behavior described in the IBM AltiVec documentation.
1313 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001314
1315 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001316 // vector (OpenCL 6.1.6).
1317 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001318 return Visit(E->getInit(0));
1319
John McCall875679e2010-06-11 17:54:15 +00001320 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001321 if (EltTy->isIntegerType()) {
1322 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001323 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001324 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001325 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001326 } else {
1327 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001328 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001329 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001330 InitValue = APValue(f);
1331 }
1332 for (unsigned i = 0; i < NumElements; i++) {
1333 Elements.push_back(InitValue);
1334 }
1335 } else {
1336 for (unsigned i = 0; i < NumElements; i++) {
1337 if (EltTy->isIntegerType()) {
1338 llvm::APSInt sInt(32);
1339 if (i < NumInits) {
1340 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001341 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001342 } else {
1343 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1344 }
1345 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001346 } else {
John McCall875679e2010-06-11 17:54:15 +00001347 llvm::APFloat f(0.0);
1348 if (i < NumInits) {
1349 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001350 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001351 } else {
1352 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1353 }
1354 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001355 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001356 }
1357 }
Richard Smith2d406342011-10-22 21:10:00 +00001358 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001359}
1360
Richard Smith2d406342011-10-22 21:10:00 +00001361bool
1362VectorExprEvaluator::ValueInitialization(const Expr *E) {
1363 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001364 QualType EltTy = VT->getElementType();
1365 APValue ZeroElement;
1366 if (EltTy->isIntegerType())
1367 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1368 else
1369 ZeroElement =
1370 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1371
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001372 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001373 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001374}
1375
Richard Smith2d406342011-10-22 21:10:00 +00001376bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001377 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001378 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001379}
1380
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001381//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001382// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001383//
1384// As a GNU extension, we support casting pointers to sufficiently-wide integer
1385// types and back in constant folding. Integer values are thus represented
1386// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001387//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001388
1389namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001390class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001391 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001392 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001393public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001394 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001395 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001396
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001397 bool Success(const llvm::APSInt &SI, const Expr *E) {
1398 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001399 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001400 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001401 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001402 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001403 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001404 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001405 return true;
1406 }
1407
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001408 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001409 assert(E->getType()->isIntegralOrEnumerationType() &&
1410 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001411 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001412 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001413 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001414 Result.getInt().setIsUnsigned(
1415 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001416 return true;
1417 }
1418
1419 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001420 assert(E->getType()->isIntegralOrEnumerationType() &&
1421 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001422 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001423 return true;
1424 }
1425
Ken Dyckdbc01912011-03-11 02:13:43 +00001426 bool Success(CharUnits Size, const Expr *E) {
1427 return Success(Size.getQuantity(), E);
1428 }
1429
1430
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001431 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001432 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001433 if (Info.EvalStatus.Diag == 0) {
1434 Info.EvalStatus.DiagLoc = L;
1435 Info.EvalStatus.Diag = D;
1436 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001437 }
Chris Lattner99415702008-07-12 00:14:42 +00001438 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001439 }
Mike Stump11289f42009-09-09 15:08:12 +00001440
Richard Smith0b0a0b62011-10-29 20:57:55 +00001441 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001442 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001443 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001444 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001445 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
Richard Smith4ce706a2011-10-11 21:43:33 +00001448 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1449
Peter Collingbournee9200682011-05-13 03:29:01 +00001450 //===--------------------------------------------------------------------===//
1451 // Visitor Methods
1452 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001453
Chris Lattner7174bf32008-07-12 00:38:25 +00001454 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001455 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001456 }
1457 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001458 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001459 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001460
1461 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1462 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001463 if (CheckReferencedDecl(E, E->getDecl()))
1464 return true;
1465
1466 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001467 }
1468 bool VisitMemberExpr(const MemberExpr *E) {
1469 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001470 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001471 return true;
1472 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001473
1474 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001475 }
1476
Peter Collingbournee9200682011-05-13 03:29:01 +00001477 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001478 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001479 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001480 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001481
Peter Collingbournee9200682011-05-13 03:29:01 +00001482 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001483 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001484
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001485 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001486 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001487 }
Mike Stump11289f42009-09-09 15:08:12 +00001488
Richard Smith4ce706a2011-10-11 21:43:33 +00001489 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001490 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001491 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001492 }
1493
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001494 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001495 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001496 }
1497
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001498 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1499 return Success(E->getValue(), E);
1500 }
1501
John Wiegley6242b6a2011-04-28 00:16:57 +00001502 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1503 return Success(E->getValue(), E);
1504 }
1505
John Wiegleyf9f65842011-04-25 06:54:41 +00001506 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1507 return Success(E->getValue(), E);
1508 }
1509
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001510 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001511 bool VisitUnaryImag(const UnaryOperator *E);
1512
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001513 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001514 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001515
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001516private:
Ken Dyck160146e2010-01-27 17:10:57 +00001517 CharUnits GetAlignOfExpr(const Expr *E);
1518 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001519 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001520 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001521 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001522};
Chris Lattner05706e882008-07-11 18:11:29 +00001523} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001524
Richard Smith11562c52011-10-28 17:51:58 +00001525/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1526/// produce either the integer value or a pointer.
1527///
1528/// GCC has a heinous extension which folds casts between pointer types and
1529/// pointer-sized integral types. We support this by allowing the evaluation of
1530/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1531/// Some simple arithmetic on such values is supported (they are treated much
1532/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001533static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1534 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001535 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001536 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001537}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001538
Daniel Dunbarce399542009-02-20 18:22:23 +00001539static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001540 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001541 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1542 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001543 Result = Val.getInt();
1544 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001545}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001546
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001547bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001548 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001549 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001550 // Check for signedness/width mismatches between E type and ECD value.
1551 bool SameSign = (ECD->getInitVal().isSigned()
1552 == E->getType()->isSignedIntegerOrEnumerationType());
1553 bool SameWidth = (ECD->getInitVal().getBitWidth()
1554 == Info.Ctx.getIntWidth(E->getType()));
1555 if (SameSign && SameWidth)
1556 return Success(ECD->getInitVal(), E);
1557 else {
1558 // Get rid of mismatch (otherwise Success assertions will fail)
1559 // by computing a new value matching the type of E.
1560 llvm::APSInt Val = ECD->getInitVal();
1561 if (!SameSign)
1562 Val.setIsSigned(!ECD->getInitVal().isSigned());
1563 if (!SameWidth)
1564 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1565 return Success(Val, E);
1566 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001567 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001568 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001569}
1570
Chris Lattner86ee2862008-10-06 06:40:35 +00001571/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1572/// as GCC.
1573static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1574 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001575 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001576 enum gcc_type_class {
1577 no_type_class = -1,
1578 void_type_class, integer_type_class, char_type_class,
1579 enumeral_type_class, boolean_type_class,
1580 pointer_type_class, reference_type_class, offset_type_class,
1581 real_type_class, complex_type_class,
1582 function_type_class, method_type_class,
1583 record_type_class, union_type_class,
1584 array_type_class, string_type_class,
1585 lang_type_class
1586 };
Mike Stump11289f42009-09-09 15:08:12 +00001587
1588 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001589 // ideal, however it is what gcc does.
1590 if (E->getNumArgs() == 0)
1591 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001592
Chris Lattner86ee2862008-10-06 06:40:35 +00001593 QualType ArgTy = E->getArg(0)->getType();
1594 if (ArgTy->isVoidType())
1595 return void_type_class;
1596 else if (ArgTy->isEnumeralType())
1597 return enumeral_type_class;
1598 else if (ArgTy->isBooleanType())
1599 return boolean_type_class;
1600 else if (ArgTy->isCharType())
1601 return string_type_class; // gcc doesn't appear to use char_type_class
1602 else if (ArgTy->isIntegerType())
1603 return integer_type_class;
1604 else if (ArgTy->isPointerType())
1605 return pointer_type_class;
1606 else if (ArgTy->isReferenceType())
1607 return reference_type_class;
1608 else if (ArgTy->isRealType())
1609 return real_type_class;
1610 else if (ArgTy->isComplexType())
1611 return complex_type_class;
1612 else if (ArgTy->isFunctionType())
1613 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001614 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001615 return record_type_class;
1616 else if (ArgTy->isUnionType())
1617 return union_type_class;
1618 else if (ArgTy->isArrayType())
1619 return array_type_class;
1620 else if (ArgTy->isUnionType())
1621 return union_type_class;
1622 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001623 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001624 return -1;
1625}
1626
John McCall95007602010-05-10 23:27:23 +00001627/// Retrieves the "underlying object type" of the given expression,
1628/// as used by __builtin_object_size.
1629QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1630 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1631 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1632 return VD->getType();
1633 } else if (isa<CompoundLiteralExpr>(E)) {
1634 return E->getType();
1635 }
1636
1637 return QualType();
1638}
1639
Peter Collingbournee9200682011-05-13 03:29:01 +00001640bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001641 // TODO: Perhaps we should let LLVM lower this?
1642 LValue Base;
1643 if (!EvaluatePointer(E->getArg(0), Base, Info))
1644 return false;
1645
1646 // If we can prove the base is null, lower to zero now.
1647 const Expr *LVBase = Base.getLValueBase();
1648 if (!LVBase) return Success(0, E);
1649
1650 QualType T = GetObjectType(LVBase);
1651 if (T.isNull() ||
1652 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001653 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001654 T->isVariablyModifiedType() ||
1655 T->isDependentType())
1656 return false;
1657
1658 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1659 CharUnits Offset = Base.getLValueOffset();
1660
1661 if (!Offset.isNegative() && Offset <= Size)
1662 Size -= Offset;
1663 else
1664 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001665 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001666}
1667
Peter Collingbournee9200682011-05-13 03:29:01 +00001668bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001669 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001670 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001671 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001672
1673 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001674 if (TryEvaluateBuiltinObjectSize(E))
1675 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001676
Eric Christopher99469702010-01-19 22:58:35 +00001677 // If evaluating the argument has side-effects we can't determine
1678 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001679 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001680 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001681 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001682 return Success(0, E);
1683 }
Mike Stump876387b2009-10-27 22:09:17 +00001684
Mike Stump722cedf2009-10-26 18:35:08 +00001685 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1686 }
1687
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001688 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001689 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001690
Anders Carlsson4c76e932008-11-24 04:21:33 +00001691 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001692 // __builtin_constant_p always has one operand: it returns true if that
1693 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001694 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001695
1696 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001697 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001698 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001699 return Success(Operand, E);
1700 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001701
1702 case Builtin::BI__builtin_expect:
1703 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001704
1705 case Builtin::BIstrlen:
1706 case Builtin::BI__builtin_strlen:
1707 // As an extension, we support strlen() and __builtin_strlen() as constant
1708 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001709 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001710 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1711 // The string literal may have embedded null characters. Find the first
1712 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001713 StringRef Str = S->getString();
1714 StringRef::size_type Pos = Str.find(0);
1715 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001716 Str = Str.substr(0, Pos);
1717
1718 return Success(Str.size(), E);
1719 }
1720
1721 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001722
1723 case Builtin::BI__atomic_is_lock_free: {
1724 APSInt SizeVal;
1725 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1726 return false;
1727
1728 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1729 // of two less than the maximum inline atomic width, we know it is
1730 // lock-free. If the size isn't a power of two, or greater than the
1731 // maximum alignment where we promote atomics, we know it is not lock-free
1732 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1733 // the answer can only be determined at runtime; for example, 16-byte
1734 // atomics have lock-free implementations on some, but not all,
1735 // x86-64 processors.
1736
1737 // Check power-of-two.
1738 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1739 if (!Size.isPowerOfTwo())
1740#if 0
1741 // FIXME: Suppress this folding until the ABI for the promotion width
1742 // settles.
1743 return Success(0, E);
1744#else
1745 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1746#endif
1747
1748#if 0
1749 // Check against promotion width.
1750 // FIXME: Suppress this folding until the ABI for the promotion width
1751 // settles.
1752 unsigned PromoteWidthBits =
1753 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1754 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1755 return Success(0, E);
1756#endif
1757
1758 // Check against inlining width.
1759 unsigned InlineWidthBits =
1760 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1761 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1762 return Success(1, E);
1763
1764 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1765 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001766 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001767}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001768
Chris Lattnere13042c2008-07-11 19:10:17 +00001769bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001770 if (E->isAssignmentOp())
1771 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1772
John McCalle3027922010-08-25 11:45:40 +00001773 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001774 VisitIgnoredValue(E->getLHS());
1775 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001776 }
1777
1778 if (E->isLogicalOp()) {
1779 // These need to be handled specially because the operands aren't
1780 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001781 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001782
Richard Smith11562c52011-10-28 17:51:58 +00001783 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001784 // We were able to evaluate the LHS, see if we can get away with not
1785 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001786 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001787 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001788
Richard Smith11562c52011-10-28 17:51:58 +00001789 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001790 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001791 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001792 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001793 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001794 }
1795 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001796 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001797 // We can't evaluate the LHS; however, sometimes the result
1798 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001799 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1800 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001801 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001802 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001803 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001804
1805 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001806 }
1807 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001808 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001809
Eli Friedman5a332ea2008-11-13 06:09:17 +00001810 return false;
1811 }
1812
Anders Carlssonacc79812008-11-16 07:17:21 +00001813 QualType LHSTy = E->getLHS()->getType();
1814 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001815
1816 if (LHSTy->isAnyComplexType()) {
1817 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001818 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001819
1820 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1821 return false;
1822
1823 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1824 return false;
1825
1826 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001827 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001828 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001829 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001830 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1831
John McCalle3027922010-08-25 11:45:40 +00001832 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001833 return Success((CR_r == APFloat::cmpEqual &&
1834 CR_i == APFloat::cmpEqual), E);
1835 else {
John McCalle3027922010-08-25 11:45:40 +00001836 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001837 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001838 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001839 CR_r == APFloat::cmpLessThan ||
1840 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001841 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001842 CR_i == APFloat::cmpLessThan ||
1843 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001844 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001845 } else {
John McCalle3027922010-08-25 11:45:40 +00001846 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001847 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1848 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1849 else {
John McCalle3027922010-08-25 11:45:40 +00001850 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001851 "Invalid compex comparison.");
1852 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1853 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1854 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001855 }
1856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Anders Carlssonacc79812008-11-16 07:17:21 +00001858 if (LHSTy->isRealFloatingType() &&
1859 RHSTy->isRealFloatingType()) {
1860 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Anders Carlssonacc79812008-11-16 07:17:21 +00001862 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1863 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlssonacc79812008-11-16 07:17:21 +00001865 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1866 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001867
Anders Carlssonacc79812008-11-16 07:17:21 +00001868 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001869
Anders Carlssonacc79812008-11-16 07:17:21 +00001870 switch (E->getOpcode()) {
1871 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001872 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001873 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001874 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001875 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001876 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001877 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001878 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001879 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001880 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001881 E);
John McCalle3027922010-08-25 11:45:40 +00001882 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001883 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001884 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001885 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001886 || CR == APFloat::cmpLessThan
1887 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001888 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001889 }
Mike Stump11289f42009-09-09 15:08:12 +00001890
Eli Friedmana38da572009-04-28 19:17:36 +00001891 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001892 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001893 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001894 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1895 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001896
John McCall45d55e42010-05-07 21:00:08 +00001897 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001898 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1899 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001900
Eli Friedman334046a2009-06-14 02:17:33 +00001901 // Reject any bases from the normal codepath; we special-case comparisons
1902 // to null.
1903 if (LHSValue.getLValueBase()) {
1904 if (!E->isEqualityOp())
1905 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001906 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001907 return false;
1908 bool bres;
1909 if (!EvalPointerValueAsBool(LHSValue, bres))
1910 return false;
John McCalle3027922010-08-25 11:45:40 +00001911 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001912 } else if (RHSValue.getLValueBase()) {
1913 if (!E->isEqualityOp())
1914 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001915 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001916 return false;
1917 bool bres;
1918 if (!EvalPointerValueAsBool(RHSValue, bres))
1919 return false;
John McCalle3027922010-08-25 11:45:40 +00001920 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001921 }
Eli Friedman64004332009-03-23 04:38:34 +00001922
John McCalle3027922010-08-25 11:45:40 +00001923 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001924 QualType Type = E->getLHS()->getType();
1925 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001926
Ken Dyck02990832010-01-15 12:37:54 +00001927 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001928 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001929 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001930
Ken Dyck02990832010-01-15 12:37:54 +00001931 CharUnits Diff = LHSValue.getLValueOffset() -
1932 RHSValue.getLValueOffset();
1933 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001934 }
1935 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001936 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001937 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001938 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001939 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1940 }
1941 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001942 }
1943 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001944 if (!LHSTy->isIntegralOrEnumerationType() ||
1945 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001946 // We can't continue from here for non-integral types, and they
1947 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001948 return false;
1949 }
1950
Anders Carlsson9c181652008-07-08 14:35:21 +00001951 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001952 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00001953 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001954 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001955
Richard Smith11562c52011-10-28 17:51:58 +00001956 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001957 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001958 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001959
1960 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001961 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001962 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1963 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001964 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00001965 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001966 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00001967 LHSVal.getLValueOffset() -= AdditionalOffset;
1968 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00001969 return true;
1970 }
1971
1972 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001973 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001974 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001975 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
1976 LHSVal.getInt().getZExtValue());
1977 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00001978 return true;
1979 }
1980
1981 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00001982 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001983 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001984
Richard Smith11562c52011-10-28 17:51:58 +00001985 APSInt &LHS = LHSVal.getInt();
1986 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00001987
Anders Carlsson9c181652008-07-08 14:35:21 +00001988 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001989 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001990 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00001991 case BO_Mul: return Success(LHS * RHS, E);
1992 case BO_Add: return Success(LHS + RHS, E);
1993 case BO_Sub: return Success(LHS - RHS, E);
1994 case BO_And: return Success(LHS & RHS, E);
1995 case BO_Xor: return Success(LHS ^ RHS, E);
1996 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001997 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001998 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001999 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002000 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002001 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002002 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002003 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002004 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002005 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002006 // During constant-folding, a negative shift is an opposite shift.
2007 if (RHS.isSigned() && RHS.isNegative()) {
2008 RHS = -RHS;
2009 goto shift_right;
2010 }
2011
2012 shift_left:
2013 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002014 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2015 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002016 }
John McCalle3027922010-08-25 11:45:40 +00002017 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002018 // During constant-folding, a negative shift is an opposite shift.
2019 if (RHS.isSigned() && RHS.isNegative()) {
2020 RHS = -RHS;
2021 goto shift_left;
2022 }
2023
2024 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002025 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002026 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2027 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Richard Smith11562c52011-10-28 17:51:58 +00002030 case BO_LT: return Success(LHS < RHS, E);
2031 case BO_GT: return Success(LHS > RHS, E);
2032 case BO_LE: return Success(LHS <= RHS, E);
2033 case BO_GE: return Success(LHS >= RHS, E);
2034 case BO_EQ: return Success(LHS == RHS, E);
2035 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002036 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002037}
2038
Ken Dyck160146e2010-01-27 17:10:57 +00002039CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002040 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2041 // the result is the size of the referenced type."
2042 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2043 // result shall be the alignment of the referenced type."
2044 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2045 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002046
2047 // __alignof is defined to return the preferred alignment.
2048 return Info.Ctx.toCharUnitsFromBits(
2049 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002050}
2051
Ken Dyck160146e2010-01-27 17:10:57 +00002052CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002053 E = E->IgnoreParens();
2054
2055 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002056 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002057 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002058 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2059 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002060
Chris Lattner68061312009-01-24 21:53:27 +00002061 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002062 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2063 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002064
Chris Lattner24aeeab2009-01-24 21:09:06 +00002065 return GetAlignOfType(E->getType());
2066}
2067
2068
Peter Collingbournee190dee2011-03-11 19:24:49 +00002069/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2070/// a result as the expression's type.
2071bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2072 const UnaryExprOrTypeTraitExpr *E) {
2073 switch(E->getKind()) {
2074 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002075 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002076 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002077 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002078 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002079 }
Eli Friedman64004332009-03-23 04:38:34 +00002080
Peter Collingbournee190dee2011-03-11 19:24:49 +00002081 case UETT_VecStep: {
2082 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002083
Peter Collingbournee190dee2011-03-11 19:24:49 +00002084 if (Ty->isVectorType()) {
2085 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002086
Peter Collingbournee190dee2011-03-11 19:24:49 +00002087 // The vec_step built-in functions that take a 3-component
2088 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2089 if (n == 3)
2090 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002091
Peter Collingbournee190dee2011-03-11 19:24:49 +00002092 return Success(n, E);
2093 } else
2094 return Success(1, E);
2095 }
2096
2097 case UETT_SizeOf: {
2098 QualType SrcTy = E->getTypeOfArgument();
2099 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2100 // the result is the size of the referenced type."
2101 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2102 // result shall be the alignment of the referenced type."
2103 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2104 SrcTy = Ref->getPointeeType();
2105
2106 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2107 // extension.
2108 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2109 return Success(1, E);
2110
2111 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2112 if (!SrcTy->isConstantSizeType())
2113 return false;
2114
2115 // Get information about the size.
2116 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2117 }
2118 }
2119
2120 llvm_unreachable("unknown expr/type trait");
2121 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002122}
2123
Peter Collingbournee9200682011-05-13 03:29:01 +00002124bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002125 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002126 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002127 if (n == 0)
2128 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002129 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002130 for (unsigned i = 0; i != n; ++i) {
2131 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2132 switch (ON.getKind()) {
2133 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002134 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002135 APSInt IdxResult;
2136 if (!EvaluateInteger(Idx, IdxResult, Info))
2137 return false;
2138 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2139 if (!AT)
2140 return false;
2141 CurrentType = AT->getElementType();
2142 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2143 Result += IdxResult.getSExtValue() * ElementSize;
2144 break;
2145 }
2146
2147 case OffsetOfExpr::OffsetOfNode::Field: {
2148 FieldDecl *MemberDecl = ON.getField();
2149 const RecordType *RT = CurrentType->getAs<RecordType>();
2150 if (!RT)
2151 return false;
2152 RecordDecl *RD = RT->getDecl();
2153 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002154 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002155 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002156 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002157 CurrentType = MemberDecl->getType().getNonReferenceType();
2158 break;
2159 }
2160
2161 case OffsetOfExpr::OffsetOfNode::Identifier:
2162 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002163 return false;
2164
2165 case OffsetOfExpr::OffsetOfNode::Base: {
2166 CXXBaseSpecifier *BaseSpec = ON.getBase();
2167 if (BaseSpec->isVirtual())
2168 return false;
2169
2170 // Find the layout of the class whose base we are looking into.
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);
2176
2177 // Find the base class itself.
2178 CurrentType = BaseSpec->getType();
2179 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2180 if (!BaseRT)
2181 return false;
2182
2183 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002184 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002185 break;
2186 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002187 }
2188 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002189 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002190}
2191
Chris Lattnere13042c2008-07-11 19:10:17 +00002192bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002193 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002194 // LNot's operand isn't necessarily an integer, so we handle it specially.
2195 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002196 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002197 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002198 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002199 }
2200
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002201 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002202 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002203 return false;
2204
Richard Smith11562c52011-10-28 17:51:58 +00002205 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002206 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002207 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002208 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002209
Chris Lattnerf09ad162008-07-11 22:15:16 +00002210 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002211 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002212 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2213 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002214 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002215 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002216 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2217 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002218 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002219 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002220 // The result is just the value.
2221 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002222 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002223 if (!Val.isInt()) return false;
2224 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002225 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002226 if (!Val.isInt()) return false;
2227 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002228 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002229}
Mike Stump11289f42009-09-09 15:08:12 +00002230
Chris Lattner477c4be2008-07-12 01:15:53 +00002231/// HandleCast - This is used to evaluate implicit or explicit casts where the
2232/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002233bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2234 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002235 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002236 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002237
Eli Friedmanc757de22011-03-25 00:43:55 +00002238 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002239 case CK_BaseToDerived:
2240 case CK_DerivedToBase:
2241 case CK_UncheckedDerivedToBase:
2242 case CK_Dynamic:
2243 case CK_ToUnion:
2244 case CK_ArrayToPointerDecay:
2245 case CK_FunctionToPointerDecay:
2246 case CK_NullToPointer:
2247 case CK_NullToMemberPointer:
2248 case CK_BaseToDerivedMemberPointer:
2249 case CK_DerivedToBaseMemberPointer:
2250 case CK_ConstructorConversion:
2251 case CK_IntegralToPointer:
2252 case CK_ToVoid:
2253 case CK_VectorSplat:
2254 case CK_IntegralToFloating:
2255 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002256 case CK_CPointerToObjCPointerCast:
2257 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002258 case CK_AnyPointerToBlockPointerCast:
2259 case CK_ObjCObjectLValueCast:
2260 case CK_FloatingRealToComplex:
2261 case CK_FloatingComplexToReal:
2262 case CK_FloatingComplexCast:
2263 case CK_FloatingComplexToIntegralComplex:
2264 case CK_IntegralRealToComplex:
2265 case CK_IntegralComplexCast:
2266 case CK_IntegralComplexToFloatingComplex:
2267 llvm_unreachable("invalid cast kind for integral value");
2268
Eli Friedman9faf2f92011-03-25 19:07:11 +00002269 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002270 case CK_Dependent:
2271 case CK_GetObjCProperty:
2272 case CK_LValueBitCast:
2273 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002274 case CK_ARCProduceObject:
2275 case CK_ARCConsumeObject:
2276 case CK_ARCReclaimReturnedObject:
2277 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002278 return false;
2279
2280 case CK_LValueToRValue:
2281 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002282 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002283
2284 case CK_MemberPointerToBoolean:
2285 case CK_PointerToBoolean:
2286 case CK_IntegralToBoolean:
2287 case CK_FloatingToBoolean:
2288 case CK_FloatingComplexToBoolean:
2289 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002290 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002291 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002292 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002293 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002294 }
2295
Eli Friedmanc757de22011-03-25 00:43:55 +00002296 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002297 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002298 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002299
Eli Friedman742421e2009-02-20 01:15:07 +00002300 if (!Result.isInt()) {
2301 // Only allow casts of lvalues if they are lossless.
2302 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2303 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002304
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002305 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002306 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Eli Friedmanc757de22011-03-25 00:43:55 +00002309 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002310 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002311 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002312 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002313
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002314 if (LV.getLValueBase()) {
2315 // Only allow based lvalue casts if they are lossless.
2316 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2317 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002318
John McCall45d55e42010-05-07 21:00:08 +00002319 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002320 return true;
2321 }
2322
Ken Dyck02990832010-01-15 12:37:54 +00002323 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2324 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002325 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002326 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002327
Eli Friedmanc757de22011-03-25 00:43:55 +00002328 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002329 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002330 if (!EvaluateComplex(SubExpr, C, Info))
2331 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002332 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002333 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002334
Eli Friedmanc757de22011-03-25 00:43:55 +00002335 case CK_FloatingToIntegral: {
2336 APFloat F(0.0);
2337 if (!EvaluateFloat(SubExpr, F, Info))
2338 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002339
Eli Friedmanc757de22011-03-25 00:43:55 +00002340 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2341 }
2342 }
Mike Stump11289f42009-09-09 15:08:12 +00002343
Eli Friedmanc757de22011-03-25 00:43:55 +00002344 llvm_unreachable("unknown cast resulting in integral value");
2345 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002346}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002347
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002348bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2349 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002350 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002351 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2352 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2353 return Success(LV.getComplexIntReal(), E);
2354 }
2355
2356 return Visit(E->getSubExpr());
2357}
2358
Eli Friedman4e7a2412009-02-27 04:45:43 +00002359bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002360 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002361 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002362 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2363 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2364 return Success(LV.getComplexIntImag(), E);
2365 }
2366
Richard Smith4a678122011-10-24 18:44:57 +00002367 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002368 return Success(0, E);
2369}
2370
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002371bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2372 return Success(E->getPackLength(), E);
2373}
2374
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002375bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2376 return Success(E->getValue(), E);
2377}
2378
Chris Lattner05706e882008-07-11 18:11:29 +00002379//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002380// Float Evaluation
2381//===----------------------------------------------------------------------===//
2382
2383namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002384class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002385 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002386 APFloat &Result;
2387public:
2388 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002389 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002390
Richard Smith0b0a0b62011-10-29 20:57:55 +00002391 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002392 Result = V.getFloat();
2393 return true;
2394 }
2395 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002396 return false;
2397 }
2398
Richard Smith4ce706a2011-10-11 21:43:33 +00002399 bool ValueInitialization(const Expr *E) {
2400 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2401 return true;
2402 }
2403
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002404 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002405
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002406 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002407 bool VisitBinaryOperator(const BinaryOperator *E);
2408 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002409 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002410
John McCallb1fb0d32010-05-07 22:08:54 +00002411 bool VisitUnaryReal(const UnaryOperator *E);
2412 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002413
John McCallb1fb0d32010-05-07 22:08:54 +00002414 // FIXME: Missing: array subscript of vector, member of vector,
2415 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002416};
2417} // end anonymous namespace
2418
2419static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002420 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002421 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002422}
2423
Jay Foad39c79802011-01-12 09:06:06 +00002424static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002425 QualType ResultTy,
2426 const Expr *Arg,
2427 bool SNaN,
2428 llvm::APFloat &Result) {
2429 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2430 if (!S) return false;
2431
2432 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2433
2434 llvm::APInt fill;
2435
2436 // Treat empty strings as if they were zero.
2437 if (S->getString().empty())
2438 fill = llvm::APInt(32, 0);
2439 else if (S->getString().getAsInteger(0, fill))
2440 return false;
2441
2442 if (SNaN)
2443 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2444 else
2445 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2446 return true;
2447}
2448
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002449bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002450 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002451 default:
2452 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2453
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002454 case Builtin::BI__builtin_huge_val:
2455 case Builtin::BI__builtin_huge_valf:
2456 case Builtin::BI__builtin_huge_vall:
2457 case Builtin::BI__builtin_inf:
2458 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002459 case Builtin::BI__builtin_infl: {
2460 const llvm::fltSemantics &Sem =
2461 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002462 Result = llvm::APFloat::getInf(Sem);
2463 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002464 }
Mike Stump11289f42009-09-09 15:08:12 +00002465
John McCall16291492010-02-28 13:00:19 +00002466 case Builtin::BI__builtin_nans:
2467 case Builtin::BI__builtin_nansf:
2468 case Builtin::BI__builtin_nansl:
2469 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2470 true, Result);
2471
Chris Lattner0b7282e2008-10-06 06:31:58 +00002472 case Builtin::BI__builtin_nan:
2473 case Builtin::BI__builtin_nanf:
2474 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002475 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002476 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002477 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2478 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002479
2480 case Builtin::BI__builtin_fabs:
2481 case Builtin::BI__builtin_fabsf:
2482 case Builtin::BI__builtin_fabsl:
2483 if (!EvaluateFloat(E->getArg(0), Result, Info))
2484 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002485
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002486 if (Result.isNegative())
2487 Result.changeSign();
2488 return true;
2489
Mike Stump11289f42009-09-09 15:08:12 +00002490 case Builtin::BI__builtin_copysign:
2491 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002492 case Builtin::BI__builtin_copysignl: {
2493 APFloat RHS(0.);
2494 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2495 !EvaluateFloat(E->getArg(1), RHS, Info))
2496 return false;
2497 Result.copySign(RHS);
2498 return true;
2499 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002500 }
2501}
2502
John McCallb1fb0d32010-05-07 22:08:54 +00002503bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002504 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2505 ComplexValue CV;
2506 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2507 return false;
2508 Result = CV.FloatReal;
2509 return true;
2510 }
2511
2512 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002513}
2514
2515bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002516 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2517 ComplexValue CV;
2518 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2519 return false;
2520 Result = CV.FloatImag;
2521 return true;
2522 }
2523
Richard Smith4a678122011-10-24 18:44:57 +00002524 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002525 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2526 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002527 return true;
2528}
2529
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002530bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002531 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002532 return false;
2533
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002534 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2535 return false;
2536
2537 switch (E->getOpcode()) {
2538 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002539 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002540 return true;
John McCalle3027922010-08-25 11:45:40 +00002541 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002542 Result.changeSign();
2543 return true;
2544 }
2545}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002546
Eli Friedman24c01542008-08-22 00:06:13 +00002547bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002548 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002549 VisitIgnoredValue(E->getLHS());
2550 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002551 }
2552
Richard Smith472d4952011-10-28 23:26:52 +00002553 // We can't evaluate pointer-to-member operations or assignments.
2554 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002555 return false;
2556
Eli Friedman24c01542008-08-22 00:06:13 +00002557 // FIXME: Diagnostics? I really don't understand how the warnings
2558 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002559 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002560 if (!EvaluateFloat(E->getLHS(), Result, Info))
2561 return false;
2562 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2563 return false;
2564
2565 switch (E->getOpcode()) {
2566 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002567 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002568 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2569 return true;
John McCalle3027922010-08-25 11:45:40 +00002570 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002571 Result.add(RHS, APFloat::rmNearestTiesToEven);
2572 return true;
John McCalle3027922010-08-25 11:45:40 +00002573 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002574 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2575 return true;
John McCalle3027922010-08-25 11:45:40 +00002576 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002577 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2578 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002579 }
2580}
2581
2582bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2583 Result = E->getValue();
2584 return true;
2585}
2586
Peter Collingbournee9200682011-05-13 03:29:01 +00002587bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2588 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002589
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002590 switch (E->getCastKind()) {
2591 default:
Richard Smith11562c52011-10-28 17:51:58 +00002592 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002593
2594 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002595 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002596 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002597 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002598 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002599 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002600 return true;
2601 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002602
2603 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002604 if (!Visit(SubExpr))
2605 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002606 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2607 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002608 return true;
2609 }
John McCalld7646252010-11-14 08:17:51 +00002610
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002611 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002612 ComplexValue V;
2613 if (!EvaluateComplex(SubExpr, V, Info))
2614 return false;
2615 Result = V.getComplexFloatReal();
2616 return true;
2617 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002618 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002619
2620 return false;
2621}
2622
Eli Friedman24c01542008-08-22 00:06:13 +00002623//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002624// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002625//===----------------------------------------------------------------------===//
2626
2627namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002628class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002629 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002630 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002631
Anders Carlsson537969c2008-11-16 20:27:53 +00002632public:
John McCall93d91dc2010-05-07 17:22:02 +00002633 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002634 : ExprEvaluatorBaseTy(info), Result(Result) {}
2635
Richard Smith0b0a0b62011-10-29 20:57:55 +00002636 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002637 Result.setFrom(V);
2638 return true;
2639 }
2640 bool Error(const Expr *E) {
2641 return false;
2642 }
Mike Stump11289f42009-09-09 15:08:12 +00002643
Anders Carlsson537969c2008-11-16 20:27:53 +00002644 //===--------------------------------------------------------------------===//
2645 // Visitor Methods
2646 //===--------------------------------------------------------------------===//
2647
Peter Collingbournee9200682011-05-13 03:29:01 +00002648 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002649
Peter Collingbournee9200682011-05-13 03:29:01 +00002650 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002651
John McCall93d91dc2010-05-07 17:22:02 +00002652 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002653 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002654 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002655};
2656} // end anonymous namespace
2657
John McCall93d91dc2010-05-07 17:22:02 +00002658static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2659 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002660 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002661 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002662}
2663
Peter Collingbournee9200682011-05-13 03:29:01 +00002664bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2665 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002666
2667 if (SubExpr->getType()->isRealFloatingType()) {
2668 Result.makeComplexFloat();
2669 APFloat &Imag = Result.FloatImag;
2670 if (!EvaluateFloat(SubExpr, Imag, Info))
2671 return false;
2672
2673 Result.FloatReal = APFloat(Imag.getSemantics());
2674 return true;
2675 } else {
2676 assert(SubExpr->getType()->isIntegerType() &&
2677 "Unexpected imaginary literal.");
2678
2679 Result.makeComplexInt();
2680 APSInt &Imag = Result.IntImag;
2681 if (!EvaluateInteger(SubExpr, Imag, Info))
2682 return false;
2683
2684 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2685 return true;
2686 }
2687}
2688
Peter Collingbournee9200682011-05-13 03:29:01 +00002689bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002690
John McCallfcef3cf2010-12-14 17:51:41 +00002691 switch (E->getCastKind()) {
2692 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002693 case CK_BaseToDerived:
2694 case CK_DerivedToBase:
2695 case CK_UncheckedDerivedToBase:
2696 case CK_Dynamic:
2697 case CK_ToUnion:
2698 case CK_ArrayToPointerDecay:
2699 case CK_FunctionToPointerDecay:
2700 case CK_NullToPointer:
2701 case CK_NullToMemberPointer:
2702 case CK_BaseToDerivedMemberPointer:
2703 case CK_DerivedToBaseMemberPointer:
2704 case CK_MemberPointerToBoolean:
2705 case CK_ConstructorConversion:
2706 case CK_IntegralToPointer:
2707 case CK_PointerToIntegral:
2708 case CK_PointerToBoolean:
2709 case CK_ToVoid:
2710 case CK_VectorSplat:
2711 case CK_IntegralCast:
2712 case CK_IntegralToBoolean:
2713 case CK_IntegralToFloating:
2714 case CK_FloatingToIntegral:
2715 case CK_FloatingToBoolean:
2716 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002717 case CK_CPointerToObjCPointerCast:
2718 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002719 case CK_AnyPointerToBlockPointerCast:
2720 case CK_ObjCObjectLValueCast:
2721 case CK_FloatingComplexToReal:
2722 case CK_FloatingComplexToBoolean:
2723 case CK_IntegralComplexToReal:
2724 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002725 case CK_ARCProduceObject:
2726 case CK_ARCConsumeObject:
2727 case CK_ARCReclaimReturnedObject:
2728 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002729 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002730
John McCallfcef3cf2010-12-14 17:51:41 +00002731 case CK_LValueToRValue:
2732 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002733 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002734
2735 case CK_Dependent:
2736 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002737 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002738 case CK_UserDefinedConversion:
2739 return false;
2740
2741 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002742 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002743 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002744 return false;
2745
John McCallfcef3cf2010-12-14 17:51:41 +00002746 Result.makeComplexFloat();
2747 Result.FloatImag = APFloat(Real.getSemantics());
2748 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002749 }
2750
John McCallfcef3cf2010-12-14 17:51:41 +00002751 case CK_FloatingComplexCast: {
2752 if (!Visit(E->getSubExpr()))
2753 return false;
2754
2755 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2756 QualType From
2757 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2758
2759 Result.FloatReal
2760 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2761 Result.FloatImag
2762 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2763 return true;
2764 }
2765
2766 case CK_FloatingComplexToIntegralComplex: {
2767 if (!Visit(E->getSubExpr()))
2768 return false;
2769
2770 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2771 QualType From
2772 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2773 Result.makeComplexInt();
2774 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2775 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2776 return true;
2777 }
2778
2779 case CK_IntegralRealToComplex: {
2780 APSInt &Real = Result.IntReal;
2781 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2782 return false;
2783
2784 Result.makeComplexInt();
2785 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2786 return true;
2787 }
2788
2789 case CK_IntegralComplexCast: {
2790 if (!Visit(E->getSubExpr()))
2791 return false;
2792
2793 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2794 QualType From
2795 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2796
2797 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2798 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2799 return true;
2800 }
2801
2802 case CK_IntegralComplexToFloatingComplex: {
2803 if (!Visit(E->getSubExpr()))
2804 return false;
2805
2806 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2807 QualType From
2808 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2809 Result.makeComplexFloat();
2810 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2811 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2812 return true;
2813 }
2814 }
2815
2816 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002817 return false;
2818}
2819
John McCall93d91dc2010-05-07 17:22:02 +00002820bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002821 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002822 VisitIgnoredValue(E->getLHS());
2823 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002824 }
John McCall93d91dc2010-05-07 17:22:02 +00002825 if (!Visit(E->getLHS()))
2826 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002827
John McCall93d91dc2010-05-07 17:22:02 +00002828 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002829 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002830 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002831
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002832 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2833 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002834 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002835 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002836 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002837 if (Result.isComplexFloat()) {
2838 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2839 APFloat::rmNearestTiesToEven);
2840 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2841 APFloat::rmNearestTiesToEven);
2842 } else {
2843 Result.getComplexIntReal() += RHS.getComplexIntReal();
2844 Result.getComplexIntImag() += RHS.getComplexIntImag();
2845 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002846 break;
John McCalle3027922010-08-25 11:45:40 +00002847 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002848 if (Result.isComplexFloat()) {
2849 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2850 APFloat::rmNearestTiesToEven);
2851 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2852 APFloat::rmNearestTiesToEven);
2853 } else {
2854 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2855 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2856 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002857 break;
John McCalle3027922010-08-25 11:45:40 +00002858 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002859 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002860 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002861 APFloat &LHS_r = LHS.getComplexFloatReal();
2862 APFloat &LHS_i = LHS.getComplexFloatImag();
2863 APFloat &RHS_r = RHS.getComplexFloatReal();
2864 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002865
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002866 APFloat Tmp = LHS_r;
2867 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2868 Result.getComplexFloatReal() = Tmp;
2869 Tmp = LHS_i;
2870 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2871 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2872
2873 Tmp = LHS_r;
2874 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2875 Result.getComplexFloatImag() = Tmp;
2876 Tmp = LHS_i;
2877 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2878 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2879 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002880 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002881 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002882 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2883 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002884 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002885 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2886 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2887 }
2888 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002889 case BO_Div:
2890 if (Result.isComplexFloat()) {
2891 ComplexValue LHS = Result;
2892 APFloat &LHS_r = LHS.getComplexFloatReal();
2893 APFloat &LHS_i = LHS.getComplexFloatImag();
2894 APFloat &RHS_r = RHS.getComplexFloatReal();
2895 APFloat &RHS_i = RHS.getComplexFloatImag();
2896 APFloat &Res_r = Result.getComplexFloatReal();
2897 APFloat &Res_i = Result.getComplexFloatImag();
2898
2899 APFloat Den = RHS_r;
2900 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2901 APFloat Tmp = RHS_i;
2902 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2903 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2904
2905 Res_r = LHS_r;
2906 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2907 Tmp = LHS_i;
2908 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2909 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2910 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2911
2912 Res_i = LHS_i;
2913 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2914 Tmp = LHS_r;
2915 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2916 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2917 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2918 } else {
2919 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2920 // FIXME: what about diagnostics?
2921 return false;
2922 }
2923 ComplexValue LHS = Result;
2924 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2925 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2926 Result.getComplexIntReal() =
2927 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2928 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2929 Result.getComplexIntImag() =
2930 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2931 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2932 }
2933 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002934 }
2935
John McCall93d91dc2010-05-07 17:22:02 +00002936 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002937}
2938
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002939bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2940 // Get the operand value into 'Result'.
2941 if (!Visit(E->getSubExpr()))
2942 return false;
2943
2944 switch (E->getOpcode()) {
2945 default:
2946 // FIXME: what about diagnostics?
2947 return false;
2948 case UO_Extension:
2949 return true;
2950 case UO_Plus:
2951 // The result is always just the subexpr.
2952 return true;
2953 case UO_Minus:
2954 if (Result.isComplexFloat()) {
2955 Result.getComplexFloatReal().changeSign();
2956 Result.getComplexFloatImag().changeSign();
2957 }
2958 else {
2959 Result.getComplexIntReal() = -Result.getComplexIntReal();
2960 Result.getComplexIntImag() = -Result.getComplexIntImag();
2961 }
2962 return true;
2963 case UO_Not:
2964 if (Result.isComplexFloat())
2965 Result.getComplexFloatImag().changeSign();
2966 else
2967 Result.getComplexIntImag() = -Result.getComplexIntImag();
2968 return true;
2969 }
2970}
2971
Anders Carlsson537969c2008-11-16 20:27:53 +00002972//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00002973// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00002974//===----------------------------------------------------------------------===//
2975
Richard Smith0b0a0b62011-10-29 20:57:55 +00002976static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002977 // In C, function designators are not lvalues, but we evaluate them as if they
2978 // are.
2979 if (E->isGLValue() || E->getType()->isFunctionType()) {
2980 LValue LV;
2981 if (!EvaluateLValue(E, LV, Info))
2982 return false;
2983 LV.moveInto(Result);
2984 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002985 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002986 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002987 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002988 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002989 return false;
John McCall45d55e42010-05-07 21:00:08 +00002990 } else if (E->getType()->hasPointerRepresentation()) {
2991 LValue LV;
2992 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002993 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002994 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002995 } else if (E->getType()->isRealFloatingType()) {
2996 llvm::APFloat F(0.0);
2997 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002998 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002999 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003000 } else if (E->getType()->isAnyComplexType()) {
3001 ComplexValue C;
3002 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003003 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003004 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003005 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003006 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003007
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003008 return true;
3009}
3010
Richard Smith11562c52011-10-28 17:51:58 +00003011
Richard Smith7b553f12011-10-29 00:50:52 +00003012/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003013/// any crazy technique (that has nothing to do with language standards) that
3014/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003015/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3016/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003017bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003018 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003019
Richard Smith0b0a0b62011-10-29 20:57:55 +00003020 CCValue Value;
3021 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003022 return false;
3023
3024 if (isGLValue()) {
3025 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003026 LV.setFrom(Value);
3027 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3028 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003029 }
3030
Richard Smith0b0a0b62011-10-29 20:57:55 +00003031 // Check this core constant expression is a constant expression, and if so,
3032 // slice it down to one.
3033 if (!CheckConstantExpression(Value))
3034 return false;
3035 Result.Val = Value;
3036 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003037}
3038
Jay Foad39c79802011-01-12 09:06:06 +00003039bool Expr::EvaluateAsBooleanCondition(bool &Result,
3040 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003041 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003042 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003043 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3044 Result);
John McCall1be1c632010-01-05 23:42:56 +00003045}
3046
Richard Smithcaf33902011-10-10 18:28:20 +00003047bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003048 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003049 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003050 !ExprResult.Val.isInt()) {
3051 return false;
3052 }
3053 Result = ExprResult.Val.getInt();
3054 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003055}
3056
Jay Foad39c79802011-01-12 09:06:06 +00003057bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003058 EvalInfo Info(Ctx, Result);
3059
John McCall45d55e42010-05-07 21:00:08 +00003060 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003061 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003062 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003063 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003064 return true;
3065 }
3066 return false;
3067}
3068
Jay Foad39c79802011-01-12 09:06:06 +00003069bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3070 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003071 EvalInfo Info(Ctx, Result);
3072
3073 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003074 // Don't allow references to out-of-scope function parameters to escape.
3075 if (EvaluateLValue(this, LV, Info) &&
3076 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3077 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003078 return true;
3079 }
3080 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003081}
3082
Richard Smith7b553f12011-10-29 00:50:52 +00003083/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3084/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003085bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003086 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003087 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003088}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003089
Jay Foad39c79802011-01-12 09:06:06 +00003090bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003091 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003092}
3093
Richard Smithcaf33902011-10-10 18:28:20 +00003094APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003095 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003096 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003097 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003098 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003099 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003100
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003101 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003102}
John McCall864e3962010-05-07 05:32:02 +00003103
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003104 bool Expr::EvalResult::isGlobalLValue() const {
3105 assert(Val.isLValue());
3106 return IsGlobalLValue(Val.getLValueBase());
3107 }
3108
3109
John McCall864e3962010-05-07 05:32:02 +00003110/// isIntegerConstantExpr - this recursive routine will test if an expression is
3111/// an integer constant expression.
3112
3113/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3114/// comma, etc
3115///
3116/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3117/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3118/// cast+dereference.
3119
3120// CheckICE - This function does the fundamental ICE checking: the returned
3121// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3122// Note that to reduce code duplication, this helper does no evaluation
3123// itself; the caller checks whether the expression is evaluatable, and
3124// in the rare cases where CheckICE actually cares about the evaluated
3125// value, it calls into Evalute.
3126//
3127// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003128// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003129// 1: This expression is not an ICE, but if it isn't evaluated, it's
3130// a legal subexpression for an ICE. This return value is used to handle
3131// the comma operator in C99 mode.
3132// 2: This expression is not an ICE, and is not a legal subexpression for one.
3133
Dan Gohman28ade552010-07-26 21:25:24 +00003134namespace {
3135
John McCall864e3962010-05-07 05:32:02 +00003136struct ICEDiag {
3137 unsigned Val;
3138 SourceLocation Loc;
3139
3140 public:
3141 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3142 ICEDiag() : Val(0) {}
3143};
3144
Dan Gohman28ade552010-07-26 21:25:24 +00003145}
3146
3147static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003148
3149static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3150 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003151 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003152 !EVResult.Val.isInt()) {
3153 return ICEDiag(2, E->getLocStart());
3154 }
3155 return NoDiag();
3156}
3157
3158static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3159 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003160 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003161 return ICEDiag(2, E->getLocStart());
3162 }
3163
3164 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003165#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003166#define STMT(Node, Base) case Expr::Node##Class:
3167#define EXPR(Node, Base)
3168#include "clang/AST/StmtNodes.inc"
3169 case Expr::PredefinedExprClass:
3170 case Expr::FloatingLiteralClass:
3171 case Expr::ImaginaryLiteralClass:
3172 case Expr::StringLiteralClass:
3173 case Expr::ArraySubscriptExprClass:
3174 case Expr::MemberExprClass:
3175 case Expr::CompoundAssignOperatorClass:
3176 case Expr::CompoundLiteralExprClass:
3177 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003178 case Expr::DesignatedInitExprClass:
3179 case Expr::ImplicitValueInitExprClass:
3180 case Expr::ParenListExprClass:
3181 case Expr::VAArgExprClass:
3182 case Expr::AddrLabelExprClass:
3183 case Expr::StmtExprClass:
3184 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003185 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003186 case Expr::CXXDynamicCastExprClass:
3187 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003188 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003189 case Expr::CXXNullPtrLiteralExprClass:
3190 case Expr::CXXThisExprClass:
3191 case Expr::CXXThrowExprClass:
3192 case Expr::CXXNewExprClass:
3193 case Expr::CXXDeleteExprClass:
3194 case Expr::CXXPseudoDestructorExprClass:
3195 case Expr::UnresolvedLookupExprClass:
3196 case Expr::DependentScopeDeclRefExprClass:
3197 case Expr::CXXConstructExprClass:
3198 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003199 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003200 case Expr::CXXTemporaryObjectExprClass:
3201 case Expr::CXXUnresolvedConstructExprClass:
3202 case Expr::CXXDependentScopeMemberExprClass:
3203 case Expr::UnresolvedMemberExprClass:
3204 case Expr::ObjCStringLiteralClass:
3205 case Expr::ObjCEncodeExprClass:
3206 case Expr::ObjCMessageExprClass:
3207 case Expr::ObjCSelectorExprClass:
3208 case Expr::ObjCProtocolExprClass:
3209 case Expr::ObjCIvarRefExprClass:
3210 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003211 case Expr::ObjCIsaExprClass:
3212 case Expr::ShuffleVectorExprClass:
3213 case Expr::BlockExprClass:
3214 case Expr::BlockDeclRefExprClass:
3215 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003216 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003217 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003218 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003219 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003220 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003221 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003222 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003223 return ICEDiag(2, E->getLocStart());
3224
Sebastian Redl12757ab2011-09-24 17:48:14 +00003225 case Expr::InitListExprClass:
3226 if (Ctx.getLangOptions().CPlusPlus0x) {
3227 const InitListExpr *ILE = cast<InitListExpr>(E);
3228 if (ILE->getNumInits() == 0)
3229 return NoDiag();
3230 if (ILE->getNumInits() == 1)
3231 return CheckICE(ILE->getInit(0), Ctx);
3232 // Fall through for more than 1 expression.
3233 }
3234 return ICEDiag(2, E->getLocStart());
3235
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003236 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003237 case Expr::GNUNullExprClass:
3238 // GCC considers the GNU __null value to be an integral constant expression.
3239 return NoDiag();
3240
John McCall7c454bb2011-07-15 05:09:51 +00003241 case Expr::SubstNonTypeTemplateParmExprClass:
3242 return
3243 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3244
John McCall864e3962010-05-07 05:32:02 +00003245 case Expr::ParenExprClass:
3246 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003247 case Expr::GenericSelectionExprClass:
3248 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003249 case Expr::IntegerLiteralClass:
3250 case Expr::CharacterLiteralClass:
3251 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003252 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003253 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003254 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003255 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003256 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003257 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003258 return NoDiag();
3259 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003260 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003261 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3262 // constant expressions, but they can never be ICEs because an ICE cannot
3263 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003264 const CallExpr *CE = cast<CallExpr>(E);
3265 if (CE->isBuiltinCall(Ctx))
3266 return CheckEvalInICE(E, Ctx);
3267 return ICEDiag(2, E->getLocStart());
3268 }
3269 case Expr::DeclRefExprClass:
3270 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3271 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003272 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003273 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3274
3275 // Parameter variables are never constants. Without this check,
3276 // getAnyInitializer() can find a default argument, which leads
3277 // to chaos.
3278 if (isa<ParmVarDecl>(D))
3279 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3280
3281 // C++ 7.1.5.1p2
3282 // A variable of non-volatile const-qualified integral or enumeration
3283 // type initialized by an ICE can be used in ICEs.
3284 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003285 // Look for a declaration of this variable that has an initializer.
3286 const VarDecl *ID = 0;
3287 const Expr *Init = Dcl->getAnyInitializer(ID);
3288 if (Init) {
3289 if (ID->isInitKnownICE()) {
3290 // We have already checked whether this subexpression is an
3291 // integral constant expression.
3292 if (ID->isInitICE())
3293 return NoDiag();
3294 else
3295 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3296 }
3297
3298 // It's an ICE whether or not the definition we found is
3299 // out-of-line. See DR 721 and the discussion in Clang PR
3300 // 6206 for details.
3301
3302 if (Dcl->isCheckingICE()) {
3303 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3304 }
3305
3306 Dcl->setCheckingICE();
3307 ICEDiag Result = CheckICE(Init, Ctx);
3308 // Cache the result of the ICE test.
3309 Dcl->setInitKnownICE(Result.Val == 0);
3310 return Result;
3311 }
3312 }
3313 }
3314 return ICEDiag(2, E->getLocStart());
3315 case Expr::UnaryOperatorClass: {
3316 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3317 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003318 case UO_PostInc:
3319 case UO_PostDec:
3320 case UO_PreInc:
3321 case UO_PreDec:
3322 case UO_AddrOf:
3323 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003324 // C99 6.6/3 allows increment and decrement within unevaluated
3325 // subexpressions of constant expressions, but they can never be ICEs
3326 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003327 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003328 case UO_Extension:
3329 case UO_LNot:
3330 case UO_Plus:
3331 case UO_Minus:
3332 case UO_Not:
3333 case UO_Real:
3334 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003335 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003336 }
3337
3338 // OffsetOf falls through here.
3339 }
3340 case Expr::OffsetOfExprClass: {
3341 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003342 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003343 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003344 // compliance: we should warn earlier for offsetof expressions with
3345 // array subscripts that aren't ICEs, and if the array subscripts
3346 // are ICEs, the value of the offsetof must be an integer constant.
3347 return CheckEvalInICE(E, Ctx);
3348 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003349 case Expr::UnaryExprOrTypeTraitExprClass: {
3350 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3351 if ((Exp->getKind() == UETT_SizeOf) &&
3352 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003353 return ICEDiag(2, E->getLocStart());
3354 return NoDiag();
3355 }
3356 case Expr::BinaryOperatorClass: {
3357 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3358 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003359 case BO_PtrMemD:
3360 case BO_PtrMemI:
3361 case BO_Assign:
3362 case BO_MulAssign:
3363 case BO_DivAssign:
3364 case BO_RemAssign:
3365 case BO_AddAssign:
3366 case BO_SubAssign:
3367 case BO_ShlAssign:
3368 case BO_ShrAssign:
3369 case BO_AndAssign:
3370 case BO_XorAssign:
3371 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003372 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3373 // constant expressions, but they can never be ICEs because an ICE cannot
3374 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003375 return ICEDiag(2, E->getLocStart());
3376
John McCalle3027922010-08-25 11:45:40 +00003377 case BO_Mul:
3378 case BO_Div:
3379 case BO_Rem:
3380 case BO_Add:
3381 case BO_Sub:
3382 case BO_Shl:
3383 case BO_Shr:
3384 case BO_LT:
3385 case BO_GT:
3386 case BO_LE:
3387 case BO_GE:
3388 case BO_EQ:
3389 case BO_NE:
3390 case BO_And:
3391 case BO_Xor:
3392 case BO_Or:
3393 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003394 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3395 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003396 if (Exp->getOpcode() == BO_Div ||
3397 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003398 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003399 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003400 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003401 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003402 if (REval == 0)
3403 return ICEDiag(1, E->getLocStart());
3404 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003405 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003406 if (LEval.isMinSignedValue())
3407 return ICEDiag(1, E->getLocStart());
3408 }
3409 }
3410 }
John McCalle3027922010-08-25 11:45:40 +00003411 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003412 if (Ctx.getLangOptions().C99) {
3413 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3414 // if it isn't evaluated.
3415 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3416 return ICEDiag(1, E->getLocStart());
3417 } else {
3418 // In both C89 and C++, commas in ICEs are illegal.
3419 return ICEDiag(2, E->getLocStart());
3420 }
3421 }
3422 if (LHSResult.Val >= RHSResult.Val)
3423 return LHSResult;
3424 return RHSResult;
3425 }
John McCalle3027922010-08-25 11:45:40 +00003426 case BO_LAnd:
3427 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003428 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003429
3430 // C++0x [expr.const]p2:
3431 // [...] subexpressions of logical AND (5.14), logical OR
3432 // (5.15), and condi- tional (5.16) operations that are not
3433 // evaluated are not considered.
3434 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3435 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003436 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003437 return LHSResult;
3438
3439 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003440 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003441 return LHSResult;
3442 }
3443
John McCall864e3962010-05-07 05:32:02 +00003444 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3445 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3446 // Rare case where the RHS has a comma "side-effect"; we need
3447 // to actually check the condition to see whether the side
3448 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003449 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003450 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003451 return RHSResult;
3452 return NoDiag();
3453 }
3454
3455 if (LHSResult.Val >= RHSResult.Val)
3456 return LHSResult;
3457 return RHSResult;
3458 }
3459 }
3460 }
3461 case Expr::ImplicitCastExprClass:
3462 case Expr::CStyleCastExprClass:
3463 case Expr::CXXFunctionalCastExprClass:
3464 case Expr::CXXStaticCastExprClass:
3465 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003466 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003467 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003468 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003469 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003470 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3471 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003472 switch (cast<CastExpr>(E)->getCastKind()) {
3473 case CK_LValueToRValue:
3474 case CK_NoOp:
3475 case CK_IntegralToBoolean:
3476 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003477 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003478 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003479 return ICEDiag(2, E->getLocStart());
3480 }
John McCall864e3962010-05-07 05:32:02 +00003481 }
John McCallc07a0c72011-02-17 10:25:35 +00003482 case Expr::BinaryConditionalOperatorClass: {
3483 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3484 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3485 if (CommonResult.Val == 2) return CommonResult;
3486 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3487 if (FalseResult.Val == 2) return FalseResult;
3488 if (CommonResult.Val == 1) return CommonResult;
3489 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003490 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003491 return FalseResult;
3492 }
John McCall864e3962010-05-07 05:32:02 +00003493 case Expr::ConditionalOperatorClass: {
3494 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3495 // If the condition (ignoring parens) is a __builtin_constant_p call,
3496 // then only the true side is actually considered in an integer constant
3497 // expression, and it is fully evaluated. This is an important GNU
3498 // extension. See GCC PR38377 for discussion.
3499 if (const CallExpr *CallCE
3500 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3501 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3502 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003503 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003504 !EVResult.Val.isInt()) {
3505 return ICEDiag(2, E->getLocStart());
3506 }
3507 return NoDiag();
3508 }
3509 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003510 if (CondResult.Val == 2)
3511 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003512
3513 // C++0x [expr.const]p2:
3514 // subexpressions of [...] conditional (5.16) operations that
3515 // are not evaluated are not considered
3516 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003517 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003518 : false;
3519 ICEDiag TrueResult = NoDiag();
3520 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3521 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3522 ICEDiag FalseResult = NoDiag();
3523 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3524 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3525
John McCall864e3962010-05-07 05:32:02 +00003526 if (TrueResult.Val == 2)
3527 return TrueResult;
3528 if (FalseResult.Val == 2)
3529 return FalseResult;
3530 if (CondResult.Val == 1)
3531 return CondResult;
3532 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3533 return NoDiag();
3534 // Rare case where the diagnostics depend on which side is evaluated
3535 // Note that if we get here, CondResult is 0, and at least one of
3536 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003537 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003538 return FalseResult;
3539 }
3540 return TrueResult;
3541 }
3542 case Expr::CXXDefaultArgExprClass:
3543 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3544 case Expr::ChooseExprClass: {
3545 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3546 }
3547 }
3548
3549 // Silence a GCC warning
3550 return ICEDiag(2, E->getLocStart());
3551}
3552
3553bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3554 SourceLocation *Loc, bool isEvaluated) const {
3555 ICEDiag d = CheckICE(this, Ctx);
3556 if (d.Val != 0) {
3557 if (Loc) *Loc = d.Loc;
3558 return false;
3559 }
Richard Smith11562c52011-10-28 17:51:58 +00003560 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003561 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003562 return true;
3563}