blob: f33827ff7c4eec8b1a148cfd0811c7b0ed06cd92 [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 //
Richard Smith254a73d2011-10-28 22:34:42 +0000460 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
461 // interpretation of C++11 suggests that volatile parameters are OK if
462 // they're never read (there's no prohibition against constructing volatile
463 // objects in constant expressions), but lvalue-to-rvalue conversions on
464 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000465 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000466 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith35a1f852011-10-29 21:53:17 +0000467 !Type->isLiteralType() ||
Richard Smith0b0a0b62011-10-29 20:57:55 +0000468 !EvaluateVarDeclInit(Info, VD, LVal.CallIndex, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000469 return false;
470
Richard Smith0b0a0b62011-10-29 20:57:55 +0000471 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000472 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000473
474 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
475 // conversion. This happens when the declaration and the lvalue should be
476 // considered synonymous, for instance when initializing an array of char
477 // from a string literal. Continue as if the initializer lvalue was the
478 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000479 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000480 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000481 Base = RVal.getLValueBase();
Richard Smith11562c52011-10-28 17:51:58 +0000482 }
483
484 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
485 // here.
486
487 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
488 // initializer until now for such expressions. Such an expression can't be
489 // an ICE in C, so this only matters for fold.
490 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
491 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
492 return Evaluate(RVal, Info, CLE->getInitializer());
493 }
494
495 return false;
496}
497
Mike Stump876387b2009-10-27 22:09:17 +0000498namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000499enum EvalStmtResult {
500 /// Evaluation failed.
501 ESR_Failed,
502 /// Hit a 'return' statement.
503 ESR_Returned,
504 /// Evaluation succeeded.
505 ESR_Succeeded
506};
507}
508
509// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000510static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000511 const Stmt *S) {
512 switch (S->getStmtClass()) {
513 default:
514 return ESR_Failed;
515
516 case Stmt::NullStmtClass:
517 case Stmt::DeclStmtClass:
518 return ESR_Succeeded;
519
520 case Stmt::ReturnStmtClass:
521 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
522 return ESR_Returned;
523 return ESR_Failed;
524
525 case Stmt::CompoundStmtClass: {
526 const CompoundStmt *CS = cast<CompoundStmt>(S);
527 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
528 BE = CS->body_end(); BI != BE; ++BI) {
529 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
530 if (ESR != ESR_Succeeded)
531 return ESR;
532 }
533 return ESR_Succeeded;
534 }
535 }
536}
537
538/// Evaluate a function call.
539static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000540 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000541 // FIXME: Implement a proper call limit, along with a command-line flag.
542 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
543 return false;
544
Richard Smith0b0a0b62011-10-29 20:57:55 +0000545 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000546 // FIXME: Deal with default arguments and 'this'.
547 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
548 I != E; ++I)
549 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
550 return false;
551
552 CallStackFrame Frame(Info, ArgValues.data());
553 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
554}
555
556namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000557class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000558 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000559 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000560public:
561
Richard Smith725810a2011-10-16 21:26:27 +0000562 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000563
564 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000565 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000566 return true;
567 }
568
Peter Collingbournee9200682011-05-13 03:29:01 +0000569 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000571 return Visit(E->getResultExpr());
572 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000574 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000575 return true;
576 return false;
577 }
John McCall31168b02011-06-15 23:02:42 +0000578 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000579 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000580 return true;
581 return false;
582 }
583 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000584 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000585 return true;
586 return false;
587 }
588
Mike Stump876387b2009-10-27 22:09:17 +0000589 // We don't want to evaluate BlockExprs multiple times, as they generate
590 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000591 bool VisitBlockExpr(const BlockExpr *E) { return true; }
592 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
593 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000594 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000595 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
596 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
597 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
598 bool VisitStringLiteral(const StringLiteral *E) { return false; }
599 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
600 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000601 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000602 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000603 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000604 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000605 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
607 bool VisitBinAssign(const BinaryOperator *E) { return true; }
608 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
609 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000610 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000611 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
612 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
613 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
614 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
615 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000616 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000617 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000618 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000619 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000620 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000621
622 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000623 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000624 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
625 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000626 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000627 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000628 return false;
629 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000630
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000632};
633
John McCallc07a0c72011-02-17 10:25:35 +0000634class OpaqueValueEvaluation {
635 EvalInfo &info;
636 OpaqueValueExpr *opaqueValue;
637
638public:
639 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
640 Expr *value)
641 : info(info), opaqueValue(opaqueValue) {
642
643 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000644 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000645 this->opaqueValue = 0;
646 return;
647 }
John McCallc07a0c72011-02-17 10:25:35 +0000648 }
649
650 bool hasError() const { return opaqueValue == 0; }
651
652 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000653 // FIXME: This will not work for recursive constexpr functions using opaque
654 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000655 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
656 }
657};
658
Mike Stump876387b2009-10-27 22:09:17 +0000659} // end anonymous namespace
660
Eli Friedman9a156e52008-11-12 09:44:48 +0000661//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000662// Generic Evaluation
663//===----------------------------------------------------------------------===//
664namespace {
665
666template <class Derived, typename RetTy=void>
667class ExprEvaluatorBase
668 : public ConstStmtVisitor<Derived, RetTy> {
669private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000670 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000671 return static_cast<Derived*>(this)->Success(V, E);
672 }
673 RetTy DerivedError(const Expr *E) {
674 return static_cast<Derived*>(this)->Error(E);
675 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000676 RetTy DerivedValueInitialization(const Expr *E) {
677 return static_cast<Derived*>(this)->ValueInitialization(E);
678 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000679
680protected:
681 EvalInfo &Info;
682 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
683 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
684
Richard Smith4ce706a2011-10-11 21:43:33 +0000685 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
686
Peter Collingbournee9200682011-05-13 03:29:01 +0000687public:
688 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
689
690 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000691 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000692 }
693 RetTy VisitExpr(const Expr *E) {
694 return DerivedError(E);
695 }
696
697 RetTy VisitParenExpr(const ParenExpr *E)
698 { return StmtVisitorTy::Visit(E->getSubExpr()); }
699 RetTy VisitUnaryExtension(const UnaryOperator *E)
700 { return StmtVisitorTy::Visit(E->getSubExpr()); }
701 RetTy VisitUnaryPlus(const UnaryOperator *E)
702 { return StmtVisitorTy::Visit(E->getSubExpr()); }
703 RetTy VisitChooseExpr(const ChooseExpr *E)
704 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
705 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
706 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000707 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
708 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000709
710 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
711 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
712 if (opaque.hasError())
713 return DerivedError(E);
714
715 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000716 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000717 return DerivedError(E);
718
719 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
720 }
721
722 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
723 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000724 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000725 return DerivedError(E);
726
Richard Smith11562c52011-10-28 17:51:58 +0000727 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000728 return StmtVisitorTy::Visit(EvalExpr);
729 }
730
731 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000732 const CCValue *Value = Info.getOpaqueValue(E);
733 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000734 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
735 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000736 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000737 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000738
Richard Smith254a73d2011-10-28 22:34:42 +0000739 RetTy VisitCallExpr(const CallExpr *E) {
740 const Expr *Callee = E->getCallee();
741 QualType CalleeType = Callee->getType();
742
743 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
744 // non-static member function.
745 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
746 return DerivedError(E);
747
748 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
749 return DerivedError(E);
750
Richard Smith0b0a0b62011-10-29 20:57:55 +0000751 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000752 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
753 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
754 return DerivedError(Callee);
755
756 const FunctionDecl *FD = 0;
757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
758 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
759 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
760 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
761 if (!FD)
762 return DerivedError(Callee);
763
764 // Don't call function pointers which have been cast to some other type.
765 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
766 return DerivedError(E);
767
768 const FunctionDecl *Definition;
769 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000770 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000771 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
772
773 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
774 HandleFunctionCall(Args, Body, Info, Result))
775 return DerivedSuccess(Result, E);
776
777 return DerivedError(E);
778 }
779
Richard Smith11562c52011-10-28 17:51:58 +0000780 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
781 return StmtVisitorTy::Visit(E->getInitializer());
782 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000783 RetTy VisitInitListExpr(const InitListExpr *E) {
784 if (Info.getLangOpts().CPlusPlus0x) {
785 if (E->getNumInits() == 0)
786 return DerivedValueInitialization(E);
787 if (E->getNumInits() == 1)
788 return StmtVisitorTy::Visit(E->getInit(0));
789 }
790 return DerivedError(E);
791 }
792 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
793 return DerivedValueInitialization(E);
794 }
795 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
796 return DerivedValueInitialization(E);
797 }
798
Richard Smith11562c52011-10-28 17:51:58 +0000799 RetTy VisitCastExpr(const CastExpr *E) {
800 switch (E->getCastKind()) {
801 default:
802 break;
803
804 case CK_NoOp:
805 return StmtVisitorTy::Visit(E->getSubExpr());
806
807 case CK_LValueToRValue: {
808 LValue LVal;
809 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000810 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000811 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
812 return DerivedSuccess(RVal, E);
813 }
814 break;
815 }
816 }
817
818 return DerivedError(E);
819 }
820
Richard Smith4a678122011-10-24 18:44:57 +0000821 /// Visit a value which is evaluated, but whose value is ignored.
822 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000823 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000824 if (!Evaluate(Scratch, Info, E))
825 Info.EvalStatus.HasSideEffects = true;
826 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000827};
828
829}
830
831//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000832// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000833//
834// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
835// function designators (in C), decl references to void objects (in C), and
836// temporaries (if building with -Wno-address-of-temporary).
837//
838// LValue evaluation produces values comprising a base expression of one of the
839// following types:
840// * DeclRefExpr
841// * MemberExpr for a static member
842// * CompoundLiteralExpr in C
843// * StringLiteral
844// * PredefinedExpr
845// * ObjCEncodeExpr
846// * AddrLabelExpr
847// * BlockExpr
848// * CallExpr for a MakeStringConstant builtin
849// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000850//===----------------------------------------------------------------------===//
851namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000852class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000853 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000854 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000855 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000856
Peter Collingbournee9200682011-05-13 03:29:01 +0000857 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000858 Result.Base = E;
859 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +0000860 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +0000861 return true;
862 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000863public:
Mike Stump11289f42009-09-09 15:08:12 +0000864
John McCall45d55e42010-05-07 21:00:08 +0000865 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000866 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000867
Richard Smith0b0a0b62011-10-29 20:57:55 +0000868 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000869 Result.setFrom(V);
870 return true;
871 }
872 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000873 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000874 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000875
Richard Smith11562c52011-10-28 17:51:58 +0000876 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
877
Peter Collingbournee9200682011-05-13 03:29:01 +0000878 bool VisitDeclRefExpr(const DeclRefExpr *E);
879 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
880 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
881 bool VisitMemberExpr(const MemberExpr *E);
882 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
883 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
884 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
885 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000886
Peter Collingbournee9200682011-05-13 03:29:01 +0000887 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000888 switch (E->getCastKind()) {
889 default:
Richard Smith11562c52011-10-28 17:51:58 +0000890 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000891
Eli Friedmance3e02a2011-10-11 00:13:24 +0000892 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000893 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000894
Richard Smith11562c52011-10-28 17:51:58 +0000895 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
896 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000897 }
898 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000899
Eli Friedman449fe542009-03-23 04:56:01 +0000900 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000901
Eli Friedman9a156e52008-11-12 09:44:48 +0000902};
903} // end anonymous namespace
904
Richard Smith11562c52011-10-28 17:51:58 +0000905/// Evaluate an expression as an lvalue. This can be legitimately called on
906/// expressions which are not glvalues, in a few cases:
907/// * function designators in C,
908/// * "extern void" objects,
909/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000910static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000911 assert((E->isGLValue() || E->getType()->isFunctionType() ||
912 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
913 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000914 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000915}
916
Peter Collingbournee9200682011-05-13 03:29:01 +0000917bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000918 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000919 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000920 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
921 return VisitVarDecl(E, VD);
922 return Error(E);
923}
Richard Smith733237d2011-10-24 23:14:33 +0000924
Richard Smith11562c52011-10-28 17:51:58 +0000925bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
926 if (!VD->getType()->isReferenceType())
927 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000928
Richard Smith0b0a0b62011-10-29 20:57:55 +0000929 CCValue V;
930 if (EvaluateVarDeclInit(Info, VD, Info.getCurrentCallIndex(), V))
931 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000932
933 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000934}
935
Peter Collingbournee9200682011-05-13 03:29:01 +0000936bool
937LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000938 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
939 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
940 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000941 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000942}
943
Peter Collingbournee9200682011-05-13 03:29:01 +0000944bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000945 // Handle static data members.
946 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
947 VisitIgnoredValue(E->getBase());
948 return VisitVarDecl(E, VD);
949 }
950
Richard Smith254a73d2011-10-28 22:34:42 +0000951 // Handle static member functions.
952 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
953 if (MD->isStatic()) {
954 VisitIgnoredValue(E->getBase());
955 return Success(E);
956 }
957 }
958
Eli Friedman9a156e52008-11-12 09:44:48 +0000959 QualType Ty;
960 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000961 if (!EvaluatePointer(E->getBase(), Result, Info))
962 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000963 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000964 } else {
John McCall45d55e42010-05-07 21:00:08 +0000965 if (!Visit(E->getBase()))
966 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000967 Ty = E->getBase()->getType();
968 }
969
Peter Collingbournee9200682011-05-13 03:29:01 +0000970 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000971 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000972
Peter Collingbournee9200682011-05-13 03:29:01 +0000973 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000974 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000975 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000976
977 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000978 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000979
Eli Friedmana3c122d2011-07-07 01:54:01 +0000980 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000981 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000982 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000983}
984
Peter Collingbournee9200682011-05-13 03:29:01 +0000985bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000986 // FIXME: Deal with vectors as array subscript bases.
987 if (E->getBase()->getType()->isVectorType())
988 return false;
989
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000990 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000991 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000992
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000993 APSInt Index;
994 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000995 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000996
Ken Dyck40775002010-01-11 17:06:35 +0000997 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000998 Result.Offset += Index.getSExtValue() * ElementSize;
999 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001000}
Eli Friedman9a156e52008-11-12 09:44:48 +00001001
Peter Collingbournee9200682011-05-13 03:29:01 +00001002bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001003 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001004}
1005
Eli Friedman9a156e52008-11-12 09:44:48 +00001006//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001007// Pointer Evaluation
1008//===----------------------------------------------------------------------===//
1009
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001010namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001011class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001012 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001013 LValue &Result;
1014
Peter Collingbournee9200682011-05-13 03:29:01 +00001015 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001016 Result.Base = E;
1017 Result.Offset = CharUnits::Zero();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001018 Result.CallIndex = Info.getCurrentCallIndex();
John McCall45d55e42010-05-07 21:00:08 +00001019 return true;
1020 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001021public:
Mike Stump11289f42009-09-09 15:08:12 +00001022
John McCall45d55e42010-05-07 21:00:08 +00001023 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001024 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001025
Richard Smith0b0a0b62011-10-29 20:57:55 +00001026 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001027 Result.setFrom(V);
1028 return true;
1029 }
1030 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001031 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001032 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001033 bool ValueInitialization(const Expr *E) {
1034 return Success((Expr*)0);
1035 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001036
John McCall45d55e42010-05-07 21:00:08 +00001037 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001038 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001039 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001040 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001041 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001042 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001043 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001044 bool VisitCallExpr(const CallExpr *E);
1045 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001046 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001047 return Success(E);
1048 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001049 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001050 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001051 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001052
Eli Friedman449fe542009-03-23 04:56:01 +00001053 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001054};
Chris Lattner05706e882008-07-11 18:11:29 +00001055} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001056
John McCall45d55e42010-05-07 21:00:08 +00001057static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001058 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001059 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001060}
1061
John McCall45d55e42010-05-07 21:00:08 +00001062bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001063 if (E->getOpcode() != BO_Add &&
1064 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001065 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001066
Chris Lattner05706e882008-07-11 18:11:29 +00001067 const Expr *PExp = E->getLHS();
1068 const Expr *IExp = E->getRHS();
1069 if (IExp->getType()->isPointerType())
1070 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001071
John McCall45d55e42010-05-07 21:00:08 +00001072 if (!EvaluatePointer(PExp, Result, Info))
1073 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001074
John McCall45d55e42010-05-07 21:00:08 +00001075 llvm::APSInt Offset;
1076 if (!EvaluateInteger(IExp, Offset, Info))
1077 return false;
1078 int64_t AdditionalOffset
1079 = Offset.isSigned() ? Offset.getSExtValue()
1080 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001081
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001082 // Compute the new offset in the appropriate width.
1083
1084 QualType PointeeType =
1085 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001086 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001087
Anders Carlssonef56fba2009-02-19 04:55:58 +00001088 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1089 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001090 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001091 else
John McCall45d55e42010-05-07 21:00:08 +00001092 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001093
John McCalle3027922010-08-25 11:45:40 +00001094 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001095 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001096 else
John McCall45d55e42010-05-07 21:00:08 +00001097 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001098
John McCall45d55e42010-05-07 21:00:08 +00001099 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001100}
Eli Friedman9a156e52008-11-12 09:44:48 +00001101
John McCall45d55e42010-05-07 21:00:08 +00001102bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1103 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001104}
Mike Stump11289f42009-09-09 15:08:12 +00001105
Chris Lattner05706e882008-07-11 18:11:29 +00001106
Peter Collingbournee9200682011-05-13 03:29:01 +00001107bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1108 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001109
Eli Friedman847a2bc2009-12-27 05:43:15 +00001110 switch (E->getCastKind()) {
1111 default:
1112 break;
1113
John McCalle3027922010-08-25 11:45:40 +00001114 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001115 case CK_CPointerToObjCPointerCast:
1116 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001117 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001118 return Visit(SubExpr);
1119
Anders Carlsson18275092010-10-31 20:41:46 +00001120 case CK_DerivedToBase:
1121 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001122 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001123 return false;
1124
1125 // Now figure out the necessary offset to add to the baseLV to get from
1126 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001127 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001128
1129 QualType Ty = E->getSubExpr()->getType();
1130 const CXXRecordDecl *DerivedDecl =
1131 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1132
1133 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1134 PathE = E->path_end(); PathI != PathE; ++PathI) {
1135 const CXXBaseSpecifier *Base = *PathI;
1136
1137 // FIXME: If the base is virtual, we'd need to determine the type of the
1138 // most derived class and we don't support that right now.
1139 if (Base->isVirtual())
1140 return false;
1141
1142 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1143 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1144
Richard Smith0b0a0b62011-10-29 20:57:55 +00001145 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001146 DerivedDecl = BaseDecl;
1147 }
1148
Anders Carlsson18275092010-10-31 20:41:46 +00001149 return true;
1150 }
1151
Richard Smith0b0a0b62011-10-29 20:57:55 +00001152 case CK_NullToPointer:
1153 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001154
John McCalle3027922010-08-25 11:45:40 +00001155 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001156 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001157 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001158 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001159
John McCall45d55e42010-05-07 21:00:08 +00001160 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001161 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1162 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001163 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001164 Result.Offset = CharUnits::fromQuantity(N);
1165 Result.CallIndex = CCValue::NoCallIndex;
John McCall45d55e42010-05-07 21:00:08 +00001166 return true;
1167 } else {
1168 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001169 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001170 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001171 }
1172 }
John McCalle3027922010-08-25 11:45:40 +00001173 case CK_ArrayToPointerDecay:
1174 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +00001175 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001176 }
1177
Richard Smith11562c52011-10-28 17:51:58 +00001178 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001179}
Chris Lattner05706e882008-07-11 18:11:29 +00001180
Peter Collingbournee9200682011-05-13 03:29:01 +00001181bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001182 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001183 Builtin::BI__builtin___CFStringMakeConstantString ||
1184 E->isBuiltinCall(Info.Ctx) ==
1185 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001186 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001187
Peter Collingbournee9200682011-05-13 03:29:01 +00001188 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001189}
Chris Lattner05706e882008-07-11 18:11:29 +00001190
1191//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001192// Vector Evaluation
1193//===----------------------------------------------------------------------===//
1194
1195namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001196 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001197 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1198 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001199 public:
Mike Stump11289f42009-09-09 15:08:12 +00001200
Richard Smith2d406342011-10-22 21:10:00 +00001201 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1202 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001203
Richard Smith2d406342011-10-22 21:10:00 +00001204 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1205 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1206 // FIXME: remove this APValue copy.
1207 Result = APValue(V.data(), V.size());
1208 return true;
1209 }
1210 bool Success(const APValue &V, const Expr *E) {
1211 Result = V;
1212 return true;
1213 }
1214 bool Error(const Expr *E) { return false; }
1215 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Richard Smith2d406342011-10-22 21:10:00 +00001217 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001218 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001219 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001220 bool VisitInitListExpr(const InitListExpr *E);
1221 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001222 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001223 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001224 // shufflevector, ExtVectorElementExpr
1225 // (Note that these require implementing conversions
1226 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001227 };
1228} // end anonymous namespace
1229
1230static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001231 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001232 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001233}
1234
Richard Smith2d406342011-10-22 21:10:00 +00001235bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1236 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001237 QualType EltTy = VTy->getElementType();
1238 unsigned NElts = VTy->getNumElements();
1239 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001241 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001242 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001243
Eli Friedmanc757de22011-03-25 00:43:55 +00001244 switch (E->getCastKind()) {
1245 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001246 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001247 if (SETy->isIntegerType()) {
1248 APSInt IntResult;
1249 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001250 return Error(E);
1251 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001252 } else if (SETy->isRealFloatingType()) {
1253 APFloat F(0.0);
1254 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001255 return Error(E);
1256 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001257 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001258 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001259 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001260
1261 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001262 SmallVector<APValue, 4> Elts(NElts, Val);
1263 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001264 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001265 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001266 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001267 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001268 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001269
Eli Friedmanc757de22011-03-25 00:43:55 +00001270 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001271 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001272
Eli Friedmanc757de22011-03-25 00:43:55 +00001273 APSInt Init;
1274 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001275 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001276
Eli Friedmanc757de22011-03-25 00:43:55 +00001277 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1278 "Vectors must be composed of ints or floats");
1279
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001280 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001281 for (unsigned i = 0; i != NElts; ++i) {
1282 APSInt Tmp = Init.extOrTrunc(EltWidth);
1283
1284 if (EltTy->isIntegerType())
1285 Elts.push_back(APValue(Tmp));
1286 else
1287 Elts.push_back(APValue(APFloat(Tmp)));
1288
1289 Init >>= EltWidth;
1290 }
Richard Smith2d406342011-10-22 21:10:00 +00001291 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001292 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001293 default:
Richard Smith11562c52011-10-28 17:51:58 +00001294 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001295 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001296}
1297
Richard Smith2d406342011-10-22 21:10:00 +00001298bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001299VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001300 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001301 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001302 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001303
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001304 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001305 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001306
John McCall875679e2010-06-11 17:54:15 +00001307 // If a vector is initialized with a single element, that value
1308 // becomes every element of the vector, not just the first.
1309 // This is the behavior described in the IBM AltiVec documentation.
1310 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001311
1312 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001313 // vector (OpenCL 6.1.6).
1314 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001315 return Visit(E->getInit(0));
1316
John McCall875679e2010-06-11 17:54:15 +00001317 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001318 if (EltTy->isIntegerType()) {
1319 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001320 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001321 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001322 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001323 } else {
1324 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001325 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001326 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001327 InitValue = APValue(f);
1328 }
1329 for (unsigned i = 0; i < NumElements; i++) {
1330 Elements.push_back(InitValue);
1331 }
1332 } else {
1333 for (unsigned i = 0; i < NumElements; i++) {
1334 if (EltTy->isIntegerType()) {
1335 llvm::APSInt sInt(32);
1336 if (i < NumInits) {
1337 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001338 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001339 } else {
1340 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1341 }
1342 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001343 } else {
John McCall875679e2010-06-11 17:54:15 +00001344 llvm::APFloat f(0.0);
1345 if (i < NumInits) {
1346 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001347 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001348 } else {
1349 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1350 }
1351 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001352 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001353 }
1354 }
Richard Smith2d406342011-10-22 21:10:00 +00001355 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001356}
1357
Richard Smith2d406342011-10-22 21:10:00 +00001358bool
1359VectorExprEvaluator::ValueInitialization(const Expr *E) {
1360 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001361 QualType EltTy = VT->getElementType();
1362 APValue ZeroElement;
1363 if (EltTy->isIntegerType())
1364 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1365 else
1366 ZeroElement =
1367 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1368
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001369 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001370 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001371}
1372
Richard Smith2d406342011-10-22 21:10:00 +00001373bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001374 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001375 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001376}
1377
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001378//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001379// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001380//
1381// As a GNU extension, we support casting pointers to sufficiently-wide integer
1382// types and back in constant folding. Integer values are thus represented
1383// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001384//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001385
1386namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001387class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001388 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001389 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001390public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001391 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001392 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001393
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001394 bool Success(const llvm::APSInt &SI, const Expr *E) {
1395 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001396 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001397 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001398 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001399 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001400 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001401 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001402 return true;
1403 }
1404
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001405 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001406 assert(E->getType()->isIntegralOrEnumerationType() &&
1407 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001408 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001409 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001410 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001411 Result.getInt().setIsUnsigned(
1412 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001413 return true;
1414 }
1415
1416 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001417 assert(E->getType()->isIntegralOrEnumerationType() &&
1418 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001419 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001420 return true;
1421 }
1422
Ken Dyckdbc01912011-03-11 02:13:43 +00001423 bool Success(CharUnits Size, const Expr *E) {
1424 return Success(Size.getQuantity(), E);
1425 }
1426
1427
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001428 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001429 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001430 if (Info.EvalStatus.Diag == 0) {
1431 Info.EvalStatus.DiagLoc = L;
1432 Info.EvalStatus.Diag = D;
1433 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001434 }
Chris Lattner99415702008-07-12 00:14:42 +00001435 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001436 }
Mike Stump11289f42009-09-09 15:08:12 +00001437
Richard Smith0b0a0b62011-10-29 20:57:55 +00001438 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001439 if (V.isLValue()) {
1440 Result = V;
1441 return true;
1442 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001443 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001444 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001445 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001446 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Richard Smith4ce706a2011-10-11 21:43:33 +00001449 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1450
Peter Collingbournee9200682011-05-13 03:29:01 +00001451 //===--------------------------------------------------------------------===//
1452 // Visitor Methods
1453 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001454
Chris Lattner7174bf32008-07-12 00:38:25 +00001455 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001456 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001457 }
1458 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001459 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001460 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001461
1462 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1463 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001464 if (CheckReferencedDecl(E, E->getDecl()))
1465 return true;
1466
1467 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001468 }
1469 bool VisitMemberExpr(const MemberExpr *E) {
1470 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001471 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001472 return true;
1473 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001474
1475 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001476 }
1477
Peter Collingbournee9200682011-05-13 03:29:01 +00001478 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001479 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001480 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001481 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001482
Peter Collingbournee9200682011-05-13 03:29:01 +00001483 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001484 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001485
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001486 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001487 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001488 }
Mike Stump11289f42009-09-09 15:08:12 +00001489
Richard Smith4ce706a2011-10-11 21:43:33 +00001490 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001491 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001492 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001493 }
1494
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001495 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001496 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001497 }
1498
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001499 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1500 return Success(E->getValue(), E);
1501 }
1502
John Wiegley6242b6a2011-04-28 00:16:57 +00001503 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1504 return Success(E->getValue(), E);
1505 }
1506
John Wiegleyf9f65842011-04-25 06:54:41 +00001507 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1508 return Success(E->getValue(), E);
1509 }
1510
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001511 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001512 bool VisitUnaryImag(const UnaryOperator *E);
1513
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001514 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001515 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001516
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001517private:
Ken Dyck160146e2010-01-27 17:10:57 +00001518 CharUnits GetAlignOfExpr(const Expr *E);
1519 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001520 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001521 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001522 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001523};
Chris Lattner05706e882008-07-11 18:11:29 +00001524} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001525
Richard Smith11562c52011-10-28 17:51:58 +00001526/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1527/// produce either the integer value or a pointer.
1528///
1529/// GCC has a heinous extension which folds casts between pointer types and
1530/// pointer-sized integral types. We support this by allowing the evaluation of
1531/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1532/// Some simple arithmetic on such values is supported (they are treated much
1533/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001534static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1535 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001536 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001537 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001538}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001539
Daniel Dunbarce399542009-02-20 18:22:23 +00001540static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001541 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001542 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1543 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001544 Result = Val.getInt();
1545 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001546}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001547
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001548bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001549 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001550 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001551 // Check for signedness/width mismatches between E type and ECD value.
1552 bool SameSign = (ECD->getInitVal().isSigned()
1553 == E->getType()->isSignedIntegerOrEnumerationType());
1554 bool SameWidth = (ECD->getInitVal().getBitWidth()
1555 == Info.Ctx.getIntWidth(E->getType()));
1556 if (SameSign && SameWidth)
1557 return Success(ECD->getInitVal(), E);
1558 else {
1559 // Get rid of mismatch (otherwise Success assertions will fail)
1560 // by computing a new value matching the type of E.
1561 llvm::APSInt Val = ECD->getInitVal();
1562 if (!SameSign)
1563 Val.setIsSigned(!ECD->getInitVal().isSigned());
1564 if (!SameWidth)
1565 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1566 return Success(Val, E);
1567 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001568 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001569 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001570}
1571
Chris Lattner86ee2862008-10-06 06:40:35 +00001572/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1573/// as GCC.
1574static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1575 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001576 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001577 enum gcc_type_class {
1578 no_type_class = -1,
1579 void_type_class, integer_type_class, char_type_class,
1580 enumeral_type_class, boolean_type_class,
1581 pointer_type_class, reference_type_class, offset_type_class,
1582 real_type_class, complex_type_class,
1583 function_type_class, method_type_class,
1584 record_type_class, union_type_class,
1585 array_type_class, string_type_class,
1586 lang_type_class
1587 };
Mike Stump11289f42009-09-09 15:08:12 +00001588
1589 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001590 // ideal, however it is what gcc does.
1591 if (E->getNumArgs() == 0)
1592 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001593
Chris Lattner86ee2862008-10-06 06:40:35 +00001594 QualType ArgTy = E->getArg(0)->getType();
1595 if (ArgTy->isVoidType())
1596 return void_type_class;
1597 else if (ArgTy->isEnumeralType())
1598 return enumeral_type_class;
1599 else if (ArgTy->isBooleanType())
1600 return boolean_type_class;
1601 else if (ArgTy->isCharType())
1602 return string_type_class; // gcc doesn't appear to use char_type_class
1603 else if (ArgTy->isIntegerType())
1604 return integer_type_class;
1605 else if (ArgTy->isPointerType())
1606 return pointer_type_class;
1607 else if (ArgTy->isReferenceType())
1608 return reference_type_class;
1609 else if (ArgTy->isRealType())
1610 return real_type_class;
1611 else if (ArgTy->isComplexType())
1612 return complex_type_class;
1613 else if (ArgTy->isFunctionType())
1614 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001615 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001616 return record_type_class;
1617 else if (ArgTy->isUnionType())
1618 return union_type_class;
1619 else if (ArgTy->isArrayType())
1620 return array_type_class;
1621 else if (ArgTy->isUnionType())
1622 return union_type_class;
1623 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001624 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001625 return -1;
1626}
1627
John McCall95007602010-05-10 23:27:23 +00001628/// Retrieves the "underlying object type" of the given expression,
1629/// as used by __builtin_object_size.
1630QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1631 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1632 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1633 return VD->getType();
1634 } else if (isa<CompoundLiteralExpr>(E)) {
1635 return E->getType();
1636 }
1637
1638 return QualType();
1639}
1640
Peter Collingbournee9200682011-05-13 03:29:01 +00001641bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001642 // TODO: Perhaps we should let LLVM lower this?
1643 LValue Base;
1644 if (!EvaluatePointer(E->getArg(0), Base, Info))
1645 return false;
1646
1647 // If we can prove the base is null, lower to zero now.
1648 const Expr *LVBase = Base.getLValueBase();
1649 if (!LVBase) return Success(0, E);
1650
1651 QualType T = GetObjectType(LVBase);
1652 if (T.isNull() ||
1653 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001654 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001655 T->isVariablyModifiedType() ||
1656 T->isDependentType())
1657 return false;
1658
1659 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1660 CharUnits Offset = Base.getLValueOffset();
1661
1662 if (!Offset.isNegative() && Offset <= Size)
1663 Size -= Offset;
1664 else
1665 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001666 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001667}
1668
Peter Collingbournee9200682011-05-13 03:29:01 +00001669bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001670 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001671 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001672 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001673
1674 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001675 if (TryEvaluateBuiltinObjectSize(E))
1676 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001677
Eric Christopher99469702010-01-19 22:58:35 +00001678 // If evaluating the argument has side-effects we can't determine
1679 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001680 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001681 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001682 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001683 return Success(0, E);
1684 }
Mike Stump876387b2009-10-27 22:09:17 +00001685
Mike Stump722cedf2009-10-26 18:35:08 +00001686 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1687 }
1688
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001689 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001690 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001691
Anders Carlsson4c76e932008-11-24 04:21:33 +00001692 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001693 // __builtin_constant_p always has one operand: it returns true if that
1694 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001695 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001696
1697 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001698 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001699 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001700 return Success(Operand, E);
1701 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001702
1703 case Builtin::BI__builtin_expect:
1704 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001705
1706 case Builtin::BIstrlen:
1707 case Builtin::BI__builtin_strlen:
1708 // As an extension, we support strlen() and __builtin_strlen() as constant
1709 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001710 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001711 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1712 // The string literal may have embedded null characters. Find the first
1713 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001714 StringRef Str = S->getString();
1715 StringRef::size_type Pos = Str.find(0);
1716 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001717 Str = Str.substr(0, Pos);
1718
1719 return Success(Str.size(), E);
1720 }
1721
1722 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001723
1724 case Builtin::BI__atomic_is_lock_free: {
1725 APSInt SizeVal;
1726 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1727 return false;
1728
1729 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1730 // of two less than the maximum inline atomic width, we know it is
1731 // lock-free. If the size isn't a power of two, or greater than the
1732 // maximum alignment where we promote atomics, we know it is not lock-free
1733 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1734 // the answer can only be determined at runtime; for example, 16-byte
1735 // atomics have lock-free implementations on some, but not all,
1736 // x86-64 processors.
1737
1738 // Check power-of-two.
1739 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1740 if (!Size.isPowerOfTwo())
1741#if 0
1742 // FIXME: Suppress this folding until the ABI for the promotion width
1743 // settles.
1744 return Success(0, E);
1745#else
1746 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1747#endif
1748
1749#if 0
1750 // Check against promotion width.
1751 // FIXME: Suppress this folding until the ABI for the promotion width
1752 // settles.
1753 unsigned PromoteWidthBits =
1754 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1755 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1756 return Success(0, E);
1757#endif
1758
1759 // Check against inlining width.
1760 unsigned InlineWidthBits =
1761 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1762 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1763 return Success(1, E);
1764
1765 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1766 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001767 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001768}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001769
Chris Lattnere13042c2008-07-11 19:10:17 +00001770bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001771 if (E->isAssignmentOp())
1772 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1773
John McCalle3027922010-08-25 11:45:40 +00001774 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001775 VisitIgnoredValue(E->getLHS());
1776 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001777 }
1778
1779 if (E->isLogicalOp()) {
1780 // These need to be handled specially because the operands aren't
1781 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001782 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001783
Richard Smith11562c52011-10-28 17:51:58 +00001784 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001785 // We were able to evaluate the LHS, see if we can get away with not
1786 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001787 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001788 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001789
Richard Smith11562c52011-10-28 17:51:58 +00001790 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001791 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001792 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001793 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001794 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001795 }
1796 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001797 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001798 // We can't evaluate the LHS; however, sometimes the result
1799 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001800 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1801 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001802 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001803 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001804 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001805
1806 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001807 }
1808 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001809 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001810
Eli Friedman5a332ea2008-11-13 06:09:17 +00001811 return false;
1812 }
1813
Anders Carlssonacc79812008-11-16 07:17:21 +00001814 QualType LHSTy = E->getLHS()->getType();
1815 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001816
1817 if (LHSTy->isAnyComplexType()) {
1818 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001819 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001820
1821 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1822 return false;
1823
1824 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1825 return false;
1826
1827 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001828 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001829 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001830 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001831 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1832
John McCalle3027922010-08-25 11:45:40 +00001833 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001834 return Success((CR_r == APFloat::cmpEqual &&
1835 CR_i == APFloat::cmpEqual), E);
1836 else {
John McCalle3027922010-08-25 11:45:40 +00001837 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001838 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001839 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001840 CR_r == APFloat::cmpLessThan ||
1841 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001842 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001843 CR_i == APFloat::cmpLessThan ||
1844 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001845 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001846 } else {
John McCalle3027922010-08-25 11:45:40 +00001847 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001848 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1849 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1850 else {
John McCalle3027922010-08-25 11:45:40 +00001851 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001852 "Invalid compex comparison.");
1853 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1854 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1855 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001856 }
1857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
Anders Carlssonacc79812008-11-16 07:17:21 +00001859 if (LHSTy->isRealFloatingType() &&
1860 RHSTy->isRealFloatingType()) {
1861 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Anders Carlssonacc79812008-11-16 07:17:21 +00001863 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1864 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001865
Anders Carlssonacc79812008-11-16 07:17:21 +00001866 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1867 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001868
Anders Carlssonacc79812008-11-16 07:17:21 +00001869 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001870
Anders Carlssonacc79812008-11-16 07:17:21 +00001871 switch (E->getOpcode()) {
1872 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001873 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001874 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001875 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001876 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001877 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001878 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001879 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001880 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001881 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001882 E);
John McCalle3027922010-08-25 11:45:40 +00001883 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001884 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001885 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001886 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001887 || CR == APFloat::cmpLessThan
1888 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001889 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891
Eli Friedmana38da572009-04-28 19:17:36 +00001892 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001893 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001894 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001895 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1896 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001897
John McCall45d55e42010-05-07 21:00:08 +00001898 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001899 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1900 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001901
Eli Friedman334046a2009-06-14 02:17:33 +00001902 // Reject any bases from the normal codepath; we special-case comparisons
1903 // to null.
1904 if (LHSValue.getLValueBase()) {
1905 if (!E->isEqualityOp())
1906 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001907 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001908 return false;
1909 bool bres;
1910 if (!EvalPointerValueAsBool(LHSValue, bres))
1911 return false;
John McCalle3027922010-08-25 11:45:40 +00001912 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001913 } else if (RHSValue.getLValueBase()) {
1914 if (!E->isEqualityOp())
1915 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001916 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001917 return false;
1918 bool bres;
1919 if (!EvalPointerValueAsBool(RHSValue, bres))
1920 return false;
John McCalle3027922010-08-25 11:45:40 +00001921 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001922 }
Eli Friedman64004332009-03-23 04:38:34 +00001923
John McCalle3027922010-08-25 11:45:40 +00001924 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001925 QualType Type = E->getLHS()->getType();
1926 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001927
Ken Dyck02990832010-01-15 12:37:54 +00001928 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001929 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001930 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001931
Ken Dyck02990832010-01-15 12:37:54 +00001932 CharUnits Diff = LHSValue.getLValueOffset() -
1933 RHSValue.getLValueOffset();
1934 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001935 }
1936 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001937 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001938 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001939 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001940 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1941 }
1942 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001943 }
1944 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001945 if (!LHSTy->isIntegralOrEnumerationType() ||
1946 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001947 // We can't continue from here for non-integral types, and they
1948 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001949 return false;
1950 }
1951
Anders Carlsson9c181652008-07-08 14:35:21 +00001952 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001953 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00001954 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001955 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001956
Richard Smith11562c52011-10-28 17:51:58 +00001957 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001958 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001959 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001960
1961 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001962 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001963 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1964 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001965 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00001966 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001967 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00001968 LHSVal.getLValueOffset() -= AdditionalOffset;
1969 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00001970 return true;
1971 }
1972
1973 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001974 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001975 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001976 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
1977 LHSVal.getInt().getZExtValue());
1978 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00001979 return true;
1980 }
1981
1982 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00001983 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001984 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001985
Richard Smith11562c52011-10-28 17:51:58 +00001986 APSInt &LHS = LHSVal.getInt();
1987 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00001988
Anders Carlsson9c181652008-07-08 14:35:21 +00001989 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001990 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001991 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00001992 case BO_Mul: return Success(LHS * RHS, E);
1993 case BO_Add: return Success(LHS + RHS, E);
1994 case BO_Sub: return Success(LHS - RHS, E);
1995 case BO_And: return Success(LHS & RHS, E);
1996 case BO_Xor: return Success(LHS ^ RHS, E);
1997 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001998 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001999 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002000 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002001 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002002 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002003 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002004 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002005 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002006 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002007 // During constant-folding, a negative shift is an opposite shift.
2008 if (RHS.isSigned() && RHS.isNegative()) {
2009 RHS = -RHS;
2010 goto shift_right;
2011 }
2012
2013 shift_left:
2014 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002015 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2016 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002017 }
John McCalle3027922010-08-25 11:45:40 +00002018 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002019 // During constant-folding, a negative shift is an opposite shift.
2020 if (RHS.isSigned() && RHS.isNegative()) {
2021 RHS = -RHS;
2022 goto shift_left;
2023 }
2024
2025 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002026 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002027 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2028 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Richard Smith11562c52011-10-28 17:51:58 +00002031 case BO_LT: return Success(LHS < RHS, E);
2032 case BO_GT: return Success(LHS > RHS, E);
2033 case BO_LE: return Success(LHS <= RHS, E);
2034 case BO_GE: return Success(LHS >= RHS, E);
2035 case BO_EQ: return Success(LHS == RHS, E);
2036 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002037 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002038}
2039
Ken Dyck160146e2010-01-27 17:10:57 +00002040CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002041 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2042 // the result is the size of the referenced type."
2043 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2044 // result shall be the alignment of the referenced type."
2045 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2046 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002047
2048 // __alignof is defined to return the preferred alignment.
2049 return Info.Ctx.toCharUnitsFromBits(
2050 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002051}
2052
Ken Dyck160146e2010-01-27 17:10:57 +00002053CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002054 E = E->IgnoreParens();
2055
2056 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002057 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002058 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002059 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2060 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002061
Chris Lattner68061312009-01-24 21:53:27 +00002062 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002063 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2064 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002065
Chris Lattner24aeeab2009-01-24 21:09:06 +00002066 return GetAlignOfType(E->getType());
2067}
2068
2069
Peter Collingbournee190dee2011-03-11 19:24:49 +00002070/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2071/// a result as the expression's type.
2072bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2073 const UnaryExprOrTypeTraitExpr *E) {
2074 switch(E->getKind()) {
2075 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002076 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002077 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002078 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002079 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002080 }
Eli Friedman64004332009-03-23 04:38:34 +00002081
Peter Collingbournee190dee2011-03-11 19:24:49 +00002082 case UETT_VecStep: {
2083 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002084
Peter Collingbournee190dee2011-03-11 19:24:49 +00002085 if (Ty->isVectorType()) {
2086 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002087
Peter Collingbournee190dee2011-03-11 19:24:49 +00002088 // The vec_step built-in functions that take a 3-component
2089 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2090 if (n == 3)
2091 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002092
Peter Collingbournee190dee2011-03-11 19:24:49 +00002093 return Success(n, E);
2094 } else
2095 return Success(1, E);
2096 }
2097
2098 case UETT_SizeOf: {
2099 QualType SrcTy = E->getTypeOfArgument();
2100 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2101 // the result is the size of the referenced type."
2102 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2103 // result shall be the alignment of the referenced type."
2104 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2105 SrcTy = Ref->getPointeeType();
2106
2107 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2108 // extension.
2109 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2110 return Success(1, E);
2111
2112 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2113 if (!SrcTy->isConstantSizeType())
2114 return false;
2115
2116 // Get information about the size.
2117 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2118 }
2119 }
2120
2121 llvm_unreachable("unknown expr/type trait");
2122 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002123}
2124
Peter Collingbournee9200682011-05-13 03:29:01 +00002125bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002126 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002127 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002128 if (n == 0)
2129 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002130 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002131 for (unsigned i = 0; i != n; ++i) {
2132 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2133 switch (ON.getKind()) {
2134 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002135 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002136 APSInt IdxResult;
2137 if (!EvaluateInteger(Idx, IdxResult, Info))
2138 return false;
2139 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2140 if (!AT)
2141 return false;
2142 CurrentType = AT->getElementType();
2143 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2144 Result += IdxResult.getSExtValue() * ElementSize;
2145 break;
2146 }
2147
2148 case OffsetOfExpr::OffsetOfNode::Field: {
2149 FieldDecl *MemberDecl = ON.getField();
2150 const RecordType *RT = CurrentType->getAs<RecordType>();
2151 if (!RT)
2152 return false;
2153 RecordDecl *RD = RT->getDecl();
2154 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002155 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002156 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002157 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002158 CurrentType = MemberDecl->getType().getNonReferenceType();
2159 break;
2160 }
2161
2162 case OffsetOfExpr::OffsetOfNode::Identifier:
2163 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002164 return false;
2165
2166 case OffsetOfExpr::OffsetOfNode::Base: {
2167 CXXBaseSpecifier *BaseSpec = ON.getBase();
2168 if (BaseSpec->isVirtual())
2169 return false;
2170
2171 // Find the layout of the class whose base we are looking into.
2172 const RecordType *RT = CurrentType->getAs<RecordType>();
2173 if (!RT)
2174 return false;
2175 RecordDecl *RD = RT->getDecl();
2176 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2177
2178 // Find the base class itself.
2179 CurrentType = BaseSpec->getType();
2180 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2181 if (!BaseRT)
2182 return false;
2183
2184 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002185 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002186 break;
2187 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002188 }
2189 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002190 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002191}
2192
Chris Lattnere13042c2008-07-11 19:10:17 +00002193bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002194 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002195 // LNot's operand isn't necessarily an integer, so we handle it specially.
2196 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002197 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002198 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002199 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002200 }
2201
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002202 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002203 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002204 return false;
2205
Richard Smith11562c52011-10-28 17:51:58 +00002206 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002207 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002208 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002209 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002210
Chris Lattnerf09ad162008-07-11 22:15:16 +00002211 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002212 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002213 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2214 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002215 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002216 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002217 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2218 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002219 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002220 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002221 // The result is just the value.
2222 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002223 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002224 if (!Val.isInt()) return false;
2225 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002226 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002227 if (!Val.isInt()) return false;
2228 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002229 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002230}
Mike Stump11289f42009-09-09 15:08:12 +00002231
Chris Lattner477c4be2008-07-12 01:15:53 +00002232/// HandleCast - This is used to evaluate implicit or explicit casts where the
2233/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002234bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2235 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002236 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002237 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002238
Eli Friedmanc757de22011-03-25 00:43:55 +00002239 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002240 case CK_BaseToDerived:
2241 case CK_DerivedToBase:
2242 case CK_UncheckedDerivedToBase:
2243 case CK_Dynamic:
2244 case CK_ToUnion:
2245 case CK_ArrayToPointerDecay:
2246 case CK_FunctionToPointerDecay:
2247 case CK_NullToPointer:
2248 case CK_NullToMemberPointer:
2249 case CK_BaseToDerivedMemberPointer:
2250 case CK_DerivedToBaseMemberPointer:
2251 case CK_ConstructorConversion:
2252 case CK_IntegralToPointer:
2253 case CK_ToVoid:
2254 case CK_VectorSplat:
2255 case CK_IntegralToFloating:
2256 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002257 case CK_CPointerToObjCPointerCast:
2258 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002259 case CK_AnyPointerToBlockPointerCast:
2260 case CK_ObjCObjectLValueCast:
2261 case CK_FloatingRealToComplex:
2262 case CK_FloatingComplexToReal:
2263 case CK_FloatingComplexCast:
2264 case CK_FloatingComplexToIntegralComplex:
2265 case CK_IntegralRealToComplex:
2266 case CK_IntegralComplexCast:
2267 case CK_IntegralComplexToFloatingComplex:
2268 llvm_unreachable("invalid cast kind for integral value");
2269
Eli Friedman9faf2f92011-03-25 19:07:11 +00002270 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002271 case CK_Dependent:
2272 case CK_GetObjCProperty:
2273 case CK_LValueBitCast:
2274 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002275 case CK_ARCProduceObject:
2276 case CK_ARCConsumeObject:
2277 case CK_ARCReclaimReturnedObject:
2278 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002279 return false;
2280
2281 case CK_LValueToRValue:
2282 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002283 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002284
2285 case CK_MemberPointerToBoolean:
2286 case CK_PointerToBoolean:
2287 case CK_IntegralToBoolean:
2288 case CK_FloatingToBoolean:
2289 case CK_FloatingComplexToBoolean:
2290 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002291 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002292 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002293 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002294 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002295 }
2296
Eli Friedmanc757de22011-03-25 00:43:55 +00002297 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002298 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002299 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002300
Eli Friedman742421e2009-02-20 01:15:07 +00002301 if (!Result.isInt()) {
2302 // Only allow casts of lvalues if they are lossless.
2303 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2304 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002305
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002306 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002307 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002308 }
Mike Stump11289f42009-09-09 15:08:12 +00002309
Eli Friedmanc757de22011-03-25 00:43:55 +00002310 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002311 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002312 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002313 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002314
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002315 if (LV.getLValueBase()) {
2316 // Only allow based lvalue casts if they are lossless.
2317 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2318 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002319
John McCall45d55e42010-05-07 21:00:08 +00002320 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002321 return true;
2322 }
2323
Ken Dyck02990832010-01-15 12:37:54 +00002324 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2325 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002326 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002327 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002328
Eli Friedmanc757de22011-03-25 00:43:55 +00002329 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002330 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002331 if (!EvaluateComplex(SubExpr, C, Info))
2332 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002333 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002334 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002335
Eli Friedmanc757de22011-03-25 00:43:55 +00002336 case CK_FloatingToIntegral: {
2337 APFloat F(0.0);
2338 if (!EvaluateFloat(SubExpr, F, Info))
2339 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002340
Eli Friedmanc757de22011-03-25 00:43:55 +00002341 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2342 }
2343 }
Mike Stump11289f42009-09-09 15:08:12 +00002344
Eli Friedmanc757de22011-03-25 00:43:55 +00002345 llvm_unreachable("unknown cast resulting in integral value");
2346 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002347}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002348
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002349bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2350 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002351 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002352 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2353 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2354 return Success(LV.getComplexIntReal(), E);
2355 }
2356
2357 return Visit(E->getSubExpr());
2358}
2359
Eli Friedman4e7a2412009-02-27 04:45:43 +00002360bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002361 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002362 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002363 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2364 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2365 return Success(LV.getComplexIntImag(), E);
2366 }
2367
Richard Smith4a678122011-10-24 18:44:57 +00002368 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002369 return Success(0, E);
2370}
2371
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002372bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2373 return Success(E->getPackLength(), E);
2374}
2375
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002376bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2377 return Success(E->getValue(), E);
2378}
2379
Chris Lattner05706e882008-07-11 18:11:29 +00002380//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002381// Float Evaluation
2382//===----------------------------------------------------------------------===//
2383
2384namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002385class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002386 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002387 APFloat &Result;
2388public:
2389 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002390 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002391
Richard Smith0b0a0b62011-10-29 20:57:55 +00002392 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002393 Result = V.getFloat();
2394 return true;
2395 }
2396 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002397 return false;
2398 }
2399
Richard Smith4ce706a2011-10-11 21:43:33 +00002400 bool ValueInitialization(const Expr *E) {
2401 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2402 return true;
2403 }
2404
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002405 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002406
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002407 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002408 bool VisitBinaryOperator(const BinaryOperator *E);
2409 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002410 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002411
John McCallb1fb0d32010-05-07 22:08:54 +00002412 bool VisitUnaryReal(const UnaryOperator *E);
2413 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002414
John McCallb1fb0d32010-05-07 22:08:54 +00002415 // FIXME: Missing: array subscript of vector, member of vector,
2416 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002417};
2418} // end anonymous namespace
2419
2420static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002421 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002422 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002423}
2424
Jay Foad39c79802011-01-12 09:06:06 +00002425static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002426 QualType ResultTy,
2427 const Expr *Arg,
2428 bool SNaN,
2429 llvm::APFloat &Result) {
2430 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2431 if (!S) return false;
2432
2433 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2434
2435 llvm::APInt fill;
2436
2437 // Treat empty strings as if they were zero.
2438 if (S->getString().empty())
2439 fill = llvm::APInt(32, 0);
2440 else if (S->getString().getAsInteger(0, fill))
2441 return false;
2442
2443 if (SNaN)
2444 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2445 else
2446 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2447 return true;
2448}
2449
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002450bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002451 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002452 default:
2453 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2454
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002455 case Builtin::BI__builtin_huge_val:
2456 case Builtin::BI__builtin_huge_valf:
2457 case Builtin::BI__builtin_huge_vall:
2458 case Builtin::BI__builtin_inf:
2459 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002460 case Builtin::BI__builtin_infl: {
2461 const llvm::fltSemantics &Sem =
2462 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002463 Result = llvm::APFloat::getInf(Sem);
2464 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002465 }
Mike Stump11289f42009-09-09 15:08:12 +00002466
John McCall16291492010-02-28 13:00:19 +00002467 case Builtin::BI__builtin_nans:
2468 case Builtin::BI__builtin_nansf:
2469 case Builtin::BI__builtin_nansl:
2470 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2471 true, Result);
2472
Chris Lattner0b7282e2008-10-06 06:31:58 +00002473 case Builtin::BI__builtin_nan:
2474 case Builtin::BI__builtin_nanf:
2475 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002476 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002477 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002478 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2479 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002480
2481 case Builtin::BI__builtin_fabs:
2482 case Builtin::BI__builtin_fabsf:
2483 case Builtin::BI__builtin_fabsl:
2484 if (!EvaluateFloat(E->getArg(0), Result, Info))
2485 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002486
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002487 if (Result.isNegative())
2488 Result.changeSign();
2489 return true;
2490
Mike Stump11289f42009-09-09 15:08:12 +00002491 case Builtin::BI__builtin_copysign:
2492 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002493 case Builtin::BI__builtin_copysignl: {
2494 APFloat RHS(0.);
2495 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2496 !EvaluateFloat(E->getArg(1), RHS, Info))
2497 return false;
2498 Result.copySign(RHS);
2499 return true;
2500 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002501 }
2502}
2503
John McCallb1fb0d32010-05-07 22:08:54 +00002504bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002505 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2506 ComplexValue CV;
2507 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2508 return false;
2509 Result = CV.FloatReal;
2510 return true;
2511 }
2512
2513 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002514}
2515
2516bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002517 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2518 ComplexValue CV;
2519 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2520 return false;
2521 Result = CV.FloatImag;
2522 return true;
2523 }
2524
Richard Smith4a678122011-10-24 18:44:57 +00002525 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002526 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2527 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002528 return true;
2529}
2530
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002531bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002532 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002533 return false;
2534
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002535 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2536 return false;
2537
2538 switch (E->getOpcode()) {
2539 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002540 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002541 return true;
John McCalle3027922010-08-25 11:45:40 +00002542 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002543 Result.changeSign();
2544 return true;
2545 }
2546}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002547
Eli Friedman24c01542008-08-22 00:06:13 +00002548bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002549 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002550 VisitIgnoredValue(E->getLHS());
2551 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002552 }
2553
Richard Smith472d4952011-10-28 23:26:52 +00002554 // We can't evaluate pointer-to-member operations or assignments.
2555 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002556 return false;
2557
Eli Friedman24c01542008-08-22 00:06:13 +00002558 // FIXME: Diagnostics? I really don't understand how the warnings
2559 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002560 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002561 if (!EvaluateFloat(E->getLHS(), Result, Info))
2562 return false;
2563 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2564 return false;
2565
2566 switch (E->getOpcode()) {
2567 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002568 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002569 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2570 return true;
John McCalle3027922010-08-25 11:45:40 +00002571 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002572 Result.add(RHS, APFloat::rmNearestTiesToEven);
2573 return true;
John McCalle3027922010-08-25 11:45:40 +00002574 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002575 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2576 return true;
John McCalle3027922010-08-25 11:45:40 +00002577 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002578 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2579 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002580 }
2581}
2582
2583bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2584 Result = E->getValue();
2585 return true;
2586}
2587
Peter Collingbournee9200682011-05-13 03:29:01 +00002588bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2589 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002590
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002591 switch (E->getCastKind()) {
2592 default:
Richard Smith11562c52011-10-28 17:51:58 +00002593 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002594
2595 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002596 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002597 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002598 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002599 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002600 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002601 return true;
2602 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002603
2604 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002605 if (!Visit(SubExpr))
2606 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002607 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2608 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002609 return true;
2610 }
John McCalld7646252010-11-14 08:17:51 +00002611
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002612 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002613 ComplexValue V;
2614 if (!EvaluateComplex(SubExpr, V, Info))
2615 return false;
2616 Result = V.getComplexFloatReal();
2617 return true;
2618 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002619 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002620
2621 return false;
2622}
2623
Eli Friedman24c01542008-08-22 00:06:13 +00002624//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002625// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002626//===----------------------------------------------------------------------===//
2627
2628namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002629class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002630 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002631 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002632
Anders Carlsson537969c2008-11-16 20:27:53 +00002633public:
John McCall93d91dc2010-05-07 17:22:02 +00002634 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002635 : ExprEvaluatorBaseTy(info), Result(Result) {}
2636
Richard Smith0b0a0b62011-10-29 20:57:55 +00002637 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002638 Result.setFrom(V);
2639 return true;
2640 }
2641 bool Error(const Expr *E) {
2642 return false;
2643 }
Mike Stump11289f42009-09-09 15:08:12 +00002644
Anders Carlsson537969c2008-11-16 20:27:53 +00002645 //===--------------------------------------------------------------------===//
2646 // Visitor Methods
2647 //===--------------------------------------------------------------------===//
2648
Peter Collingbournee9200682011-05-13 03:29:01 +00002649 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002650
Peter Collingbournee9200682011-05-13 03:29:01 +00002651 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002652
John McCall93d91dc2010-05-07 17:22:02 +00002653 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002654 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002655 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002656};
2657} // end anonymous namespace
2658
John McCall93d91dc2010-05-07 17:22:02 +00002659static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2660 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002661 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002662 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002663}
2664
Peter Collingbournee9200682011-05-13 03:29:01 +00002665bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2666 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002667
2668 if (SubExpr->getType()->isRealFloatingType()) {
2669 Result.makeComplexFloat();
2670 APFloat &Imag = Result.FloatImag;
2671 if (!EvaluateFloat(SubExpr, Imag, Info))
2672 return false;
2673
2674 Result.FloatReal = APFloat(Imag.getSemantics());
2675 return true;
2676 } else {
2677 assert(SubExpr->getType()->isIntegerType() &&
2678 "Unexpected imaginary literal.");
2679
2680 Result.makeComplexInt();
2681 APSInt &Imag = Result.IntImag;
2682 if (!EvaluateInteger(SubExpr, Imag, Info))
2683 return false;
2684
2685 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2686 return true;
2687 }
2688}
2689
Peter Collingbournee9200682011-05-13 03:29:01 +00002690bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002691
John McCallfcef3cf2010-12-14 17:51:41 +00002692 switch (E->getCastKind()) {
2693 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002694 case CK_BaseToDerived:
2695 case CK_DerivedToBase:
2696 case CK_UncheckedDerivedToBase:
2697 case CK_Dynamic:
2698 case CK_ToUnion:
2699 case CK_ArrayToPointerDecay:
2700 case CK_FunctionToPointerDecay:
2701 case CK_NullToPointer:
2702 case CK_NullToMemberPointer:
2703 case CK_BaseToDerivedMemberPointer:
2704 case CK_DerivedToBaseMemberPointer:
2705 case CK_MemberPointerToBoolean:
2706 case CK_ConstructorConversion:
2707 case CK_IntegralToPointer:
2708 case CK_PointerToIntegral:
2709 case CK_PointerToBoolean:
2710 case CK_ToVoid:
2711 case CK_VectorSplat:
2712 case CK_IntegralCast:
2713 case CK_IntegralToBoolean:
2714 case CK_IntegralToFloating:
2715 case CK_FloatingToIntegral:
2716 case CK_FloatingToBoolean:
2717 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002718 case CK_CPointerToObjCPointerCast:
2719 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002720 case CK_AnyPointerToBlockPointerCast:
2721 case CK_ObjCObjectLValueCast:
2722 case CK_FloatingComplexToReal:
2723 case CK_FloatingComplexToBoolean:
2724 case CK_IntegralComplexToReal:
2725 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002726 case CK_ARCProduceObject:
2727 case CK_ARCConsumeObject:
2728 case CK_ARCReclaimReturnedObject:
2729 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002730 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002731
John McCallfcef3cf2010-12-14 17:51:41 +00002732 case CK_LValueToRValue:
2733 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002735
2736 case CK_Dependent:
2737 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002738 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002739 case CK_UserDefinedConversion:
2740 return false;
2741
2742 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002743 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002744 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002745 return false;
2746
John McCallfcef3cf2010-12-14 17:51:41 +00002747 Result.makeComplexFloat();
2748 Result.FloatImag = APFloat(Real.getSemantics());
2749 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002750 }
2751
John McCallfcef3cf2010-12-14 17:51:41 +00002752 case CK_FloatingComplexCast: {
2753 if (!Visit(E->getSubExpr()))
2754 return false;
2755
2756 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2757 QualType From
2758 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2759
2760 Result.FloatReal
2761 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2762 Result.FloatImag
2763 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2764 return true;
2765 }
2766
2767 case CK_FloatingComplexToIntegralComplex: {
2768 if (!Visit(E->getSubExpr()))
2769 return false;
2770
2771 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2772 QualType From
2773 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2774 Result.makeComplexInt();
2775 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2776 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2777 return true;
2778 }
2779
2780 case CK_IntegralRealToComplex: {
2781 APSInt &Real = Result.IntReal;
2782 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2783 return false;
2784
2785 Result.makeComplexInt();
2786 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2787 return true;
2788 }
2789
2790 case CK_IntegralComplexCast: {
2791 if (!Visit(E->getSubExpr()))
2792 return false;
2793
2794 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2795 QualType From
2796 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2797
2798 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2799 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2800 return true;
2801 }
2802
2803 case CK_IntegralComplexToFloatingComplex: {
2804 if (!Visit(E->getSubExpr()))
2805 return false;
2806
2807 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2808 QualType From
2809 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2810 Result.makeComplexFloat();
2811 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2812 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2813 return true;
2814 }
2815 }
2816
2817 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002818 return false;
2819}
2820
John McCall93d91dc2010-05-07 17:22:02 +00002821bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002822 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002823 VisitIgnoredValue(E->getLHS());
2824 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002825 }
John McCall93d91dc2010-05-07 17:22:02 +00002826 if (!Visit(E->getLHS()))
2827 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002828
John McCall93d91dc2010-05-07 17:22:02 +00002829 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002830 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002831 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002832
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002833 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2834 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002835 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002836 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002837 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002838 if (Result.isComplexFloat()) {
2839 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2840 APFloat::rmNearestTiesToEven);
2841 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2842 APFloat::rmNearestTiesToEven);
2843 } else {
2844 Result.getComplexIntReal() += RHS.getComplexIntReal();
2845 Result.getComplexIntImag() += RHS.getComplexIntImag();
2846 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002847 break;
John McCalle3027922010-08-25 11:45:40 +00002848 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002849 if (Result.isComplexFloat()) {
2850 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2851 APFloat::rmNearestTiesToEven);
2852 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2853 APFloat::rmNearestTiesToEven);
2854 } else {
2855 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2856 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2857 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002858 break;
John McCalle3027922010-08-25 11:45:40 +00002859 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002860 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002861 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002862 APFloat &LHS_r = LHS.getComplexFloatReal();
2863 APFloat &LHS_i = LHS.getComplexFloatImag();
2864 APFloat &RHS_r = RHS.getComplexFloatReal();
2865 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002866
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002867 APFloat Tmp = LHS_r;
2868 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2869 Result.getComplexFloatReal() = Tmp;
2870 Tmp = LHS_i;
2871 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2872 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2873
2874 Tmp = LHS_r;
2875 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2876 Result.getComplexFloatImag() = Tmp;
2877 Tmp = LHS_i;
2878 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2879 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2880 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002881 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002882 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002883 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2884 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002885 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002886 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2887 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2888 }
2889 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002890 case BO_Div:
2891 if (Result.isComplexFloat()) {
2892 ComplexValue LHS = Result;
2893 APFloat &LHS_r = LHS.getComplexFloatReal();
2894 APFloat &LHS_i = LHS.getComplexFloatImag();
2895 APFloat &RHS_r = RHS.getComplexFloatReal();
2896 APFloat &RHS_i = RHS.getComplexFloatImag();
2897 APFloat &Res_r = Result.getComplexFloatReal();
2898 APFloat &Res_i = Result.getComplexFloatImag();
2899
2900 APFloat Den = RHS_r;
2901 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2902 APFloat Tmp = RHS_i;
2903 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2904 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2905
2906 Res_r = LHS_r;
2907 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2908 Tmp = LHS_i;
2909 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2910 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2911 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2912
2913 Res_i = LHS_i;
2914 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2915 Tmp = LHS_r;
2916 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2917 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2918 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2919 } else {
2920 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2921 // FIXME: what about diagnostics?
2922 return false;
2923 }
2924 ComplexValue LHS = Result;
2925 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2926 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2927 Result.getComplexIntReal() =
2928 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2929 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2930 Result.getComplexIntImag() =
2931 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2932 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2933 }
2934 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002935 }
2936
John McCall93d91dc2010-05-07 17:22:02 +00002937 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002938}
2939
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002940bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2941 // Get the operand value into 'Result'.
2942 if (!Visit(E->getSubExpr()))
2943 return false;
2944
2945 switch (E->getOpcode()) {
2946 default:
2947 // FIXME: what about diagnostics?
2948 return false;
2949 case UO_Extension:
2950 return true;
2951 case UO_Plus:
2952 // The result is always just the subexpr.
2953 return true;
2954 case UO_Minus:
2955 if (Result.isComplexFloat()) {
2956 Result.getComplexFloatReal().changeSign();
2957 Result.getComplexFloatImag().changeSign();
2958 }
2959 else {
2960 Result.getComplexIntReal() = -Result.getComplexIntReal();
2961 Result.getComplexIntImag() = -Result.getComplexIntImag();
2962 }
2963 return true;
2964 case UO_Not:
2965 if (Result.isComplexFloat())
2966 Result.getComplexFloatImag().changeSign();
2967 else
2968 Result.getComplexIntImag() = -Result.getComplexIntImag();
2969 return true;
2970 }
2971}
2972
Anders Carlsson537969c2008-11-16 20:27:53 +00002973//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00002974// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00002975//===----------------------------------------------------------------------===//
2976
Richard Smith0b0a0b62011-10-29 20:57:55 +00002977static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002978 // In C, function designators are not lvalues, but we evaluate them as if they
2979 // are.
2980 if (E->isGLValue() || E->getType()->isFunctionType()) {
2981 LValue LV;
2982 if (!EvaluateLValue(E, LV, Info))
2983 return false;
2984 LV.moveInto(Result);
2985 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002986 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002987 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002988 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002989 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002990 return false;
John McCall45d55e42010-05-07 21:00:08 +00002991 } else if (E->getType()->hasPointerRepresentation()) {
2992 LValue LV;
2993 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002994 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002995 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002996 } else if (E->getType()->isRealFloatingType()) {
2997 llvm::APFloat F(0.0);
2998 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002999 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003000 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003001 } else if (E->getType()->isAnyComplexType()) {
3002 ComplexValue C;
3003 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003004 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003005 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003006 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003007 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003008
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003009 return true;
3010}
3011
Richard Smith11562c52011-10-28 17:51:58 +00003012
Richard Smith7b553f12011-10-29 00:50:52 +00003013/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003014/// any crazy technique (that has nothing to do with language standards) that
3015/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003016/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3017/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003018bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003019 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003020
Richard Smith0b0a0b62011-10-29 20:57:55 +00003021 CCValue Value;
3022 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003023 return false;
3024
3025 if (isGLValue()) {
3026 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003027 LV.setFrom(Value);
3028 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3029 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003030 }
3031
Richard Smith0b0a0b62011-10-29 20:57:55 +00003032 // Check this core constant expression is a constant expression, and if so,
3033 // slice it down to one.
3034 if (!CheckConstantExpression(Value))
3035 return false;
3036 Result.Val = Value;
3037 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003038}
3039
Jay Foad39c79802011-01-12 09:06:06 +00003040bool Expr::EvaluateAsBooleanCondition(bool &Result,
3041 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003042 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003043 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith0b0a0b62011-10-29 20:57:55 +00003044 HandleConversionToBool(CCValue(Scratch.Val, CCValue::NoCallIndex),
3045 Result);
John McCall1be1c632010-01-05 23:42:56 +00003046}
3047
Richard Smithcaf33902011-10-10 18:28:20 +00003048bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003049 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003050 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003051 !ExprResult.Val.isInt()) {
3052 return false;
3053 }
3054 Result = ExprResult.Val.getInt();
3055 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003056}
3057
Jay Foad39c79802011-01-12 09:06:06 +00003058bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003059 EvalInfo Info(Ctx, Result);
3060
John McCall45d55e42010-05-07 21:00:08 +00003061 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003062 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003063 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003064 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003065 return true;
3066 }
3067 return false;
3068}
3069
Jay Foad39c79802011-01-12 09:06:06 +00003070bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3071 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003072 EvalInfo Info(Ctx, Result);
3073
3074 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003075 // Don't allow references to out-of-scope function parameters to escape.
3076 if (EvaluateLValue(this, LV, Info) &&
3077 (!IsParamLValue(LV.Base) || LV.CallIndex == CCValue::NoCallIndex)) {
3078 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003079 return true;
3080 }
3081 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003082}
3083
Richard Smith7b553f12011-10-29 00:50:52 +00003084/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3085/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003086bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003087 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003088 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003089}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003090
Jay Foad39c79802011-01-12 09:06:06 +00003091bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003092 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003093}
3094
Richard Smithcaf33902011-10-10 18:28:20 +00003095APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003096 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003097 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003098 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003099 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003100 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003101
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003102 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003103}
John McCall864e3962010-05-07 05:32:02 +00003104
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003105 bool Expr::EvalResult::isGlobalLValue() const {
3106 assert(Val.isLValue());
3107 return IsGlobalLValue(Val.getLValueBase());
3108 }
3109
3110
John McCall864e3962010-05-07 05:32:02 +00003111/// isIntegerConstantExpr - this recursive routine will test if an expression is
3112/// an integer constant expression.
3113
3114/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3115/// comma, etc
3116///
3117/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3118/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3119/// cast+dereference.
3120
3121// CheckICE - This function does the fundamental ICE checking: the returned
3122// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3123// Note that to reduce code duplication, this helper does no evaluation
3124// itself; the caller checks whether the expression is evaluatable, and
3125// in the rare cases where CheckICE actually cares about the evaluated
3126// value, it calls into Evalute.
3127//
3128// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003129// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003130// 1: This expression is not an ICE, but if it isn't evaluated, it's
3131// a legal subexpression for an ICE. This return value is used to handle
3132// the comma operator in C99 mode.
3133// 2: This expression is not an ICE, and is not a legal subexpression for one.
3134
Dan Gohman28ade552010-07-26 21:25:24 +00003135namespace {
3136
John McCall864e3962010-05-07 05:32:02 +00003137struct ICEDiag {
3138 unsigned Val;
3139 SourceLocation Loc;
3140
3141 public:
3142 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3143 ICEDiag() : Val(0) {}
3144};
3145
Dan Gohman28ade552010-07-26 21:25:24 +00003146}
3147
3148static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003149
3150static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3151 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003152 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003153 !EVResult.Val.isInt()) {
3154 return ICEDiag(2, E->getLocStart());
3155 }
3156 return NoDiag();
3157}
3158
3159static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3160 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003161 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003162 return ICEDiag(2, E->getLocStart());
3163 }
3164
3165 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003166#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003167#define STMT(Node, Base) case Expr::Node##Class:
3168#define EXPR(Node, Base)
3169#include "clang/AST/StmtNodes.inc"
3170 case Expr::PredefinedExprClass:
3171 case Expr::FloatingLiteralClass:
3172 case Expr::ImaginaryLiteralClass:
3173 case Expr::StringLiteralClass:
3174 case Expr::ArraySubscriptExprClass:
3175 case Expr::MemberExprClass:
3176 case Expr::CompoundAssignOperatorClass:
3177 case Expr::CompoundLiteralExprClass:
3178 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003179 case Expr::DesignatedInitExprClass:
3180 case Expr::ImplicitValueInitExprClass:
3181 case Expr::ParenListExprClass:
3182 case Expr::VAArgExprClass:
3183 case Expr::AddrLabelExprClass:
3184 case Expr::StmtExprClass:
3185 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003186 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003187 case Expr::CXXDynamicCastExprClass:
3188 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003189 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003190 case Expr::CXXNullPtrLiteralExprClass:
3191 case Expr::CXXThisExprClass:
3192 case Expr::CXXThrowExprClass:
3193 case Expr::CXXNewExprClass:
3194 case Expr::CXXDeleteExprClass:
3195 case Expr::CXXPseudoDestructorExprClass:
3196 case Expr::UnresolvedLookupExprClass:
3197 case Expr::DependentScopeDeclRefExprClass:
3198 case Expr::CXXConstructExprClass:
3199 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003200 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003201 case Expr::CXXTemporaryObjectExprClass:
3202 case Expr::CXXUnresolvedConstructExprClass:
3203 case Expr::CXXDependentScopeMemberExprClass:
3204 case Expr::UnresolvedMemberExprClass:
3205 case Expr::ObjCStringLiteralClass:
3206 case Expr::ObjCEncodeExprClass:
3207 case Expr::ObjCMessageExprClass:
3208 case Expr::ObjCSelectorExprClass:
3209 case Expr::ObjCProtocolExprClass:
3210 case Expr::ObjCIvarRefExprClass:
3211 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003212 case Expr::ObjCIsaExprClass:
3213 case Expr::ShuffleVectorExprClass:
3214 case Expr::BlockExprClass:
3215 case Expr::BlockDeclRefExprClass:
3216 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003217 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003218 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003219 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003220 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003221 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003222 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003223 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003224 return ICEDiag(2, E->getLocStart());
3225
Sebastian Redl12757ab2011-09-24 17:48:14 +00003226 case Expr::InitListExprClass:
3227 if (Ctx.getLangOptions().CPlusPlus0x) {
3228 const InitListExpr *ILE = cast<InitListExpr>(E);
3229 if (ILE->getNumInits() == 0)
3230 return NoDiag();
3231 if (ILE->getNumInits() == 1)
3232 return CheckICE(ILE->getInit(0), Ctx);
3233 // Fall through for more than 1 expression.
3234 }
3235 return ICEDiag(2, E->getLocStart());
3236
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003237 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003238 case Expr::GNUNullExprClass:
3239 // GCC considers the GNU __null value to be an integral constant expression.
3240 return NoDiag();
3241
John McCall7c454bb2011-07-15 05:09:51 +00003242 case Expr::SubstNonTypeTemplateParmExprClass:
3243 return
3244 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3245
John McCall864e3962010-05-07 05:32:02 +00003246 case Expr::ParenExprClass:
3247 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003248 case Expr::GenericSelectionExprClass:
3249 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003250 case Expr::IntegerLiteralClass:
3251 case Expr::CharacterLiteralClass:
3252 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003253 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003254 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003255 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003256 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003257 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003258 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003259 return NoDiag();
3260 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003261 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003262 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3263 // constant expressions, but they can never be ICEs because an ICE cannot
3264 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003265 const CallExpr *CE = cast<CallExpr>(E);
3266 if (CE->isBuiltinCall(Ctx))
3267 return CheckEvalInICE(E, Ctx);
3268 return ICEDiag(2, E->getLocStart());
3269 }
3270 case Expr::DeclRefExprClass:
3271 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3272 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003273 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003274 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3275
3276 // Parameter variables are never constants. Without this check,
3277 // getAnyInitializer() can find a default argument, which leads
3278 // to chaos.
3279 if (isa<ParmVarDecl>(D))
3280 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3281
3282 // C++ 7.1.5.1p2
3283 // A variable of non-volatile const-qualified integral or enumeration
3284 // type initialized by an ICE can be used in ICEs.
3285 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003286 // Look for a declaration of this variable that has an initializer.
3287 const VarDecl *ID = 0;
3288 const Expr *Init = Dcl->getAnyInitializer(ID);
3289 if (Init) {
3290 if (ID->isInitKnownICE()) {
3291 // We have already checked whether this subexpression is an
3292 // integral constant expression.
3293 if (ID->isInitICE())
3294 return NoDiag();
3295 else
3296 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3297 }
3298
3299 // It's an ICE whether or not the definition we found is
3300 // out-of-line. See DR 721 and the discussion in Clang PR
3301 // 6206 for details.
3302
3303 if (Dcl->isCheckingICE()) {
3304 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3305 }
3306
3307 Dcl->setCheckingICE();
3308 ICEDiag Result = CheckICE(Init, Ctx);
3309 // Cache the result of the ICE test.
3310 Dcl->setInitKnownICE(Result.Val == 0);
3311 return Result;
3312 }
3313 }
3314 }
3315 return ICEDiag(2, E->getLocStart());
3316 case Expr::UnaryOperatorClass: {
3317 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3318 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003319 case UO_PostInc:
3320 case UO_PostDec:
3321 case UO_PreInc:
3322 case UO_PreDec:
3323 case UO_AddrOf:
3324 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003325 // C99 6.6/3 allows increment and decrement within unevaluated
3326 // subexpressions of constant expressions, but they can never be ICEs
3327 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003328 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003329 case UO_Extension:
3330 case UO_LNot:
3331 case UO_Plus:
3332 case UO_Minus:
3333 case UO_Not:
3334 case UO_Real:
3335 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003336 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003337 }
3338
3339 // OffsetOf falls through here.
3340 }
3341 case Expr::OffsetOfExprClass: {
3342 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003343 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003344 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003345 // compliance: we should warn earlier for offsetof expressions with
3346 // array subscripts that aren't ICEs, and if the array subscripts
3347 // are ICEs, the value of the offsetof must be an integer constant.
3348 return CheckEvalInICE(E, Ctx);
3349 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003350 case Expr::UnaryExprOrTypeTraitExprClass: {
3351 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3352 if ((Exp->getKind() == UETT_SizeOf) &&
3353 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003354 return ICEDiag(2, E->getLocStart());
3355 return NoDiag();
3356 }
3357 case Expr::BinaryOperatorClass: {
3358 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3359 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003360 case BO_PtrMemD:
3361 case BO_PtrMemI:
3362 case BO_Assign:
3363 case BO_MulAssign:
3364 case BO_DivAssign:
3365 case BO_RemAssign:
3366 case BO_AddAssign:
3367 case BO_SubAssign:
3368 case BO_ShlAssign:
3369 case BO_ShrAssign:
3370 case BO_AndAssign:
3371 case BO_XorAssign:
3372 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003373 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3374 // constant expressions, but they can never be ICEs because an ICE cannot
3375 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003376 return ICEDiag(2, E->getLocStart());
3377
John McCalle3027922010-08-25 11:45:40 +00003378 case BO_Mul:
3379 case BO_Div:
3380 case BO_Rem:
3381 case BO_Add:
3382 case BO_Sub:
3383 case BO_Shl:
3384 case BO_Shr:
3385 case BO_LT:
3386 case BO_GT:
3387 case BO_LE:
3388 case BO_GE:
3389 case BO_EQ:
3390 case BO_NE:
3391 case BO_And:
3392 case BO_Xor:
3393 case BO_Or:
3394 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003395 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3396 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003397 if (Exp->getOpcode() == BO_Div ||
3398 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003399 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003400 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003401 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003402 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003403 if (REval == 0)
3404 return ICEDiag(1, E->getLocStart());
3405 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003406 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003407 if (LEval.isMinSignedValue())
3408 return ICEDiag(1, E->getLocStart());
3409 }
3410 }
3411 }
John McCalle3027922010-08-25 11:45:40 +00003412 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003413 if (Ctx.getLangOptions().C99) {
3414 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3415 // if it isn't evaluated.
3416 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3417 return ICEDiag(1, E->getLocStart());
3418 } else {
3419 // In both C89 and C++, commas in ICEs are illegal.
3420 return ICEDiag(2, E->getLocStart());
3421 }
3422 }
3423 if (LHSResult.Val >= RHSResult.Val)
3424 return LHSResult;
3425 return RHSResult;
3426 }
John McCalle3027922010-08-25 11:45:40 +00003427 case BO_LAnd:
3428 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003429 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003430
3431 // C++0x [expr.const]p2:
3432 // [...] subexpressions of logical AND (5.14), logical OR
3433 // (5.15), and condi- tional (5.16) operations that are not
3434 // evaluated are not considered.
3435 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3436 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003437 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003438 return LHSResult;
3439
3440 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003441 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003442 return LHSResult;
3443 }
3444
John McCall864e3962010-05-07 05:32:02 +00003445 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3446 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3447 // Rare case where the RHS has a comma "side-effect"; we need
3448 // to actually check the condition to see whether the side
3449 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003450 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003451 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003452 return RHSResult;
3453 return NoDiag();
3454 }
3455
3456 if (LHSResult.Val >= RHSResult.Val)
3457 return LHSResult;
3458 return RHSResult;
3459 }
3460 }
3461 }
3462 case Expr::ImplicitCastExprClass:
3463 case Expr::CStyleCastExprClass:
3464 case Expr::CXXFunctionalCastExprClass:
3465 case Expr::CXXStaticCastExprClass:
3466 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003467 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003468 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003469 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003470 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003471 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3472 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003473 switch (cast<CastExpr>(E)->getCastKind()) {
3474 case CK_LValueToRValue:
3475 case CK_NoOp:
3476 case CK_IntegralToBoolean:
3477 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003478 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003479 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003480 return ICEDiag(2, E->getLocStart());
3481 }
John McCall864e3962010-05-07 05:32:02 +00003482 }
John McCallc07a0c72011-02-17 10:25:35 +00003483 case Expr::BinaryConditionalOperatorClass: {
3484 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3485 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3486 if (CommonResult.Val == 2) return CommonResult;
3487 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3488 if (FalseResult.Val == 2) return FalseResult;
3489 if (CommonResult.Val == 1) return CommonResult;
3490 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003491 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003492 return FalseResult;
3493 }
John McCall864e3962010-05-07 05:32:02 +00003494 case Expr::ConditionalOperatorClass: {
3495 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3496 // If the condition (ignoring parens) is a __builtin_constant_p call,
3497 // then only the true side is actually considered in an integer constant
3498 // expression, and it is fully evaluated. This is an important GNU
3499 // extension. See GCC PR38377 for discussion.
3500 if (const CallExpr *CallCE
3501 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3502 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3503 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003504 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003505 !EVResult.Val.isInt()) {
3506 return ICEDiag(2, E->getLocStart());
3507 }
3508 return NoDiag();
3509 }
3510 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003511 if (CondResult.Val == 2)
3512 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003513
3514 // C++0x [expr.const]p2:
3515 // subexpressions of [...] conditional (5.16) operations that
3516 // are not evaluated are not considered
3517 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003518 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003519 : false;
3520 ICEDiag TrueResult = NoDiag();
3521 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3522 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3523 ICEDiag FalseResult = NoDiag();
3524 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3525 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3526
John McCall864e3962010-05-07 05:32:02 +00003527 if (TrueResult.Val == 2)
3528 return TrueResult;
3529 if (FalseResult.Val == 2)
3530 return FalseResult;
3531 if (CondResult.Val == 1)
3532 return CondResult;
3533 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3534 return NoDiag();
3535 // Rare case where the diagnostics depend on which side is evaluated
3536 // Note that if we get here, CondResult is 0, and at least one of
3537 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003538 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003539 return FalseResult;
3540 }
3541 return TrueResult;
3542 }
3543 case Expr::CXXDefaultArgExprClass:
3544 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3545 case Expr::ChooseExprClass: {
3546 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3547 }
3548 }
3549
3550 // Silence a GCC warning
3551 return ICEDiag(2, E->getLocStart());
3552}
3553
3554bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3555 SourceLocation *Loc, bool isEvaluated) const {
3556 ICEDiag d = CheckICE(this, Ctx);
3557 if (d.Val != 0) {
3558 if (Loc) *Loc = d.Loc;
3559 return false;
3560 }
Richard Smith11562c52011-10-28 17:51:58 +00003561 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003562 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003563 return true;
3564}