blob: 3e82c4ce8ad278fc3bb35d8acbe20c13ea8f7082 [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
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smith254a73d2011-10-28 22:34:42 +000046 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000047 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000048
Richard Smith0b0a0b62011-10-29 20:57:55 +000049 /// A core constant value. This can be the value of any constant expression,
50 /// or a pointer or reference to a non-static object or function parameter.
51 class CCValue : public APValue {
52 typedef llvm::APSInt APSInt;
53 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +000054 /// If the value is a reference or pointer into a parameter or temporary,
55 /// this is the corresponding call stack frame.
56 CallStackFrame *CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +000057 public:
Richard Smithfec09922011-11-01 16:57:24 +000058 struct GlobalValue {};
59
Richard Smith0b0a0b62011-10-29 20:57:55 +000060 CCValue() {}
61 explicit CCValue(const APSInt &I) : APValue(I) {}
62 explicit CCValue(const APFloat &F) : APValue(F) {}
63 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
64 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
65 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +000066 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
67 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F) :
68 APValue(B, O), CallFrame(F) {}
69 CCValue(const APValue &V, GlobalValue) :
70 APValue(V), CallFrame(0) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +000071
Richard Smithfec09922011-11-01 16:57:24 +000072 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +000073 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +000074 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +000075 }
76 };
77
Richard Smith254a73d2011-10-28 22:34:42 +000078 /// A stack frame in the constexpr call stack.
79 struct CallStackFrame {
80 EvalInfo &Info;
81
82 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +000083 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +000084
85 /// ParmBindings - Parameter bindings for this function call, indexed by
86 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +000087 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +000088
Richard Smith4e4c78ff2011-10-31 05:52:43 +000089 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
90 typedef MapTy::const_iterator temp_iterator;
91 /// Temporaries - Temporary lvalues materialized within this stack frame.
92 MapTy Temporaries;
93
94 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
95 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +000096 };
97
Richard Smith4e4c78ff2011-10-31 05:52:43 +000098 struct EvalInfo {
99 const ASTContext &Ctx;
100
101 /// EvalStatus - Contains information about the evaluation.
102 Expr::EvalStatus &EvalStatus;
103
104 /// CurrentCall - The top of the constexpr call stack.
105 CallStackFrame *CurrentCall;
106
107 /// NumCalls - The number of calls we've evaluated so far.
108 unsigned NumCalls;
109
110 /// CallStackDepth - The number of calls in the call stack right now.
111 unsigned CallStackDepth;
112
113 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
114 /// OpaqueValues - Values used as the common expression in a
115 /// BinaryConditionalOperator.
116 MapTy OpaqueValues;
117
118 /// BottomFrame - The frame in which evaluation started. This must be
119 /// initialized last.
120 CallStackFrame BottomFrame;
121
122
123 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
124 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
125 BottomFrame(*this, 0) {}
126
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000127 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
128 MapTy::const_iterator i = OpaqueValues.find(e);
129 if (i == OpaqueValues.end()) return 0;
130 return &i->second;
131 }
132
133 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
134 };
135
136 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000137 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000138 Info.CurrentCall = this;
139 ++Info.CallStackDepth;
140 }
141
142 CallStackFrame::~CallStackFrame() {
143 assert(Info.CurrentCall == this && "calls retired out of order");
144 --Info.CallStackDepth;
145 Info.CurrentCall = Caller;
146 }
147
John McCall93d91dc2010-05-07 17:22:02 +0000148 struct ComplexValue {
149 private:
150 bool IsInt;
151
152 public:
153 APSInt IntReal, IntImag;
154 APFloat FloatReal, FloatImag;
155
156 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
157
158 void makeComplexFloat() { IsInt = false; }
159 bool isComplexFloat() const { return !IsInt; }
160 APFloat &getComplexFloatReal() { return FloatReal; }
161 APFloat &getComplexFloatImag() { return FloatImag; }
162
163 void makeComplexInt() { IsInt = true; }
164 bool isComplexInt() const { return IsInt; }
165 APSInt &getComplexIntReal() { return IntReal; }
166 APSInt &getComplexIntImag() { return IntImag; }
167
Richard Smith0b0a0b62011-10-29 20:57:55 +0000168 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000169 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000170 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000171 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000172 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000173 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000174 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000175 assert(v.isComplexFloat() || v.isComplexInt());
176 if (v.isComplexFloat()) {
177 makeComplexFloat();
178 FloatReal = v.getComplexFloatReal();
179 FloatImag = v.getComplexFloatImag();
180 } else {
181 makeComplexInt();
182 IntReal = v.getComplexIntReal();
183 IntImag = v.getComplexIntImag();
184 }
185 }
John McCall93d91dc2010-05-07 17:22:02 +0000186 };
John McCall45d55e42010-05-07 21:00:08 +0000187
188 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000189 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000190 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000191 CallStackFrame *Frame;
John McCall45d55e42010-05-07 21:00:08 +0000192
Richard Smith8b3497e2011-10-31 01:37:14 +0000193 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000194 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000195 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000196 CallStackFrame *getLValueFrame() const { return Frame; }
John McCall45d55e42010-05-07 21:00:08 +0000197
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198 void moveInto(CCValue &V) const {
Richard Smithfec09922011-11-01 16:57:24 +0000199 V = CCValue(Base, Offset, Frame);
John McCall45d55e42010-05-07 21:00:08 +0000200 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000201 void setFrom(const CCValue &V) {
202 assert(V.isLValue());
203 Base = V.getLValueBase();
204 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000205 Frame = V.getLValueFrame();
John McCallc07a0c72011-02-17 10:25:35 +0000206 }
John McCall45d55e42010-05-07 21:00:08 +0000207 };
John McCall93d91dc2010-05-07 17:22:02 +0000208}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000209
Richard Smith0b0a0b62011-10-29 20:57:55 +0000210static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000211static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
212static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000213static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000214static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000215 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000216static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000217static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000218
219//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000220// Misc utilities
221//===----------------------------------------------------------------------===//
222
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000223static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000224 if (!E) return true;
225
226 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
227 if (isa<FunctionDecl>(DRE->getDecl()))
228 return true;
229 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
230 return VD->hasGlobalStorage();
231 return false;
232 }
233
234 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
235 return CLE->isFileScope();
236
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000237 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000238 return false;
239
John McCall95007602010-05-10 23:27:23 +0000240 return true;
241}
242
Richard Smith0b0a0b62011-10-29 20:57:55 +0000243/// Check that this core constant expression value is a valid value for a
244/// constant expression.
245static bool CheckConstantExpression(const CCValue &Value) {
246 return !Value.isLValue() || IsGlobalLValue(Value.getLValueBase());
247}
248
Richard Smith83c68212011-10-31 05:11:32 +0000249const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
250 if (!LVal.Base)
251 return 0;
252
253 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
254 return DRE->getDecl();
255
256 // FIXME: Static data members accessed via a MemberExpr are represented as
257 // that MemberExpr. We should use the Decl directly instead.
258 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
259 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
260 return ME->getMemberDecl();
261 }
262
263 return 0;
264}
265
266static bool IsLiteralLValue(const LValue &Value) {
267 return Value.Base &&
268 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000269 !isa<MemberExpr>(Value.Base) &&
270 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000271}
272
Richard Smithcecf1842011-11-01 21:06:14 +0000273static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000274 return Decl->hasAttr<WeakAttr>() ||
275 Decl->hasAttr<WeakRefAttr>() ||
276 Decl->isWeakImported();
277}
278
Richard Smithcecf1842011-11-01 21:06:14 +0000279static bool IsWeakLValue(const LValue &Value) {
280 const ValueDecl *Decl = GetLValueBaseDecl(Value);
281 return Decl && IsWeakDecl(Decl);
282}
283
Richard Smith11562c52011-10-28 17:51:58 +0000284static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000285 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000286
John McCalleb3e4f32010-05-07 21:34:32 +0000287 // A null base expression indicates a null pointer. These are always
288 // evaluatable, and they are false unless the offset is zero.
289 if (!Base) {
290 Result = !Value.Offset.isZero();
291 return true;
292 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000293
John McCall95007602010-05-10 23:27:23 +0000294 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000295 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000296 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000297
John McCalleb3e4f32010-05-07 21:34:32 +0000298 // We have a non-null base expression. These are generally known to
299 // be true, but if it'a decl-ref to a weak symbol it can be null at
300 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000301 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000302 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000303}
304
Richard Smith0b0a0b62011-10-29 20:57:55 +0000305static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000306 switch (Val.getKind()) {
307 case APValue::Uninitialized:
308 return false;
309 case APValue::Int:
310 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000311 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000312 case APValue::Float:
313 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000314 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000315 case APValue::ComplexInt:
316 Result = Val.getComplexIntReal().getBoolValue() ||
317 Val.getComplexIntImag().getBoolValue();
318 return true;
319 case APValue::ComplexFloat:
320 Result = !Val.getComplexFloatReal().isZero() ||
321 !Val.getComplexFloatImag().isZero();
322 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000323 case APValue::LValue: {
324 LValue PointerResult;
325 PointerResult.setFrom(Val);
326 return EvalPointerValueAsBool(PointerResult, Result);
327 }
Richard Smith11562c52011-10-28 17:51:58 +0000328 case APValue::Vector:
329 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000330 }
331
Richard Smith11562c52011-10-28 17:51:58 +0000332 llvm_unreachable("unknown APValue kind");
333}
334
335static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
336 EvalInfo &Info) {
337 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000338 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000339 if (!Evaluate(Val, Info, E))
340 return false;
341 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000342}
343
Mike Stump11289f42009-09-09 15:08:12 +0000344static APSInt HandleFloatToIntCast(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 unsigned DestWidth = Ctx.getIntWidth(DestType);
347 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000348 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000349
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000350 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000351 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000352 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000353 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
354 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000355}
356
Mike Stump11289f42009-09-09 15:08:12 +0000357static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000358 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000359 bool ignored;
360 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000361 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000362 APFloat::rmNearestTiesToEven, &ignored);
363 return Result;
364}
365
Mike Stump11289f42009-09-09 15:08:12 +0000366static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000367 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000368 unsigned DestWidth = Ctx.getIntWidth(DestType);
369 APSInt Result = Value;
370 // Figure out if this is a truncate, extend or noop cast.
371 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000372 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000373 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000374 return Result;
375}
376
Mike Stump11289f42009-09-09 15:08:12 +0000377static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000378 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000379
380 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
381 Result.convertFromAPInt(Value, Value.isSigned(),
382 APFloat::rmNearestTiesToEven);
383 return Result;
384}
385
Richard Smith27908702011-10-24 17:54:18 +0000386/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000387static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000388 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000389 // If this is a parameter to an active constexpr function call, perform
390 // argument substitution.
391 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000392 if (!Frame || !Frame->Arguments)
393 return false;
394 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
395 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000396 }
Richard Smith27908702011-10-24 17:54:18 +0000397
Richard Smithcecf1842011-11-01 21:06:14 +0000398 // Never evaluate the initializer of a weak variable. We can't be sure that
399 // this is the definition which will be used.
400 if (IsWeakDecl(VD))
401 return false;
402
Richard Smith27908702011-10-24 17:54:18 +0000403 const Expr *Init = VD->getAnyInitializer();
404 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000405 return false;
Richard Smith27908702011-10-24 17:54:18 +0000406
Richard Smith0b0a0b62011-10-29 20:57:55 +0000407 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000408 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000409 return !Result.isUninit();
410 }
Richard Smith27908702011-10-24 17:54:18 +0000411
412 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000413 return false;
Richard Smith27908702011-10-24 17:54:18 +0000414
415 VD->setEvaluatingValue();
416
Richard Smith0b0a0b62011-10-29 20:57:55 +0000417 Expr::EvalStatus EStatus;
418 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000419 // FIXME: The caller will need to know whether the value was a constant
420 // expression. If not, we should propagate up a diagnostic.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000421 if (!Evaluate(Result, InitInfo, Init) || !CheckConstantExpression(Result)) {
Richard Smith27908702011-10-24 17:54:18 +0000422 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000423 return false;
424 }
Richard Smith27908702011-10-24 17:54:18 +0000425
Richard Smith0b0a0b62011-10-29 20:57:55 +0000426 VD->setEvaluatedValue(Result);
427 return true;
Richard Smith27908702011-10-24 17:54:18 +0000428}
429
Richard Smith11562c52011-10-28 17:51:58 +0000430static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000431 Qualifiers Quals = T.getQualifiers();
432 return Quals.hasConst() && !Quals.hasVolatile();
433}
434
Richard Smith11562c52011-10-28 17:51:58 +0000435bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000436 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000437 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000438 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000439
440 // FIXME: Indirection through a null pointer deserves a diagnostic.
441 if (!Base)
442 return false;
443
444 // FIXME: Support accessing subobjects of objects of literal types. A simple
445 // byte offset is insufficient for C++11 semantics: we need to know how the
446 // reference was formed (which union member was named, for instance).
447 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
448 if (!LVal.Offset.isZero())
449 return false;
450
Richard Smith8b3497e2011-10-31 01:37:14 +0000451 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000452 // If the lvalue has been cast to some other type, don't try to read it.
453 // FIXME: Could simulate a bitcast here.
Richard Smith8b3497e2011-10-31 01:37:14 +0000454 if (!Info.Ctx.hasSameUnqualifiedType(Type, D->getType()))
455 return 0;
Richard Smith11562c52011-10-28 17:51:58 +0000456
Richard Smith11562c52011-10-28 17:51:58 +0000457 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
458 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000459 // expressions are constant expressions too. Inside constexpr functions,
460 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000461 // In C, such things can also be folded, although they are not ICEs.
462 //
Richard Smith254a73d2011-10-28 22:34:42 +0000463 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
464 // interpretation of C++11 suggests that volatile parameters are OK if
465 // they're never read (there's no prohibition against constructing volatile
466 // objects in constant expressions), but lvalue-to-rvalue conversions on
467 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000468 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith254a73d2011-10-28 22:34:42 +0000469 if (!VD || !(IsConstNonVolatile(VD->getType()) || isa<ParmVarDecl>(VD)) ||
Richard Smith1f1f2d82011-11-01 20:38:59 +0000470 !(Type->isIntegralOrEnumerationType() || Type->isRealFloatingType()) ||
471 !EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000472 return false;
473
Richard Smith0b0a0b62011-10-29 20:57:55 +0000474 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith11562c52011-10-28 17:51:58 +0000475 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000476
477 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
478 // conversion. This happens when the declaration and the lvalue should be
479 // considered synonymous, for instance when initializing an array of char
480 // from a string literal. Continue as if the initializer lvalue was the
481 // value we were originally given.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000482 if (!RVal.getLValueOffset().isZero())
Richard Smith11562c52011-10-28 17:51:58 +0000483 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000484 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000485 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000486 }
487
Richard Smithfec09922011-11-01 16:57:24 +0000488 // If this is a temporary expression with a nontrivial initializer, grab the
489 // value from the relevant stack frame.
490 if (Frame) {
491 RVal = Frame->Temporaries[Base];
492 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000493 }
Richard Smith11562c52011-10-28 17:51:58 +0000494
495 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
496 // initializer until now for such expressions. Such an expression can't be
497 // an ICE in C, so this only matters for fold.
498 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
499 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
500 return Evaluate(RVal, Info, CLE->getInitializer());
501 }
502
503 return false;
504}
505
Mike Stump876387b2009-10-27 22:09:17 +0000506namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000507enum EvalStmtResult {
508 /// Evaluation failed.
509 ESR_Failed,
510 /// Hit a 'return' statement.
511 ESR_Returned,
512 /// Evaluation succeeded.
513 ESR_Succeeded
514};
515}
516
517// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000518static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000519 const Stmt *S) {
520 switch (S->getStmtClass()) {
521 default:
522 return ESR_Failed;
523
524 case Stmt::NullStmtClass:
525 case Stmt::DeclStmtClass:
526 return ESR_Succeeded;
527
528 case Stmt::ReturnStmtClass:
529 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
530 return ESR_Returned;
531 return ESR_Failed;
532
533 case Stmt::CompoundStmtClass: {
534 const CompoundStmt *CS = cast<CompoundStmt>(S);
535 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
536 BE = CS->body_end(); BI != BE; ++BI) {
537 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
538 if (ESR != ESR_Succeeded)
539 return ESR;
540 }
541 return ESR_Succeeded;
542 }
543 }
544}
545
546/// Evaluate a function call.
547static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000548 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000549 // FIXME: Implement a proper call limit, along with a command-line flag.
550 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
551 return false;
552
Richard Smith0b0a0b62011-10-29 20:57:55 +0000553 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000554 // FIXME: Deal with default arguments and 'this'.
555 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
556 I != E; ++I)
557 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
558 return false;
559
560 CallStackFrame Frame(Info, ArgValues.data());
561 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
562}
563
564namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000565class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000566 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000567 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000568public:
569
Richard Smith725810a2011-10-16 21:26:27 +0000570 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000571
572 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000574 return true;
575 }
576
Peter Collingbournee9200682011-05-13 03:29:01 +0000577 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
578 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000579 return Visit(E->getResultExpr());
580 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000581 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000582 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000583 return true;
584 return false;
585 }
John McCall31168b02011-06-15 23:02:42 +0000586 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000587 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000588 return true;
589 return false;
590 }
591 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000592 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000593 return true;
594 return false;
595 }
596
Mike Stump876387b2009-10-27 22:09:17 +0000597 // We don't want to evaluate BlockExprs multiple times, as they generate
598 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000599 bool VisitBlockExpr(const BlockExpr *E) { return true; }
600 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
601 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000602 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
604 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
605 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
606 bool VisitStringLiteral(const StringLiteral *E) { return false; }
607 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
608 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000609 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000610 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000611 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000612 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000613 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
615 bool VisitBinAssign(const BinaryOperator *E) { return true; }
616 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
617 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000618 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000619 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
620 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
621 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
622 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
623 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000624 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000625 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000626 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000627 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000628 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000629
630 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000632 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
633 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000635 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000636 return false;
637 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000638
Peter Collingbournee9200682011-05-13 03:29:01 +0000639 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000640};
641
John McCallc07a0c72011-02-17 10:25:35 +0000642class OpaqueValueEvaluation {
643 EvalInfo &info;
644 OpaqueValueExpr *opaqueValue;
645
646public:
647 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
648 Expr *value)
649 : info(info), opaqueValue(opaqueValue) {
650
651 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000652 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000653 this->opaqueValue = 0;
654 return;
655 }
John McCallc07a0c72011-02-17 10:25:35 +0000656 }
657
658 bool hasError() const { return opaqueValue == 0; }
659
660 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000661 // FIXME: This will not work for recursive constexpr functions using opaque
662 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000663 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
664 }
665};
666
Mike Stump876387b2009-10-27 22:09:17 +0000667} // end anonymous namespace
668
Eli Friedman9a156e52008-11-12 09:44:48 +0000669//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000670// Generic Evaluation
671//===----------------------------------------------------------------------===//
672namespace {
673
674template <class Derived, typename RetTy=void>
675class ExprEvaluatorBase
676 : public ConstStmtVisitor<Derived, RetTy> {
677private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000678 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000679 return static_cast<Derived*>(this)->Success(V, E);
680 }
681 RetTy DerivedError(const Expr *E) {
682 return static_cast<Derived*>(this)->Error(E);
683 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000684 RetTy DerivedValueInitialization(const Expr *E) {
685 return static_cast<Derived*>(this)->ValueInitialization(E);
686 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000687
688protected:
689 EvalInfo &Info;
690 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
691 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
692
Richard Smith4ce706a2011-10-11 21:43:33 +0000693 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
694
Richard Smithfec09922011-11-01 16:57:24 +0000695 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
696 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
697 return false;
698 Result.Base = Key;
699 Result.Offset = CharUnits::Zero();
700 Result.Frame = Info.CurrentCall;
701 return true;
702 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000703public:
704 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
705
706 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000707 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000708 }
709 RetTy VisitExpr(const Expr *E) {
710 return DerivedError(E);
711 }
712
713 RetTy VisitParenExpr(const ParenExpr *E)
714 { return StmtVisitorTy::Visit(E->getSubExpr()); }
715 RetTy VisitUnaryExtension(const UnaryOperator *E)
716 { return StmtVisitorTy::Visit(E->getSubExpr()); }
717 RetTy VisitUnaryPlus(const UnaryOperator *E)
718 { return StmtVisitorTy::Visit(E->getSubExpr()); }
719 RetTy VisitChooseExpr(const ChooseExpr *E)
720 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
721 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
722 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000723 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
724 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000725
726 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
727 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
728 if (opaque.hasError())
729 return DerivedError(E);
730
731 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000732 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000733 return DerivedError(E);
734
735 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
736 }
737
738 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
739 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000740 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000741 return DerivedError(E);
742
Richard Smith11562c52011-10-28 17:51:58 +0000743 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000744 return StmtVisitorTy::Visit(EvalExpr);
745 }
746
747 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000748 const CCValue *Value = Info.getOpaqueValue(E);
749 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000750 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
751 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000752 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000753 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000754
Richard Smith254a73d2011-10-28 22:34:42 +0000755 RetTy VisitCallExpr(const CallExpr *E) {
756 const Expr *Callee = E->getCallee();
757 QualType CalleeType = Callee->getType();
758
759 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
760 // non-static member function.
761 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
762 return DerivedError(E);
763
764 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
765 return DerivedError(E);
766
Richard Smith0b0a0b62011-10-29 20:57:55 +0000767 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000768 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
769 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
770 return DerivedError(Callee);
771
772 const FunctionDecl *FD = 0;
773 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
774 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
775 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
776 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
777 if (!FD)
778 return DerivedError(Callee);
779
780 // Don't call function pointers which have been cast to some other type.
781 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
782 return DerivedError(E);
783
784 const FunctionDecl *Definition;
785 Stmt *Body = FD->getBody(Definition);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000786 CCValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000787 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
788
789 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithfec09922011-11-01 16:57:24 +0000790 HandleFunctionCall(Args, Body, Info, Result) &&
791 CheckConstantExpression(Result))
Richard Smith254a73d2011-10-28 22:34:42 +0000792 return DerivedSuccess(Result, E);
793
794 return DerivedError(E);
795 }
796
Richard Smith11562c52011-10-28 17:51:58 +0000797 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
798 return StmtVisitorTy::Visit(E->getInitializer());
799 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000800 RetTy VisitInitListExpr(const InitListExpr *E) {
801 if (Info.getLangOpts().CPlusPlus0x) {
802 if (E->getNumInits() == 0)
803 return DerivedValueInitialization(E);
804 if (E->getNumInits() == 1)
805 return StmtVisitorTy::Visit(E->getInit(0));
806 }
807 return DerivedError(E);
808 }
809 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
810 return DerivedValueInitialization(E);
811 }
812 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
813 return DerivedValueInitialization(E);
814 }
815
Richard Smith11562c52011-10-28 17:51:58 +0000816 RetTy VisitCastExpr(const CastExpr *E) {
817 switch (E->getCastKind()) {
818 default:
819 break;
820
821 case CK_NoOp:
822 return StmtVisitorTy::Visit(E->getSubExpr());
823
824 case CK_LValueToRValue: {
825 LValue LVal;
826 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000827 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000828 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
829 return DerivedSuccess(RVal, E);
830 }
831 break;
832 }
833 }
834
835 return DerivedError(E);
836 }
837
Richard Smith4a678122011-10-24 18:44:57 +0000838 /// Visit a value which is evaluated, but whose value is ignored.
839 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000840 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000841 if (!Evaluate(Scratch, Info, E))
842 Info.EvalStatus.HasSideEffects = true;
843 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000844};
845
846}
847
848//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000849// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000850//
851// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
852// function designators (in C), decl references to void objects (in C), and
853// temporaries (if building with -Wno-address-of-temporary).
854//
855// LValue evaluation produces values comprising a base expression of one of the
856// following types:
857// * DeclRefExpr
858// * MemberExpr for a static member
859// * CompoundLiteralExpr in C
860// * StringLiteral
861// * PredefinedExpr
862// * ObjCEncodeExpr
863// * AddrLabelExpr
864// * BlockExpr
865// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +0000866// plus an offset in bytes. It can also produce lvalues referring to locals. In
867// that case, the Frame will point to a stack frame, and the Expr is used as a
868// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +0000869//===----------------------------------------------------------------------===//
870namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000871class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000872 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000873 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000874 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000875
Peter Collingbournee9200682011-05-13 03:29:01 +0000876 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000877 Result.Base = E;
878 Result.Offset = CharUnits::Zero();
Richard Smithfec09922011-11-01 16:57:24 +0000879 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +0000880 return true;
881 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000882public:
Mike Stump11289f42009-09-09 15:08:12 +0000883
John McCall45d55e42010-05-07 21:00:08 +0000884 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000885 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000886
Richard Smith0b0a0b62011-10-29 20:57:55 +0000887 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000888 Result.setFrom(V);
889 return true;
890 }
891 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000892 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000893 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000894
Richard Smith11562c52011-10-28 17:51:58 +0000895 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
896
Peter Collingbournee9200682011-05-13 03:29:01 +0000897 bool VisitDeclRefExpr(const DeclRefExpr *E);
898 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000899 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000900 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
901 bool VisitMemberExpr(const MemberExpr *E);
902 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
903 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
904 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
905 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000906
Peter Collingbournee9200682011-05-13 03:29:01 +0000907 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000908 switch (E->getCastKind()) {
909 default:
Richard Smith11562c52011-10-28 17:51:58 +0000910 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000911
Eli Friedmance3e02a2011-10-11 00:13:24 +0000912 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000913 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000914
Richard Smith11562c52011-10-28 17:51:58 +0000915 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
916 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000917 }
918 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000919
Eli Friedman449fe542009-03-23 04:56:01 +0000920 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000921
Eli Friedman9a156e52008-11-12 09:44:48 +0000922};
923} // end anonymous namespace
924
Richard Smith11562c52011-10-28 17:51:58 +0000925/// Evaluate an expression as an lvalue. This can be legitimately called on
926/// expressions which are not glvalues, in a few cases:
927/// * function designators in C,
928/// * "extern void" objects,
929/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000930static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000931 assert((E->isGLValue() || E->getType()->isFunctionType() ||
932 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
933 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000934 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000935}
936
Peter Collingbournee9200682011-05-13 03:29:01 +0000937bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000938 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000939 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000940 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
941 return VisitVarDecl(E, VD);
942 return Error(E);
943}
Richard Smith733237d2011-10-24 23:14:33 +0000944
Richard Smith11562c52011-10-28 17:51:58 +0000945bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +0000946 if (!VD->getType()->isReferenceType()) {
947 if (isa<ParmVarDecl>(VD)) {
948 Result.Base = E;
949 Result.Offset = CharUnits::Zero();
950 Result.Frame = Info.CurrentCall;
951 return true;
952 }
Richard Smith11562c52011-10-28 17:51:58 +0000953 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +0000954 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000955
Richard Smith0b0a0b62011-10-29 20:57:55 +0000956 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +0000957 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +0000958 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +0000959
960 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000961}
962
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000963bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
964 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +0000965 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000966}
967
Peter Collingbournee9200682011-05-13 03:29:01 +0000968bool
969LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000970 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
971 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
972 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000973 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000974}
975
Peter Collingbournee9200682011-05-13 03:29:01 +0000976bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000977 // Handle static data members.
978 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
979 VisitIgnoredValue(E->getBase());
980 return VisitVarDecl(E, VD);
981 }
982
Richard Smith254a73d2011-10-28 22:34:42 +0000983 // Handle static member functions.
984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
985 if (MD->isStatic()) {
986 VisitIgnoredValue(E->getBase());
987 return Success(E);
988 }
989 }
990
Eli Friedman9a156e52008-11-12 09:44:48 +0000991 QualType Ty;
992 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000993 if (!EvaluatePointer(E->getBase(), Result, Info))
994 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000995 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000996 } else {
John McCall45d55e42010-05-07 21:00:08 +0000997 if (!Visit(E->getBase()))
998 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000999 Ty = E->getBase()->getType();
1000 }
1001
Peter Collingbournee9200682011-05-13 03:29:01 +00001002 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001003 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001004
Peter Collingbournee9200682011-05-13 03:29:01 +00001005 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001006 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001007 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001008
1009 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001010 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001011
Eli Friedmana3c122d2011-07-07 01:54:01 +00001012 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001013 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +00001014 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001015}
1016
Peter Collingbournee9200682011-05-13 03:29:01 +00001017bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001018 // FIXME: Deal with vectors as array subscript bases.
1019 if (E->getBase()->getType()->isVectorType())
1020 return false;
1021
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001022 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001023 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001025 APSInt Index;
1026 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001027 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001028
Ken Dyck40775002010-01-11 17:06:35 +00001029 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +00001030 Result.Offset += Index.getSExtValue() * ElementSize;
1031 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001032}
Eli Friedman9a156e52008-11-12 09:44:48 +00001033
Peter Collingbournee9200682011-05-13 03:29:01 +00001034bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001035 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001036}
1037
Eli Friedman9a156e52008-11-12 09:44:48 +00001038//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001039// Pointer Evaluation
1040//===----------------------------------------------------------------------===//
1041
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001042namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001043class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001044 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001045 LValue &Result;
1046
Peter Collingbournee9200682011-05-13 03:29:01 +00001047 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001048 Result.Base = E;
1049 Result.Offset = CharUnits::Zero();
Richard Smithfec09922011-11-01 16:57:24 +00001050 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +00001051 return true;
1052 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001053public:
Mike Stump11289f42009-09-09 15:08:12 +00001054
John McCall45d55e42010-05-07 21:00:08 +00001055 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001056 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001057
Richard Smith0b0a0b62011-10-29 20:57:55 +00001058 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001059 Result.setFrom(V);
1060 return true;
1061 }
1062 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001063 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001064 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001065 bool ValueInitialization(const Expr *E) {
1066 return Success((Expr*)0);
1067 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001068
John McCall45d55e42010-05-07 21:00:08 +00001069 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001070 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001071 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001072 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001073 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001074 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001075 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001076 bool VisitCallExpr(const CallExpr *E);
1077 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001078 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001079 return Success(E);
1080 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001081 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001082 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001083 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001084
Eli Friedman449fe542009-03-23 04:56:01 +00001085 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001086};
Chris Lattner05706e882008-07-11 18:11:29 +00001087} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001088
John McCall45d55e42010-05-07 21:00:08 +00001089static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001090 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001091 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001092}
1093
John McCall45d55e42010-05-07 21:00:08 +00001094bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001095 if (E->getOpcode() != BO_Add &&
1096 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001097 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001098
Chris Lattner05706e882008-07-11 18:11:29 +00001099 const Expr *PExp = E->getLHS();
1100 const Expr *IExp = E->getRHS();
1101 if (IExp->getType()->isPointerType())
1102 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001103
John McCall45d55e42010-05-07 21:00:08 +00001104 if (!EvaluatePointer(PExp, Result, Info))
1105 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001106
John McCall45d55e42010-05-07 21:00:08 +00001107 llvm::APSInt Offset;
1108 if (!EvaluateInteger(IExp, Offset, Info))
1109 return false;
1110 int64_t AdditionalOffset
1111 = Offset.isSigned() ? Offset.getSExtValue()
1112 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +00001113
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001114 // Compute the new offset in the appropriate width.
1115
1116 QualType PointeeType =
1117 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001118 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001119
Anders Carlssonef56fba2009-02-19 04:55:58 +00001120 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1121 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001122 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001123 else
John McCall45d55e42010-05-07 21:00:08 +00001124 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001125
John McCalle3027922010-08-25 11:45:40 +00001126 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +00001127 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +00001128 else
John McCall45d55e42010-05-07 21:00:08 +00001129 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +00001130
John McCall45d55e42010-05-07 21:00:08 +00001131 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001132}
Eli Friedman9a156e52008-11-12 09:44:48 +00001133
John McCall45d55e42010-05-07 21:00:08 +00001134bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1135 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001136}
Mike Stump11289f42009-09-09 15:08:12 +00001137
Chris Lattner05706e882008-07-11 18:11:29 +00001138
Peter Collingbournee9200682011-05-13 03:29:01 +00001139bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1140 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001141
Eli Friedman847a2bc2009-12-27 05:43:15 +00001142 switch (E->getCastKind()) {
1143 default:
1144 break;
1145
John McCalle3027922010-08-25 11:45:40 +00001146 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001147 case CK_CPointerToObjCPointerCast:
1148 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001149 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +00001150 return Visit(SubExpr);
1151
Anders Carlsson18275092010-10-31 20:41:46 +00001152 case CK_DerivedToBase:
1153 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001154 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001155 return false;
1156
1157 // Now figure out the necessary offset to add to the baseLV to get from
1158 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +00001159 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +00001160
1161 QualType Ty = E->getSubExpr()->getType();
1162 const CXXRecordDecl *DerivedDecl =
1163 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1164
1165 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1166 PathE = E->path_end(); PathI != PathE; ++PathI) {
1167 const CXXBaseSpecifier *Base = *PathI;
1168
1169 // FIXME: If the base is virtual, we'd need to determine the type of the
1170 // most derived class and we don't support that right now.
1171 if (Base->isVirtual())
1172 return false;
1173
1174 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1176
Richard Smith0b0a0b62011-10-29 20:57:55 +00001177 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001178 DerivedDecl = BaseDecl;
1179 }
1180
Anders Carlsson18275092010-10-31 20:41:46 +00001181 return true;
1182 }
1183
Richard Smith0b0a0b62011-10-29 20:57:55 +00001184 case CK_NullToPointer:
1185 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001186
John McCalle3027922010-08-25 11:45:40 +00001187 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001188 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001189 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001190 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001191
John McCall45d55e42010-05-07 21:00:08 +00001192 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001193 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1194 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001195 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001196 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001197 Result.Frame = 0;
John McCall45d55e42010-05-07 21:00:08 +00001198 return true;
1199 } else {
1200 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001201 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001202 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001203 }
1204 }
John McCalle3027922010-08-25 11:45:40 +00001205 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001206 // FIXME: Support array-to-pointer decay on array rvalues.
1207 if (!SubExpr->isGLValue())
1208 return Error(E);
1209 return EvaluateLValue(SubExpr, Result, Info);
1210
John McCalle3027922010-08-25 11:45:40 +00001211 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001212 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001213 }
1214
Richard Smith11562c52011-10-28 17:51:58 +00001215 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001216}
Chris Lattner05706e882008-07-11 18:11:29 +00001217
Peter Collingbournee9200682011-05-13 03:29:01 +00001218bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001219 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001220 Builtin::BI__builtin___CFStringMakeConstantString ||
1221 E->isBuiltinCall(Info.Ctx) ==
1222 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001223 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001224
Peter Collingbournee9200682011-05-13 03:29:01 +00001225 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001226}
Chris Lattner05706e882008-07-11 18:11:29 +00001227
1228//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001229// Vector Evaluation
1230//===----------------------------------------------------------------------===//
1231
1232namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001233 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001234 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1235 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001236 public:
Mike Stump11289f42009-09-09 15:08:12 +00001237
Richard Smith2d406342011-10-22 21:10:00 +00001238 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1239 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001240
Richard Smith2d406342011-10-22 21:10:00 +00001241 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1242 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1243 // FIXME: remove this APValue copy.
1244 Result = APValue(V.data(), V.size());
1245 return true;
1246 }
1247 bool Success(const APValue &V, const Expr *E) {
1248 Result = V;
1249 return true;
1250 }
1251 bool Error(const Expr *E) { return false; }
1252 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001253
Richard Smith2d406342011-10-22 21:10:00 +00001254 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001255 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001256 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001257 bool VisitInitListExpr(const InitListExpr *E);
1258 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001259 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001260 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001261 // shufflevector, ExtVectorElementExpr
1262 // (Note that these require implementing conversions
1263 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001264 };
1265} // end anonymous namespace
1266
1267static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001268 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001269 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001270}
1271
Richard Smith2d406342011-10-22 21:10:00 +00001272bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1273 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001274 QualType EltTy = VTy->getElementType();
1275 unsigned NElts = VTy->getNumElements();
1276 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001277
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001278 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001279 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001280
Eli Friedmanc757de22011-03-25 00:43:55 +00001281 switch (E->getCastKind()) {
1282 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001283 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001284 if (SETy->isIntegerType()) {
1285 APSInt IntResult;
1286 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001287 return Error(E);
1288 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001289 } else if (SETy->isRealFloatingType()) {
1290 APFloat F(0.0);
1291 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001292 return Error(E);
1293 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001294 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001295 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001296 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001297
1298 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001299 SmallVector<APValue, 4> Elts(NElts, Val);
1300 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001301 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001302 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001303 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001304 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001305 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001306
Eli Friedmanc757de22011-03-25 00:43:55 +00001307 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001308 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001309
Eli Friedmanc757de22011-03-25 00:43:55 +00001310 APSInt Init;
1311 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001312 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001313
Eli Friedmanc757de22011-03-25 00:43:55 +00001314 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1315 "Vectors must be composed of ints or floats");
1316
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001317 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001318 for (unsigned i = 0; i != NElts; ++i) {
1319 APSInt Tmp = Init.extOrTrunc(EltWidth);
1320
1321 if (EltTy->isIntegerType())
1322 Elts.push_back(APValue(Tmp));
1323 else
1324 Elts.push_back(APValue(APFloat(Tmp)));
1325
1326 Init >>= EltWidth;
1327 }
Richard Smith2d406342011-10-22 21:10:00 +00001328 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001329 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001330 default:
Richard Smith11562c52011-10-28 17:51:58 +00001331 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001332 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001333}
1334
Richard Smith2d406342011-10-22 21:10:00 +00001335bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001336VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001337 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001338 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001339 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001340
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001341 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001342 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001343
John McCall875679e2010-06-11 17:54:15 +00001344 // If a vector is initialized with a single element, that value
1345 // becomes every element of the vector, not just the first.
1346 // This is the behavior described in the IBM AltiVec documentation.
1347 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001348
1349 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001350 // vector (OpenCL 6.1.6).
1351 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001352 return Visit(E->getInit(0));
1353
John McCall875679e2010-06-11 17:54:15 +00001354 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001355 if (EltTy->isIntegerType()) {
1356 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001357 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001358 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001359 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001360 } else {
1361 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001362 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001363 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001364 InitValue = APValue(f);
1365 }
1366 for (unsigned i = 0; i < NumElements; i++) {
1367 Elements.push_back(InitValue);
1368 }
1369 } else {
1370 for (unsigned i = 0; i < NumElements; i++) {
1371 if (EltTy->isIntegerType()) {
1372 llvm::APSInt sInt(32);
1373 if (i < NumInits) {
1374 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001375 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001376 } else {
1377 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1378 }
1379 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001380 } else {
John McCall875679e2010-06-11 17:54:15 +00001381 llvm::APFloat f(0.0);
1382 if (i < NumInits) {
1383 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001384 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001385 } else {
1386 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1387 }
1388 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001389 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001390 }
1391 }
Richard Smith2d406342011-10-22 21:10:00 +00001392 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001393}
1394
Richard Smith2d406342011-10-22 21:10:00 +00001395bool
1396VectorExprEvaluator::ValueInitialization(const Expr *E) {
1397 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001398 QualType EltTy = VT->getElementType();
1399 APValue ZeroElement;
1400 if (EltTy->isIntegerType())
1401 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1402 else
1403 ZeroElement =
1404 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1405
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001406 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001407 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001408}
1409
Richard Smith2d406342011-10-22 21:10:00 +00001410bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001411 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001412 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001413}
1414
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001415//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001416// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001417//
1418// As a GNU extension, we support casting pointers to sufficiently-wide integer
1419// types and back in constant folding. Integer values are thus represented
1420// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001421//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001422
1423namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001424class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001425 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001426 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001427public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001428 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001429 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001430
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001431 bool Success(const llvm::APSInt &SI, const Expr *E) {
1432 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001433 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001434 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001435 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001436 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001437 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001438 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001439 return true;
1440 }
1441
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001442 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001443 assert(E->getType()->isIntegralOrEnumerationType() &&
1444 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001445 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001446 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001447 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001448 Result.getInt().setIsUnsigned(
1449 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001450 return true;
1451 }
1452
1453 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001454 assert(E->getType()->isIntegralOrEnumerationType() &&
1455 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001456 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001457 return true;
1458 }
1459
Ken Dyckdbc01912011-03-11 02:13:43 +00001460 bool Success(CharUnits Size, const Expr *E) {
1461 return Success(Size.getQuantity(), E);
1462 }
1463
1464
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001465 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001466 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001467 if (Info.EvalStatus.Diag == 0) {
1468 Info.EvalStatus.DiagLoc = L;
1469 Info.EvalStatus.Diag = D;
1470 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001471 }
Chris Lattner99415702008-07-12 00:14:42 +00001472 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001473 }
Mike Stump11289f42009-09-09 15:08:12 +00001474
Richard Smith0b0a0b62011-10-29 20:57:55 +00001475 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001476 if (V.isLValue()) {
1477 Result = V;
1478 return true;
1479 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001480 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001481 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001482 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001483 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001484 }
Mike Stump11289f42009-09-09 15:08:12 +00001485
Richard Smith4ce706a2011-10-11 21:43:33 +00001486 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1487
Peter Collingbournee9200682011-05-13 03:29:01 +00001488 //===--------------------------------------------------------------------===//
1489 // Visitor Methods
1490 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001491
Chris Lattner7174bf32008-07-12 00:38:25 +00001492 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001493 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001494 }
1495 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001496 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001497 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001498
1499 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1500 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001501 if (CheckReferencedDecl(E, E->getDecl()))
1502 return true;
1503
1504 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001505 }
1506 bool VisitMemberExpr(const MemberExpr *E) {
1507 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001508 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001509 return true;
1510 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001511
1512 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001513 }
1514
Peter Collingbournee9200682011-05-13 03:29:01 +00001515 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001516 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001517 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001518 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001519
Peter Collingbournee9200682011-05-13 03:29:01 +00001520 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001521 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001522
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001523 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001524 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Richard Smith4ce706a2011-10-11 21:43:33 +00001527 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001528 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001529 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001530 }
1531
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001532 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001533 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001534 }
1535
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001536 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1537 return Success(E->getValue(), E);
1538 }
1539
John Wiegley6242b6a2011-04-28 00:16:57 +00001540 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1541 return Success(E->getValue(), E);
1542 }
1543
John Wiegleyf9f65842011-04-25 06:54:41 +00001544 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1545 return Success(E->getValue(), E);
1546 }
1547
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001548 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001549 bool VisitUnaryImag(const UnaryOperator *E);
1550
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001551 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001552 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001553
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001554private:
Ken Dyck160146e2010-01-27 17:10:57 +00001555 CharUnits GetAlignOfExpr(const Expr *E);
1556 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001557 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001558 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001559 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001560};
Chris Lattner05706e882008-07-11 18:11:29 +00001561} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001562
Richard Smith11562c52011-10-28 17:51:58 +00001563/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1564/// produce either the integer value or a pointer.
1565///
1566/// GCC has a heinous extension which folds casts between pointer types and
1567/// pointer-sized integral types. We support this by allowing the evaluation of
1568/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1569/// Some simple arithmetic on such values is supported (they are treated much
1570/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001571static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1572 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001573 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001574 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001575}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001576
Daniel Dunbarce399542009-02-20 18:22:23 +00001577static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001578 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001579 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1580 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001581 Result = Val.getInt();
1582 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001583}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001584
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001585bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001586 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001587 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001588 // Check for signedness/width mismatches between E type and ECD value.
1589 bool SameSign = (ECD->getInitVal().isSigned()
1590 == E->getType()->isSignedIntegerOrEnumerationType());
1591 bool SameWidth = (ECD->getInitVal().getBitWidth()
1592 == Info.Ctx.getIntWidth(E->getType()));
1593 if (SameSign && SameWidth)
1594 return Success(ECD->getInitVal(), E);
1595 else {
1596 // Get rid of mismatch (otherwise Success assertions will fail)
1597 // by computing a new value matching the type of E.
1598 llvm::APSInt Val = ECD->getInitVal();
1599 if (!SameSign)
1600 Val.setIsSigned(!ECD->getInitVal().isSigned());
1601 if (!SameWidth)
1602 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1603 return Success(Val, E);
1604 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001605 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001606 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001607}
1608
Chris Lattner86ee2862008-10-06 06:40:35 +00001609/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1610/// as GCC.
1611static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1612 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001613 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001614 enum gcc_type_class {
1615 no_type_class = -1,
1616 void_type_class, integer_type_class, char_type_class,
1617 enumeral_type_class, boolean_type_class,
1618 pointer_type_class, reference_type_class, offset_type_class,
1619 real_type_class, complex_type_class,
1620 function_type_class, method_type_class,
1621 record_type_class, union_type_class,
1622 array_type_class, string_type_class,
1623 lang_type_class
1624 };
Mike Stump11289f42009-09-09 15:08:12 +00001625
1626 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001627 // ideal, however it is what gcc does.
1628 if (E->getNumArgs() == 0)
1629 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001630
Chris Lattner86ee2862008-10-06 06:40:35 +00001631 QualType ArgTy = E->getArg(0)->getType();
1632 if (ArgTy->isVoidType())
1633 return void_type_class;
1634 else if (ArgTy->isEnumeralType())
1635 return enumeral_type_class;
1636 else if (ArgTy->isBooleanType())
1637 return boolean_type_class;
1638 else if (ArgTy->isCharType())
1639 return string_type_class; // gcc doesn't appear to use char_type_class
1640 else if (ArgTy->isIntegerType())
1641 return integer_type_class;
1642 else if (ArgTy->isPointerType())
1643 return pointer_type_class;
1644 else if (ArgTy->isReferenceType())
1645 return reference_type_class;
1646 else if (ArgTy->isRealType())
1647 return real_type_class;
1648 else if (ArgTy->isComplexType())
1649 return complex_type_class;
1650 else if (ArgTy->isFunctionType())
1651 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001652 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001653 return record_type_class;
1654 else if (ArgTy->isUnionType())
1655 return union_type_class;
1656 else if (ArgTy->isArrayType())
1657 return array_type_class;
1658 else if (ArgTy->isUnionType())
1659 return union_type_class;
1660 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001661 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001662 return -1;
1663}
1664
John McCall95007602010-05-10 23:27:23 +00001665/// Retrieves the "underlying object type" of the given expression,
1666/// as used by __builtin_object_size.
1667QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1668 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1669 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1670 return VD->getType();
1671 } else if (isa<CompoundLiteralExpr>(E)) {
1672 return E->getType();
1673 }
1674
1675 return QualType();
1676}
1677
Peter Collingbournee9200682011-05-13 03:29:01 +00001678bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001679 // TODO: Perhaps we should let LLVM lower this?
1680 LValue Base;
1681 if (!EvaluatePointer(E->getArg(0), Base, Info))
1682 return false;
1683
1684 // If we can prove the base is null, lower to zero now.
1685 const Expr *LVBase = Base.getLValueBase();
1686 if (!LVBase) return Success(0, E);
1687
1688 QualType T = GetObjectType(LVBase);
1689 if (T.isNull() ||
1690 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001691 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001692 T->isVariablyModifiedType() ||
1693 T->isDependentType())
1694 return false;
1695
1696 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1697 CharUnits Offset = Base.getLValueOffset();
1698
1699 if (!Offset.isNegative() && Offset <= Size)
1700 Size -= Offset;
1701 else
1702 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001703 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001704}
1705
Peter Collingbournee9200682011-05-13 03:29:01 +00001706bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001707 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001708 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001709 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001710
1711 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001712 if (TryEvaluateBuiltinObjectSize(E))
1713 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001714
Eric Christopher99469702010-01-19 22:58:35 +00001715 // If evaluating the argument has side-effects we can't determine
1716 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001717 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001718 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001719 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001720 return Success(0, E);
1721 }
Mike Stump876387b2009-10-27 22:09:17 +00001722
Mike Stump722cedf2009-10-26 18:35:08 +00001723 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1724 }
1725
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001726 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001727 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001728
Anders Carlsson4c76e932008-11-24 04:21:33 +00001729 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001730 // __builtin_constant_p always has one operand: it returns true if that
1731 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001732 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001733
1734 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001735 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001736 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001737 return Success(Operand, E);
1738 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001739
1740 case Builtin::BI__builtin_expect:
1741 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001742
1743 case Builtin::BIstrlen:
1744 case Builtin::BI__builtin_strlen:
1745 // As an extension, we support strlen() and __builtin_strlen() as constant
1746 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001747 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001748 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1749 // The string literal may have embedded null characters. Find the first
1750 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001751 StringRef Str = S->getString();
1752 StringRef::size_type Pos = Str.find(0);
1753 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001754 Str = Str.substr(0, Pos);
1755
1756 return Success(Str.size(), E);
1757 }
1758
1759 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001760
1761 case Builtin::BI__atomic_is_lock_free: {
1762 APSInt SizeVal;
1763 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1764 return false;
1765
1766 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1767 // of two less than the maximum inline atomic width, we know it is
1768 // lock-free. If the size isn't a power of two, or greater than the
1769 // maximum alignment where we promote atomics, we know it is not lock-free
1770 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1771 // the answer can only be determined at runtime; for example, 16-byte
1772 // atomics have lock-free implementations on some, but not all,
1773 // x86-64 processors.
1774
1775 // Check power-of-two.
1776 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1777 if (!Size.isPowerOfTwo())
1778#if 0
1779 // FIXME: Suppress this folding until the ABI for the promotion width
1780 // settles.
1781 return Success(0, E);
1782#else
1783 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1784#endif
1785
1786#if 0
1787 // Check against promotion width.
1788 // FIXME: Suppress this folding until the ABI for the promotion width
1789 // settles.
1790 unsigned PromoteWidthBits =
1791 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1792 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1793 return Success(0, E);
1794#endif
1795
1796 // Check against inlining width.
1797 unsigned InlineWidthBits =
1798 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1799 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1800 return Success(1, E);
1801
1802 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1803 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001804 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001805}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001806
Richard Smith8b3497e2011-10-31 01:37:14 +00001807static bool HasSameBase(const LValue &A, const LValue &B) {
1808 if (!A.getLValueBase())
1809 return !B.getLValueBase();
1810 if (!B.getLValueBase())
1811 return false;
1812
1813 if (A.getLValueBase() != B.getLValueBase()) {
1814 const Decl *ADecl = GetLValueBaseDecl(A);
1815 if (!ADecl)
1816 return false;
1817 const Decl *BDecl = GetLValueBaseDecl(B);
1818 if (ADecl != BDecl)
1819 return false;
1820 }
1821
1822 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00001823 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00001824}
1825
Chris Lattnere13042c2008-07-11 19:10:17 +00001826bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001827 if (E->isAssignmentOp())
1828 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1829
John McCalle3027922010-08-25 11:45:40 +00001830 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001831 VisitIgnoredValue(E->getLHS());
1832 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001833 }
1834
1835 if (E->isLogicalOp()) {
1836 // These need to be handled specially because the operands aren't
1837 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001838 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001839
Richard Smith11562c52011-10-28 17:51:58 +00001840 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001841 // We were able to evaluate the LHS, see if we can get away with not
1842 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001843 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001844 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001845
Richard Smith11562c52011-10-28 17:51:58 +00001846 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001847 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001848 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001849 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001850 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001851 }
1852 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001853 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001854 // We can't evaluate the LHS; however, sometimes the result
1855 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001856 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1857 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001858 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001859 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001860 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001861
1862 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001863 }
1864 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001865 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001866
Eli Friedman5a332ea2008-11-13 06:09:17 +00001867 return false;
1868 }
1869
Anders Carlssonacc79812008-11-16 07:17:21 +00001870 QualType LHSTy = E->getLHS()->getType();
1871 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001872
1873 if (LHSTy->isAnyComplexType()) {
1874 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001875 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001876
1877 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1878 return false;
1879
1880 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1881 return false;
1882
1883 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001884 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001885 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001886 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001887 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1888
John McCalle3027922010-08-25 11:45:40 +00001889 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001890 return Success((CR_r == APFloat::cmpEqual &&
1891 CR_i == APFloat::cmpEqual), E);
1892 else {
John McCalle3027922010-08-25 11:45:40 +00001893 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001894 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001895 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001896 CR_r == APFloat::cmpLessThan ||
1897 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001898 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001899 CR_i == APFloat::cmpLessThan ||
1900 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001901 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001902 } else {
John McCalle3027922010-08-25 11:45:40 +00001903 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001904 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1905 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1906 else {
John McCalle3027922010-08-25 11:45:40 +00001907 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001908 "Invalid compex comparison.");
1909 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1910 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1911 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001912 }
1913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssonacc79812008-11-16 07:17:21 +00001915 if (LHSTy->isRealFloatingType() &&
1916 RHSTy->isRealFloatingType()) {
1917 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001918
Anders Carlssonacc79812008-11-16 07:17:21 +00001919 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1920 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001921
Anders Carlssonacc79812008-11-16 07:17:21 +00001922 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1923 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001924
Anders Carlssonacc79812008-11-16 07:17:21 +00001925 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001926
Anders Carlssonacc79812008-11-16 07:17:21 +00001927 switch (E->getOpcode()) {
1928 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001929 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001930 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001931 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001932 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001933 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001934 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001935 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001936 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001937 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001938 E);
John McCalle3027922010-08-25 11:45:40 +00001939 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001940 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001941 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001942 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001943 || CR == APFloat::cmpLessThan
1944 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001945 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
Eli Friedmana38da572009-04-28 19:17:36 +00001948 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00001949 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001950 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001951 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1952 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001953
John McCall45d55e42010-05-07 21:00:08 +00001954 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001955 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1956 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001957
Richard Smith8b3497e2011-10-31 01:37:14 +00001958 // Reject differing bases from the normal codepath; we special-case
1959 // comparisons to null.
1960 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00001961 // Inequalities and subtractions between unrelated pointers have
1962 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00001963 if (!E->isEqualityOp())
1964 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00001965 // A constant address may compare equal to the address of a symbol.
1966 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00001967 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00001968 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
1969 (!RHSValue.Base && !RHSValue.Offset.isZero()))
1970 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001971 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00001972 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00001973 // distinct. However, we do know that the address of a literal will be
1974 // non-null.
1975 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
1976 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00001977 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001978 // We can't tell whether weak symbols will end up pointing to the same
1979 // object.
1980 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00001981 return false;
Richard Smith83c68212011-10-31 05:11:32 +00001982 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00001983 // (Note that clang defaults to -fmerge-all-constants, which can
1984 // lead to inconsistent results for comparisons involving the address
1985 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00001986 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00001987 }
Eli Friedman64004332009-03-23 04:38:34 +00001988
John McCalle3027922010-08-25 11:45:40 +00001989 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001990 QualType Type = E->getLHS()->getType();
1991 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001992
Ken Dyck02990832010-01-15 12:37:54 +00001993 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001994 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001995 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001996
Ken Dyck02990832010-01-15 12:37:54 +00001997 CharUnits Diff = LHSValue.getLValueOffset() -
1998 RHSValue.getLValueOffset();
1999 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002000 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002001
2002 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2003 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2004 switch (E->getOpcode()) {
2005 default: llvm_unreachable("missing comparison operator");
2006 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2007 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2008 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2009 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2010 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2011 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002012 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002013 }
2014 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002015 if (!LHSTy->isIntegralOrEnumerationType() ||
2016 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002017 // We can't continue from here for non-integral types, and they
2018 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002019 return false;
2020 }
2021
Anders Carlsson9c181652008-07-08 14:35:21 +00002022 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002023 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002024 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002025 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002026
Richard Smith11562c52011-10-28 17:51:58 +00002027 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002028 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002029 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002030
2031 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002032 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002033 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2034 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002035 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002036 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002037 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002038 LHSVal.getLValueOffset() -= AdditionalOffset;
2039 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002040 return true;
2041 }
2042
2043 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002044 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002045 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002046 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2047 LHSVal.getInt().getZExtValue());
2048 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002049 return true;
2050 }
2051
2052 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002053 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002054 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002055
Richard Smith11562c52011-10-28 17:51:58 +00002056 APSInt &LHS = LHSVal.getInt();
2057 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002058
Anders Carlsson9c181652008-07-08 14:35:21 +00002059 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002060 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002061 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002062 case BO_Mul: return Success(LHS * RHS, E);
2063 case BO_Add: return Success(LHS + RHS, E);
2064 case BO_Sub: return Success(LHS - RHS, E);
2065 case BO_And: return Success(LHS & RHS, E);
2066 case BO_Xor: return Success(LHS ^ RHS, E);
2067 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002068 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002069 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002070 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002071 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002072 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002073 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002074 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002075 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002076 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002077 // During constant-folding, a negative shift is an opposite shift.
2078 if (RHS.isSigned() && RHS.isNegative()) {
2079 RHS = -RHS;
2080 goto shift_right;
2081 }
2082
2083 shift_left:
2084 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002085 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2086 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002087 }
John McCalle3027922010-08-25 11:45:40 +00002088 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002089 // During constant-folding, a negative shift is an opposite shift.
2090 if (RHS.isSigned() && RHS.isNegative()) {
2091 RHS = -RHS;
2092 goto shift_left;
2093 }
2094
2095 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002096 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002097 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2098 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002099 }
Mike Stump11289f42009-09-09 15:08:12 +00002100
Richard Smith11562c52011-10-28 17:51:58 +00002101 case BO_LT: return Success(LHS < RHS, E);
2102 case BO_GT: return Success(LHS > RHS, E);
2103 case BO_LE: return Success(LHS <= RHS, E);
2104 case BO_GE: return Success(LHS >= RHS, E);
2105 case BO_EQ: return Success(LHS == RHS, E);
2106 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002107 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002108}
2109
Ken Dyck160146e2010-01-27 17:10:57 +00002110CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002111 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2112 // the result is the size of the referenced type."
2113 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2114 // result shall be the alignment of the referenced type."
2115 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2116 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002117
2118 // __alignof is defined to return the preferred alignment.
2119 return Info.Ctx.toCharUnitsFromBits(
2120 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002121}
2122
Ken Dyck160146e2010-01-27 17:10:57 +00002123CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002124 E = E->IgnoreParens();
2125
2126 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002127 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002128 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002129 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2130 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002131
Chris Lattner68061312009-01-24 21:53:27 +00002132 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002133 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2134 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002135
Chris Lattner24aeeab2009-01-24 21:09:06 +00002136 return GetAlignOfType(E->getType());
2137}
2138
2139
Peter Collingbournee190dee2011-03-11 19:24:49 +00002140/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2141/// a result as the expression's type.
2142bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2143 const UnaryExprOrTypeTraitExpr *E) {
2144 switch(E->getKind()) {
2145 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002146 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002147 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002148 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002149 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002150 }
Eli Friedman64004332009-03-23 04:38:34 +00002151
Peter Collingbournee190dee2011-03-11 19:24:49 +00002152 case UETT_VecStep: {
2153 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002154
Peter Collingbournee190dee2011-03-11 19:24:49 +00002155 if (Ty->isVectorType()) {
2156 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002157
Peter Collingbournee190dee2011-03-11 19:24:49 +00002158 // The vec_step built-in functions that take a 3-component
2159 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2160 if (n == 3)
2161 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002162
Peter Collingbournee190dee2011-03-11 19:24:49 +00002163 return Success(n, E);
2164 } else
2165 return Success(1, E);
2166 }
2167
2168 case UETT_SizeOf: {
2169 QualType SrcTy = E->getTypeOfArgument();
2170 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2171 // the result is the size of the referenced type."
2172 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2173 // result shall be the alignment of the referenced type."
2174 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2175 SrcTy = Ref->getPointeeType();
2176
2177 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2178 // extension.
2179 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2180 return Success(1, E);
2181
2182 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2183 if (!SrcTy->isConstantSizeType())
2184 return false;
2185
2186 // Get information about the size.
2187 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2188 }
2189 }
2190
2191 llvm_unreachable("unknown expr/type trait");
2192 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002193}
2194
Peter Collingbournee9200682011-05-13 03:29:01 +00002195bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002196 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002197 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002198 if (n == 0)
2199 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002200 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002201 for (unsigned i = 0; i != n; ++i) {
2202 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2203 switch (ON.getKind()) {
2204 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002205 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002206 APSInt IdxResult;
2207 if (!EvaluateInteger(Idx, IdxResult, Info))
2208 return false;
2209 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2210 if (!AT)
2211 return false;
2212 CurrentType = AT->getElementType();
2213 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2214 Result += IdxResult.getSExtValue() * ElementSize;
2215 break;
2216 }
2217
2218 case OffsetOfExpr::OffsetOfNode::Field: {
2219 FieldDecl *MemberDecl = ON.getField();
2220 const RecordType *RT = CurrentType->getAs<RecordType>();
2221 if (!RT)
2222 return false;
2223 RecordDecl *RD = RT->getDecl();
2224 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002225 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002226 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002227 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002228 CurrentType = MemberDecl->getType().getNonReferenceType();
2229 break;
2230 }
2231
2232 case OffsetOfExpr::OffsetOfNode::Identifier:
2233 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002234 return false;
2235
2236 case OffsetOfExpr::OffsetOfNode::Base: {
2237 CXXBaseSpecifier *BaseSpec = ON.getBase();
2238 if (BaseSpec->isVirtual())
2239 return false;
2240
2241 // Find the layout of the class whose base we are looking into.
2242 const RecordType *RT = CurrentType->getAs<RecordType>();
2243 if (!RT)
2244 return false;
2245 RecordDecl *RD = RT->getDecl();
2246 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2247
2248 // Find the base class itself.
2249 CurrentType = BaseSpec->getType();
2250 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2251 if (!BaseRT)
2252 return false;
2253
2254 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002255 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002256 break;
2257 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002258 }
2259 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002260 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002261}
2262
Chris Lattnere13042c2008-07-11 19:10:17 +00002263bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002264 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002265 // LNot's operand isn't necessarily an integer, so we handle it specially.
2266 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002267 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002268 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002269 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002270 }
2271
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002272 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002273 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002274 return false;
2275
Richard Smith11562c52011-10-28 17:51:58 +00002276 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002277 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002278 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002279 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002280
Chris Lattnerf09ad162008-07-11 22:15:16 +00002281 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002282 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002283 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2284 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002285 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002286 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002287 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2288 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002289 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002290 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002291 // The result is just the value.
2292 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002293 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002294 if (!Val.isInt()) return false;
2295 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002296 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002297 if (!Val.isInt()) return false;
2298 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002299 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002300}
Mike Stump11289f42009-09-09 15:08:12 +00002301
Chris Lattner477c4be2008-07-12 01:15:53 +00002302/// HandleCast - This is used to evaluate implicit or explicit casts where the
2303/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002304bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2305 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002306 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002307 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002308
Eli Friedmanc757de22011-03-25 00:43:55 +00002309 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002310 case CK_BaseToDerived:
2311 case CK_DerivedToBase:
2312 case CK_UncheckedDerivedToBase:
2313 case CK_Dynamic:
2314 case CK_ToUnion:
2315 case CK_ArrayToPointerDecay:
2316 case CK_FunctionToPointerDecay:
2317 case CK_NullToPointer:
2318 case CK_NullToMemberPointer:
2319 case CK_BaseToDerivedMemberPointer:
2320 case CK_DerivedToBaseMemberPointer:
2321 case CK_ConstructorConversion:
2322 case CK_IntegralToPointer:
2323 case CK_ToVoid:
2324 case CK_VectorSplat:
2325 case CK_IntegralToFloating:
2326 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002327 case CK_CPointerToObjCPointerCast:
2328 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002329 case CK_AnyPointerToBlockPointerCast:
2330 case CK_ObjCObjectLValueCast:
2331 case CK_FloatingRealToComplex:
2332 case CK_FloatingComplexToReal:
2333 case CK_FloatingComplexCast:
2334 case CK_FloatingComplexToIntegralComplex:
2335 case CK_IntegralRealToComplex:
2336 case CK_IntegralComplexCast:
2337 case CK_IntegralComplexToFloatingComplex:
2338 llvm_unreachable("invalid cast kind for integral value");
2339
Eli Friedman9faf2f92011-03-25 19:07:11 +00002340 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002341 case CK_Dependent:
2342 case CK_GetObjCProperty:
2343 case CK_LValueBitCast:
2344 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002345 case CK_ARCProduceObject:
2346 case CK_ARCConsumeObject:
2347 case CK_ARCReclaimReturnedObject:
2348 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002349 return false;
2350
2351 case CK_LValueToRValue:
2352 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002353 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002354
2355 case CK_MemberPointerToBoolean:
2356 case CK_PointerToBoolean:
2357 case CK_IntegralToBoolean:
2358 case CK_FloatingToBoolean:
2359 case CK_FloatingComplexToBoolean:
2360 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002361 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002362 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002363 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002364 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002365 }
2366
Eli Friedmanc757de22011-03-25 00:43:55 +00002367 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002368 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002369 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002370
Eli Friedman742421e2009-02-20 01:15:07 +00002371 if (!Result.isInt()) {
2372 // Only allow casts of lvalues if they are lossless.
2373 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2374 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002375
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002376 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002377 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
Eli Friedmanc757de22011-03-25 00:43:55 +00002380 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002381 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002382 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002383 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002384
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002385 if (LV.getLValueBase()) {
2386 // Only allow based lvalue casts if they are lossless.
2387 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2388 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002389
John McCall45d55e42010-05-07 21:00:08 +00002390 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002391 return true;
2392 }
2393
Ken Dyck02990832010-01-15 12:37:54 +00002394 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2395 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002396 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002397 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002398
Eli Friedmanc757de22011-03-25 00:43:55 +00002399 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002400 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002401 if (!EvaluateComplex(SubExpr, C, Info))
2402 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002403 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002404 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002405
Eli Friedmanc757de22011-03-25 00:43:55 +00002406 case CK_FloatingToIntegral: {
2407 APFloat F(0.0);
2408 if (!EvaluateFloat(SubExpr, F, Info))
2409 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002410
Eli Friedmanc757de22011-03-25 00:43:55 +00002411 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2412 }
2413 }
Mike Stump11289f42009-09-09 15:08:12 +00002414
Eli Friedmanc757de22011-03-25 00:43:55 +00002415 llvm_unreachable("unknown cast resulting in integral value");
2416 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002417}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002418
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002419bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2420 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002421 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002422 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2423 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2424 return Success(LV.getComplexIntReal(), E);
2425 }
2426
2427 return Visit(E->getSubExpr());
2428}
2429
Eli Friedman4e7a2412009-02-27 04:45:43 +00002430bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002431 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002432 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002433 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2434 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2435 return Success(LV.getComplexIntImag(), E);
2436 }
2437
Richard Smith4a678122011-10-24 18:44:57 +00002438 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002439 return Success(0, E);
2440}
2441
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002442bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2443 return Success(E->getPackLength(), E);
2444}
2445
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002446bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2447 return Success(E->getValue(), E);
2448}
2449
Chris Lattner05706e882008-07-11 18:11:29 +00002450//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002451// Float Evaluation
2452//===----------------------------------------------------------------------===//
2453
2454namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002455class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002456 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002457 APFloat &Result;
2458public:
2459 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002460 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002461
Richard Smith0b0a0b62011-10-29 20:57:55 +00002462 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002463 Result = V.getFloat();
2464 return true;
2465 }
2466 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002467 return false;
2468 }
2469
Richard Smith4ce706a2011-10-11 21:43:33 +00002470 bool ValueInitialization(const Expr *E) {
2471 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2472 return true;
2473 }
2474
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002475 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002476
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002477 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002478 bool VisitBinaryOperator(const BinaryOperator *E);
2479 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002480 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002481
John McCallb1fb0d32010-05-07 22:08:54 +00002482 bool VisitUnaryReal(const UnaryOperator *E);
2483 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002484
John McCallb1fb0d32010-05-07 22:08:54 +00002485 // FIXME: Missing: array subscript of vector, member of vector,
2486 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002487};
2488} // end anonymous namespace
2489
2490static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002491 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002492 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002493}
2494
Jay Foad39c79802011-01-12 09:06:06 +00002495static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002496 QualType ResultTy,
2497 const Expr *Arg,
2498 bool SNaN,
2499 llvm::APFloat &Result) {
2500 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2501 if (!S) return false;
2502
2503 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2504
2505 llvm::APInt fill;
2506
2507 // Treat empty strings as if they were zero.
2508 if (S->getString().empty())
2509 fill = llvm::APInt(32, 0);
2510 else if (S->getString().getAsInteger(0, fill))
2511 return false;
2512
2513 if (SNaN)
2514 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2515 else
2516 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2517 return true;
2518}
2519
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002520bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002521 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002522 default:
2523 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2524
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002525 case Builtin::BI__builtin_huge_val:
2526 case Builtin::BI__builtin_huge_valf:
2527 case Builtin::BI__builtin_huge_vall:
2528 case Builtin::BI__builtin_inf:
2529 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002530 case Builtin::BI__builtin_infl: {
2531 const llvm::fltSemantics &Sem =
2532 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002533 Result = llvm::APFloat::getInf(Sem);
2534 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
John McCall16291492010-02-28 13:00:19 +00002537 case Builtin::BI__builtin_nans:
2538 case Builtin::BI__builtin_nansf:
2539 case Builtin::BI__builtin_nansl:
2540 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2541 true, Result);
2542
Chris Lattner0b7282e2008-10-06 06:31:58 +00002543 case Builtin::BI__builtin_nan:
2544 case Builtin::BI__builtin_nanf:
2545 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002546 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002547 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002548 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2549 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002550
2551 case Builtin::BI__builtin_fabs:
2552 case Builtin::BI__builtin_fabsf:
2553 case Builtin::BI__builtin_fabsl:
2554 if (!EvaluateFloat(E->getArg(0), Result, Info))
2555 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002557 if (Result.isNegative())
2558 Result.changeSign();
2559 return true;
2560
Mike Stump11289f42009-09-09 15:08:12 +00002561 case Builtin::BI__builtin_copysign:
2562 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002563 case Builtin::BI__builtin_copysignl: {
2564 APFloat RHS(0.);
2565 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2566 !EvaluateFloat(E->getArg(1), RHS, Info))
2567 return false;
2568 Result.copySign(RHS);
2569 return true;
2570 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002571 }
2572}
2573
John McCallb1fb0d32010-05-07 22:08:54 +00002574bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002575 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2576 ComplexValue CV;
2577 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2578 return false;
2579 Result = CV.FloatReal;
2580 return true;
2581 }
2582
2583 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002584}
2585
2586bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002587 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2588 ComplexValue CV;
2589 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2590 return false;
2591 Result = CV.FloatImag;
2592 return true;
2593 }
2594
Richard Smith4a678122011-10-24 18:44:57 +00002595 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002596 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2597 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002598 return true;
2599}
2600
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002601bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002602 switch (E->getOpcode()) {
2603 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002604 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002605 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002606 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002607 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2608 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002609 Result.changeSign();
2610 return true;
2611 }
2612}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002613
Eli Friedman24c01542008-08-22 00:06:13 +00002614bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002615 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002616 VisitIgnoredValue(E->getLHS());
2617 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002618 }
2619
Richard Smith472d4952011-10-28 23:26:52 +00002620 // We can't evaluate pointer-to-member operations or assignments.
2621 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002622 return false;
2623
Eli Friedman24c01542008-08-22 00:06:13 +00002624 // FIXME: Diagnostics? I really don't understand how the warnings
2625 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002626 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002627 if (!EvaluateFloat(E->getLHS(), Result, Info))
2628 return false;
2629 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2630 return false;
2631
2632 switch (E->getOpcode()) {
2633 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002634 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002635 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2636 return true;
John McCalle3027922010-08-25 11:45:40 +00002637 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002638 Result.add(RHS, APFloat::rmNearestTiesToEven);
2639 return true;
John McCalle3027922010-08-25 11:45:40 +00002640 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002641 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2642 return true;
John McCalle3027922010-08-25 11:45:40 +00002643 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002644 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2645 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002646 }
2647}
2648
2649bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2650 Result = E->getValue();
2651 return true;
2652}
2653
Peter Collingbournee9200682011-05-13 03:29:01 +00002654bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2655 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002656
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002657 switch (E->getCastKind()) {
2658 default:
Richard Smith11562c52011-10-28 17:51:58 +00002659 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002660
2661 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002662 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002663 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002664 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002665 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002666 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002667 return true;
2668 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002669
2670 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002671 if (!Visit(SubExpr))
2672 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002673 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2674 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002675 return true;
2676 }
John McCalld7646252010-11-14 08:17:51 +00002677
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002678 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002679 ComplexValue V;
2680 if (!EvaluateComplex(SubExpr, V, Info))
2681 return false;
2682 Result = V.getComplexFloatReal();
2683 return true;
2684 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002685 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002686
2687 return false;
2688}
2689
Eli Friedman24c01542008-08-22 00:06:13 +00002690//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002691// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002692//===----------------------------------------------------------------------===//
2693
2694namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002695class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002696 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002697 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Anders Carlsson537969c2008-11-16 20:27:53 +00002699public:
John McCall93d91dc2010-05-07 17:22:02 +00002700 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002701 : ExprEvaluatorBaseTy(info), Result(Result) {}
2702
Richard Smith0b0a0b62011-10-29 20:57:55 +00002703 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002704 Result.setFrom(V);
2705 return true;
2706 }
2707 bool Error(const Expr *E) {
2708 return false;
2709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
Anders Carlsson537969c2008-11-16 20:27:53 +00002711 //===--------------------------------------------------------------------===//
2712 // Visitor Methods
2713 //===--------------------------------------------------------------------===//
2714
Peter Collingbournee9200682011-05-13 03:29:01 +00002715 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002716
Peter Collingbournee9200682011-05-13 03:29:01 +00002717 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002718
John McCall93d91dc2010-05-07 17:22:02 +00002719 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002720 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002721 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002722};
2723} // end anonymous namespace
2724
John McCall93d91dc2010-05-07 17:22:02 +00002725static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2726 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002727 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002728 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002729}
2730
Peter Collingbournee9200682011-05-13 03:29:01 +00002731bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2732 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002733
2734 if (SubExpr->getType()->isRealFloatingType()) {
2735 Result.makeComplexFloat();
2736 APFloat &Imag = Result.FloatImag;
2737 if (!EvaluateFloat(SubExpr, Imag, Info))
2738 return false;
2739
2740 Result.FloatReal = APFloat(Imag.getSemantics());
2741 return true;
2742 } else {
2743 assert(SubExpr->getType()->isIntegerType() &&
2744 "Unexpected imaginary literal.");
2745
2746 Result.makeComplexInt();
2747 APSInt &Imag = Result.IntImag;
2748 if (!EvaluateInteger(SubExpr, Imag, Info))
2749 return false;
2750
2751 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2752 return true;
2753 }
2754}
2755
Peter Collingbournee9200682011-05-13 03:29:01 +00002756bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002757
John McCallfcef3cf2010-12-14 17:51:41 +00002758 switch (E->getCastKind()) {
2759 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002760 case CK_BaseToDerived:
2761 case CK_DerivedToBase:
2762 case CK_UncheckedDerivedToBase:
2763 case CK_Dynamic:
2764 case CK_ToUnion:
2765 case CK_ArrayToPointerDecay:
2766 case CK_FunctionToPointerDecay:
2767 case CK_NullToPointer:
2768 case CK_NullToMemberPointer:
2769 case CK_BaseToDerivedMemberPointer:
2770 case CK_DerivedToBaseMemberPointer:
2771 case CK_MemberPointerToBoolean:
2772 case CK_ConstructorConversion:
2773 case CK_IntegralToPointer:
2774 case CK_PointerToIntegral:
2775 case CK_PointerToBoolean:
2776 case CK_ToVoid:
2777 case CK_VectorSplat:
2778 case CK_IntegralCast:
2779 case CK_IntegralToBoolean:
2780 case CK_IntegralToFloating:
2781 case CK_FloatingToIntegral:
2782 case CK_FloatingToBoolean:
2783 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002784 case CK_CPointerToObjCPointerCast:
2785 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002786 case CK_AnyPointerToBlockPointerCast:
2787 case CK_ObjCObjectLValueCast:
2788 case CK_FloatingComplexToReal:
2789 case CK_FloatingComplexToBoolean:
2790 case CK_IntegralComplexToReal:
2791 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002792 case CK_ARCProduceObject:
2793 case CK_ARCConsumeObject:
2794 case CK_ARCReclaimReturnedObject:
2795 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002796 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002797
John McCallfcef3cf2010-12-14 17:51:41 +00002798 case CK_LValueToRValue:
2799 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002800 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002801
2802 case CK_Dependent:
2803 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002804 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002805 case CK_UserDefinedConversion:
2806 return false;
2807
2808 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002809 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002810 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002811 return false;
2812
John McCallfcef3cf2010-12-14 17:51:41 +00002813 Result.makeComplexFloat();
2814 Result.FloatImag = APFloat(Real.getSemantics());
2815 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002816 }
2817
John McCallfcef3cf2010-12-14 17:51:41 +00002818 case CK_FloatingComplexCast: {
2819 if (!Visit(E->getSubExpr()))
2820 return false;
2821
2822 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2823 QualType From
2824 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2825
2826 Result.FloatReal
2827 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2828 Result.FloatImag
2829 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2830 return true;
2831 }
2832
2833 case CK_FloatingComplexToIntegralComplex: {
2834 if (!Visit(E->getSubExpr()))
2835 return false;
2836
2837 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2838 QualType From
2839 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2840 Result.makeComplexInt();
2841 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2842 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2843 return true;
2844 }
2845
2846 case CK_IntegralRealToComplex: {
2847 APSInt &Real = Result.IntReal;
2848 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2849 return false;
2850
2851 Result.makeComplexInt();
2852 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2853 return true;
2854 }
2855
2856 case CK_IntegralComplexCast: {
2857 if (!Visit(E->getSubExpr()))
2858 return false;
2859
2860 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2861 QualType From
2862 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2863
2864 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2865 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2866 return true;
2867 }
2868
2869 case CK_IntegralComplexToFloatingComplex: {
2870 if (!Visit(E->getSubExpr()))
2871 return false;
2872
2873 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2874 QualType From
2875 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2876 Result.makeComplexFloat();
2877 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2878 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2879 return true;
2880 }
2881 }
2882
2883 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002884 return false;
2885}
2886
John McCall93d91dc2010-05-07 17:22:02 +00002887bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002888 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002889 VisitIgnoredValue(E->getLHS());
2890 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002891 }
John McCall93d91dc2010-05-07 17:22:02 +00002892 if (!Visit(E->getLHS()))
2893 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002894
John McCall93d91dc2010-05-07 17:22:02 +00002895 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002896 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002897 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002898
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002899 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2900 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002901 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002902 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002903 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002904 if (Result.isComplexFloat()) {
2905 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2906 APFloat::rmNearestTiesToEven);
2907 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2908 APFloat::rmNearestTiesToEven);
2909 } else {
2910 Result.getComplexIntReal() += RHS.getComplexIntReal();
2911 Result.getComplexIntImag() += RHS.getComplexIntImag();
2912 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002913 break;
John McCalle3027922010-08-25 11:45:40 +00002914 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002915 if (Result.isComplexFloat()) {
2916 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2917 APFloat::rmNearestTiesToEven);
2918 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2919 APFloat::rmNearestTiesToEven);
2920 } else {
2921 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2922 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2923 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002924 break;
John McCalle3027922010-08-25 11:45:40 +00002925 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002926 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002927 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002928 APFloat &LHS_r = LHS.getComplexFloatReal();
2929 APFloat &LHS_i = LHS.getComplexFloatImag();
2930 APFloat &RHS_r = RHS.getComplexFloatReal();
2931 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002932
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002933 APFloat Tmp = LHS_r;
2934 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2935 Result.getComplexFloatReal() = Tmp;
2936 Tmp = LHS_i;
2937 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2938 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2939
2940 Tmp = LHS_r;
2941 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2942 Result.getComplexFloatImag() = Tmp;
2943 Tmp = LHS_i;
2944 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2945 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2946 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002947 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002948 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002949 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2950 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002951 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002952 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2953 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2954 }
2955 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002956 case BO_Div:
2957 if (Result.isComplexFloat()) {
2958 ComplexValue LHS = Result;
2959 APFloat &LHS_r = LHS.getComplexFloatReal();
2960 APFloat &LHS_i = LHS.getComplexFloatImag();
2961 APFloat &RHS_r = RHS.getComplexFloatReal();
2962 APFloat &RHS_i = RHS.getComplexFloatImag();
2963 APFloat &Res_r = Result.getComplexFloatReal();
2964 APFloat &Res_i = Result.getComplexFloatImag();
2965
2966 APFloat Den = RHS_r;
2967 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2968 APFloat Tmp = RHS_i;
2969 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2970 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2971
2972 Res_r = LHS_r;
2973 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2974 Tmp = LHS_i;
2975 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2976 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2977 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2978
2979 Res_i = LHS_i;
2980 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2981 Tmp = LHS_r;
2982 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2983 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2984 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2985 } else {
2986 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2987 // FIXME: what about diagnostics?
2988 return false;
2989 }
2990 ComplexValue LHS = Result;
2991 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2992 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2993 Result.getComplexIntReal() =
2994 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2995 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2996 Result.getComplexIntImag() =
2997 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2998 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2999 }
3000 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003001 }
3002
John McCall93d91dc2010-05-07 17:22:02 +00003003 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003004}
3005
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003006bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3007 // Get the operand value into 'Result'.
3008 if (!Visit(E->getSubExpr()))
3009 return false;
3010
3011 switch (E->getOpcode()) {
3012 default:
3013 // FIXME: what about diagnostics?
3014 return false;
3015 case UO_Extension:
3016 return true;
3017 case UO_Plus:
3018 // The result is always just the subexpr.
3019 return true;
3020 case UO_Minus:
3021 if (Result.isComplexFloat()) {
3022 Result.getComplexFloatReal().changeSign();
3023 Result.getComplexFloatImag().changeSign();
3024 }
3025 else {
3026 Result.getComplexIntReal() = -Result.getComplexIntReal();
3027 Result.getComplexIntImag() = -Result.getComplexIntImag();
3028 }
3029 return true;
3030 case UO_Not:
3031 if (Result.isComplexFloat())
3032 Result.getComplexFloatImag().changeSign();
3033 else
3034 Result.getComplexIntImag() = -Result.getComplexIntImag();
3035 return true;
3036 }
3037}
3038
Anders Carlsson537969c2008-11-16 20:27:53 +00003039//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003040// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003041//===----------------------------------------------------------------------===//
3042
Richard Smith0b0a0b62011-10-29 20:57:55 +00003043static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003044 // In C, function designators are not lvalues, but we evaluate them as if they
3045 // are.
3046 if (E->isGLValue() || E->getType()->isFunctionType()) {
3047 LValue LV;
3048 if (!EvaluateLValue(E, LV, Info))
3049 return false;
3050 LV.moveInto(Result);
3051 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003052 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003053 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003054 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003055 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003056 return false;
John McCall45d55e42010-05-07 21:00:08 +00003057 } else if (E->getType()->hasPointerRepresentation()) {
3058 LValue LV;
3059 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003060 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003061 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003062 } else if (E->getType()->isRealFloatingType()) {
3063 llvm::APFloat F(0.0);
3064 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003065 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003066 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003067 } else if (E->getType()->isAnyComplexType()) {
3068 ComplexValue C;
3069 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003070 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003071 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003072 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003073 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003074
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003075 return true;
3076}
3077
Richard Smith11562c52011-10-28 17:51:58 +00003078
Richard Smith7b553f12011-10-29 00:50:52 +00003079/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003080/// any crazy technique (that has nothing to do with language standards) that
3081/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003082/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3083/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003084bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003085 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003086
Richard Smith0b0a0b62011-10-29 20:57:55 +00003087 CCValue Value;
3088 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003089 return false;
3090
3091 if (isGLValue()) {
3092 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003093 LV.setFrom(Value);
3094 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3095 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003096 }
3097
Richard Smith0b0a0b62011-10-29 20:57:55 +00003098 // Check this core constant expression is a constant expression, and if so,
3099 // slice it down to one.
3100 if (!CheckConstantExpression(Value))
3101 return false;
3102 Result.Val = Value;
3103 return true;
John McCallc07a0c72011-02-17 10:25:35 +00003104}
3105
Jay Foad39c79802011-01-12 09:06:06 +00003106bool Expr::EvaluateAsBooleanCondition(bool &Result,
3107 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003108 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003109 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003110 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003111 Result);
John McCall1be1c632010-01-05 23:42:56 +00003112}
3113
Richard Smithcaf33902011-10-10 18:28:20 +00003114bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003115 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003116 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003117 !ExprResult.Val.isInt()) {
3118 return false;
3119 }
3120 Result = ExprResult.Val.getInt();
3121 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003122}
3123
Jay Foad39c79802011-01-12 09:06:06 +00003124bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003125 EvalInfo Info(Ctx, Result);
3126
John McCall45d55e42010-05-07 21:00:08 +00003127 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003128 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003129 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003130 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003131 return true;
3132 }
3133 return false;
3134}
3135
Jay Foad39c79802011-01-12 09:06:06 +00003136bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3137 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003138 EvalInfo Info(Ctx, Result);
3139
3140 LValue LV;
Richard Smithfec09922011-11-01 16:57:24 +00003141 if (EvaluateLValue(this, LV, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003142 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003143 return true;
3144 }
3145 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003146}
3147
Richard Smith7b553f12011-10-29 00:50:52 +00003148/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3149/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003150bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003151 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003152 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003153}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003154
Jay Foad39c79802011-01-12 09:06:06 +00003155bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003156 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003157}
3158
Richard Smithcaf33902011-10-10 18:28:20 +00003159APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003160 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003161 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003162 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003163 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003164 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003165
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003166 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003167}
John McCall864e3962010-05-07 05:32:02 +00003168
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003169 bool Expr::EvalResult::isGlobalLValue() const {
3170 assert(Val.isLValue());
3171 return IsGlobalLValue(Val.getLValueBase());
3172 }
3173
3174
John McCall864e3962010-05-07 05:32:02 +00003175/// isIntegerConstantExpr - this recursive routine will test if an expression is
3176/// an integer constant expression.
3177
3178/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3179/// comma, etc
3180///
3181/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3182/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3183/// cast+dereference.
3184
3185// CheckICE - This function does the fundamental ICE checking: the returned
3186// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3187// Note that to reduce code duplication, this helper does no evaluation
3188// itself; the caller checks whether the expression is evaluatable, and
3189// in the rare cases where CheckICE actually cares about the evaluated
3190// value, it calls into Evalute.
3191//
3192// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003193// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003194// 1: This expression is not an ICE, but if it isn't evaluated, it's
3195// a legal subexpression for an ICE. This return value is used to handle
3196// the comma operator in C99 mode.
3197// 2: This expression is not an ICE, and is not a legal subexpression for one.
3198
Dan Gohman28ade552010-07-26 21:25:24 +00003199namespace {
3200
John McCall864e3962010-05-07 05:32:02 +00003201struct ICEDiag {
3202 unsigned Val;
3203 SourceLocation Loc;
3204
3205 public:
3206 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3207 ICEDiag() : Val(0) {}
3208};
3209
Dan Gohman28ade552010-07-26 21:25:24 +00003210}
3211
3212static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003213
3214static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3215 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003216 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003217 !EVResult.Val.isInt()) {
3218 return ICEDiag(2, E->getLocStart());
3219 }
3220 return NoDiag();
3221}
3222
3223static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3224 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003225 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003226 return ICEDiag(2, E->getLocStart());
3227 }
3228
3229 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003230#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003231#define STMT(Node, Base) case Expr::Node##Class:
3232#define EXPR(Node, Base)
3233#include "clang/AST/StmtNodes.inc"
3234 case Expr::PredefinedExprClass:
3235 case Expr::FloatingLiteralClass:
3236 case Expr::ImaginaryLiteralClass:
3237 case Expr::StringLiteralClass:
3238 case Expr::ArraySubscriptExprClass:
3239 case Expr::MemberExprClass:
3240 case Expr::CompoundAssignOperatorClass:
3241 case Expr::CompoundLiteralExprClass:
3242 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003243 case Expr::DesignatedInitExprClass:
3244 case Expr::ImplicitValueInitExprClass:
3245 case Expr::ParenListExprClass:
3246 case Expr::VAArgExprClass:
3247 case Expr::AddrLabelExprClass:
3248 case Expr::StmtExprClass:
3249 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003250 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003251 case Expr::CXXDynamicCastExprClass:
3252 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003253 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003254 case Expr::CXXNullPtrLiteralExprClass:
3255 case Expr::CXXThisExprClass:
3256 case Expr::CXXThrowExprClass:
3257 case Expr::CXXNewExprClass:
3258 case Expr::CXXDeleteExprClass:
3259 case Expr::CXXPseudoDestructorExprClass:
3260 case Expr::UnresolvedLookupExprClass:
3261 case Expr::DependentScopeDeclRefExprClass:
3262 case Expr::CXXConstructExprClass:
3263 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003264 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003265 case Expr::CXXTemporaryObjectExprClass:
3266 case Expr::CXXUnresolvedConstructExprClass:
3267 case Expr::CXXDependentScopeMemberExprClass:
3268 case Expr::UnresolvedMemberExprClass:
3269 case Expr::ObjCStringLiteralClass:
3270 case Expr::ObjCEncodeExprClass:
3271 case Expr::ObjCMessageExprClass:
3272 case Expr::ObjCSelectorExprClass:
3273 case Expr::ObjCProtocolExprClass:
3274 case Expr::ObjCIvarRefExprClass:
3275 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003276 case Expr::ObjCIsaExprClass:
3277 case Expr::ShuffleVectorExprClass:
3278 case Expr::BlockExprClass:
3279 case Expr::BlockDeclRefExprClass:
3280 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003281 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003282 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003283 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003284 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003285 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003286 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003287 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003288 return ICEDiag(2, E->getLocStart());
3289
Sebastian Redl12757ab2011-09-24 17:48:14 +00003290 case Expr::InitListExprClass:
3291 if (Ctx.getLangOptions().CPlusPlus0x) {
3292 const InitListExpr *ILE = cast<InitListExpr>(E);
3293 if (ILE->getNumInits() == 0)
3294 return NoDiag();
3295 if (ILE->getNumInits() == 1)
3296 return CheckICE(ILE->getInit(0), Ctx);
3297 // Fall through for more than 1 expression.
3298 }
3299 return ICEDiag(2, E->getLocStart());
3300
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003301 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003302 case Expr::GNUNullExprClass:
3303 // GCC considers the GNU __null value to be an integral constant expression.
3304 return NoDiag();
3305
John McCall7c454bb2011-07-15 05:09:51 +00003306 case Expr::SubstNonTypeTemplateParmExprClass:
3307 return
3308 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3309
John McCall864e3962010-05-07 05:32:02 +00003310 case Expr::ParenExprClass:
3311 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003312 case Expr::GenericSelectionExprClass:
3313 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003314 case Expr::IntegerLiteralClass:
3315 case Expr::CharacterLiteralClass:
3316 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003317 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003318 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003319 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003320 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003321 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003322 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003323 return NoDiag();
3324 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003325 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003326 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3327 // constant expressions, but they can never be ICEs because an ICE cannot
3328 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003329 const CallExpr *CE = cast<CallExpr>(E);
3330 if (CE->isBuiltinCall(Ctx))
3331 return CheckEvalInICE(E, Ctx);
3332 return ICEDiag(2, E->getLocStart());
3333 }
3334 case Expr::DeclRefExprClass:
3335 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3336 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003337 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003338 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3339
3340 // Parameter variables are never constants. Without this check,
3341 // getAnyInitializer() can find a default argument, which leads
3342 // to chaos.
3343 if (isa<ParmVarDecl>(D))
3344 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3345
3346 // C++ 7.1.5.1p2
3347 // A variable of non-volatile const-qualified integral or enumeration
3348 // type initialized by an ICE can be used in ICEs.
3349 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003350 // Look for a declaration of this variable that has an initializer.
3351 const VarDecl *ID = 0;
3352 const Expr *Init = Dcl->getAnyInitializer(ID);
3353 if (Init) {
3354 if (ID->isInitKnownICE()) {
3355 // We have already checked whether this subexpression is an
3356 // integral constant expression.
3357 if (ID->isInitICE())
3358 return NoDiag();
3359 else
3360 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3361 }
3362
3363 // It's an ICE whether or not the definition we found is
3364 // out-of-line. See DR 721 and the discussion in Clang PR
3365 // 6206 for details.
3366
3367 if (Dcl->isCheckingICE()) {
3368 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3369 }
3370
3371 Dcl->setCheckingICE();
3372 ICEDiag Result = CheckICE(Init, Ctx);
3373 // Cache the result of the ICE test.
3374 Dcl->setInitKnownICE(Result.Val == 0);
3375 return Result;
3376 }
3377 }
3378 }
3379 return ICEDiag(2, E->getLocStart());
3380 case Expr::UnaryOperatorClass: {
3381 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3382 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003383 case UO_PostInc:
3384 case UO_PostDec:
3385 case UO_PreInc:
3386 case UO_PreDec:
3387 case UO_AddrOf:
3388 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003389 // C99 6.6/3 allows increment and decrement within unevaluated
3390 // subexpressions of constant expressions, but they can never be ICEs
3391 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003392 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003393 case UO_Extension:
3394 case UO_LNot:
3395 case UO_Plus:
3396 case UO_Minus:
3397 case UO_Not:
3398 case UO_Real:
3399 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003400 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003401 }
3402
3403 // OffsetOf falls through here.
3404 }
3405 case Expr::OffsetOfExprClass: {
3406 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003407 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003408 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003409 // compliance: we should warn earlier for offsetof expressions with
3410 // array subscripts that aren't ICEs, and if the array subscripts
3411 // are ICEs, the value of the offsetof must be an integer constant.
3412 return CheckEvalInICE(E, Ctx);
3413 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003414 case Expr::UnaryExprOrTypeTraitExprClass: {
3415 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3416 if ((Exp->getKind() == UETT_SizeOf) &&
3417 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003418 return ICEDiag(2, E->getLocStart());
3419 return NoDiag();
3420 }
3421 case Expr::BinaryOperatorClass: {
3422 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3423 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003424 case BO_PtrMemD:
3425 case BO_PtrMemI:
3426 case BO_Assign:
3427 case BO_MulAssign:
3428 case BO_DivAssign:
3429 case BO_RemAssign:
3430 case BO_AddAssign:
3431 case BO_SubAssign:
3432 case BO_ShlAssign:
3433 case BO_ShrAssign:
3434 case BO_AndAssign:
3435 case BO_XorAssign:
3436 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003437 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3438 // constant expressions, but they can never be ICEs because an ICE cannot
3439 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003440 return ICEDiag(2, E->getLocStart());
3441
John McCalle3027922010-08-25 11:45:40 +00003442 case BO_Mul:
3443 case BO_Div:
3444 case BO_Rem:
3445 case BO_Add:
3446 case BO_Sub:
3447 case BO_Shl:
3448 case BO_Shr:
3449 case BO_LT:
3450 case BO_GT:
3451 case BO_LE:
3452 case BO_GE:
3453 case BO_EQ:
3454 case BO_NE:
3455 case BO_And:
3456 case BO_Xor:
3457 case BO_Or:
3458 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003459 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3460 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003461 if (Exp->getOpcode() == BO_Div ||
3462 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003463 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003464 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003465 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003466 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003467 if (REval == 0)
3468 return ICEDiag(1, E->getLocStart());
3469 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003470 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003471 if (LEval.isMinSignedValue())
3472 return ICEDiag(1, E->getLocStart());
3473 }
3474 }
3475 }
John McCalle3027922010-08-25 11:45:40 +00003476 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003477 if (Ctx.getLangOptions().C99) {
3478 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3479 // if it isn't evaluated.
3480 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3481 return ICEDiag(1, E->getLocStart());
3482 } else {
3483 // In both C89 and C++, commas in ICEs are illegal.
3484 return ICEDiag(2, E->getLocStart());
3485 }
3486 }
3487 if (LHSResult.Val >= RHSResult.Val)
3488 return LHSResult;
3489 return RHSResult;
3490 }
John McCalle3027922010-08-25 11:45:40 +00003491 case BO_LAnd:
3492 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003493 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003494
3495 // C++0x [expr.const]p2:
3496 // [...] subexpressions of logical AND (5.14), logical OR
3497 // (5.15), and condi- tional (5.16) operations that are not
3498 // evaluated are not considered.
3499 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3500 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003501 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003502 return LHSResult;
3503
3504 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003505 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003506 return LHSResult;
3507 }
3508
John McCall864e3962010-05-07 05:32:02 +00003509 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3510 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3511 // Rare case where the RHS has a comma "side-effect"; we need
3512 // to actually check the condition to see whether the side
3513 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003514 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003515 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003516 return RHSResult;
3517 return NoDiag();
3518 }
3519
3520 if (LHSResult.Val >= RHSResult.Val)
3521 return LHSResult;
3522 return RHSResult;
3523 }
3524 }
3525 }
3526 case Expr::ImplicitCastExprClass:
3527 case Expr::CStyleCastExprClass:
3528 case Expr::CXXFunctionalCastExprClass:
3529 case Expr::CXXStaticCastExprClass:
3530 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003531 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003532 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003533 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003534 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003535 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3536 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003537 switch (cast<CastExpr>(E)->getCastKind()) {
3538 case CK_LValueToRValue:
3539 case CK_NoOp:
3540 case CK_IntegralToBoolean:
3541 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003542 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003543 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003544 return ICEDiag(2, E->getLocStart());
3545 }
John McCall864e3962010-05-07 05:32:02 +00003546 }
John McCallc07a0c72011-02-17 10:25:35 +00003547 case Expr::BinaryConditionalOperatorClass: {
3548 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3549 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3550 if (CommonResult.Val == 2) return CommonResult;
3551 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3552 if (FalseResult.Val == 2) return FalseResult;
3553 if (CommonResult.Val == 1) return CommonResult;
3554 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003555 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003556 return FalseResult;
3557 }
John McCall864e3962010-05-07 05:32:02 +00003558 case Expr::ConditionalOperatorClass: {
3559 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3560 // If the condition (ignoring parens) is a __builtin_constant_p call,
3561 // then only the true side is actually considered in an integer constant
3562 // expression, and it is fully evaluated. This is an important GNU
3563 // extension. See GCC PR38377 for discussion.
3564 if (const CallExpr *CallCE
3565 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3566 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3567 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003568 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003569 !EVResult.Val.isInt()) {
3570 return ICEDiag(2, E->getLocStart());
3571 }
3572 return NoDiag();
3573 }
3574 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003575 if (CondResult.Val == 2)
3576 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003577
3578 // C++0x [expr.const]p2:
3579 // subexpressions of [...] conditional (5.16) operations that
3580 // are not evaluated are not considered
3581 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003582 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003583 : false;
3584 ICEDiag TrueResult = NoDiag();
3585 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3586 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3587 ICEDiag FalseResult = NoDiag();
3588 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3589 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3590
John McCall864e3962010-05-07 05:32:02 +00003591 if (TrueResult.Val == 2)
3592 return TrueResult;
3593 if (FalseResult.Val == 2)
3594 return FalseResult;
3595 if (CondResult.Val == 1)
3596 return CondResult;
3597 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3598 return NoDiag();
3599 // Rare case where the diagnostics depend on which side is evaluated
3600 // Note that if we get here, CondResult is 0, and at least one of
3601 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003602 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003603 return FalseResult;
3604 }
3605 return TrueResult;
3606 }
3607 case Expr::CXXDefaultArgExprClass:
3608 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3609 case Expr::ChooseExprClass: {
3610 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3611 }
3612 }
3613
3614 // Silence a GCC warning
3615 return ICEDiag(2, E->getLocStart());
3616}
3617
3618bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3619 SourceLocation *Loc, bool isEvaluated) const {
3620 ICEDiag d = CheckICE(this, Ctx);
3621 if (d.Val != 0) {
3622 if (Loc) *Loc = d.Loc;
3623 return false;
3624 }
Richard Smith11562c52011-10-28 17:51:58 +00003625 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003626 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003627 return true;
3628}