blob: 9c9e473f7b5af460bd0a5f3ab72d85f8cc8ed111 [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 Smith96e0c102011-11-04 02:25:55 +000049 /// A path from a glvalue to a subobject of that glvalue.
50 struct SubobjectDesignator {
51 /// True if the subobject was named in a manner not supported by C++11. Such
52 /// lvalues can still be folded, but they are not core constant expressions
53 /// and we cannot perform lvalue-to-rvalue conversions on them.
54 bool Invalid : 1;
55
56 /// Whether this designates an array element.
57 bool ArrayElement : 1;
58
59 /// Whether this designates 'one past the end' of the current subobject.
60 bool OnePastTheEnd : 1;
61
62 union PathEntry {
63 /// If the current subobject is of class type, this indicates which
64 /// subobject of that type is accessed next.
65 const Decl *BaseOrMember;
66 /// If the current subobject is of array type, this indicates which index
67 /// within that array is accessed next.
68 uint64_t Index;
69 };
70 /// The entries on the path from the glvalue to the designated subobject.
71 SmallVector<PathEntry, 8> Entries;
72
73 SubobjectDesignator() :
74 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
75
76 void setInvalid() {
77 Invalid = true;
78 Entries.clear();
79 }
80 /// Update this designator to refer to the given element within this array.
81 void addIndex(uint64_t N) {
82 if (Invalid) return;
83 if (OnePastTheEnd) {
84 setInvalid();
85 return;
86 }
87 PathEntry Entry;
88 Entry.Index = N;
89 Entries.push_back(Entry);
90 ArrayElement = true;
91 }
92 /// Update this designator to refer to the given base or member of this
93 /// object.
94 void addDecl(const Decl *D) {
95 if (Invalid) return;
96 if (OnePastTheEnd) {
97 setInvalid();
98 return;
99 }
100 PathEntry Entry;
101 Entry.BaseOrMember = D;
102 Entries.push_back(Entry);
103 ArrayElement = false;
104 }
105 /// Add N to the address of this subobject.
106 void adjustIndex(uint64_t N) {
107 if (Invalid) return;
108 if (ArrayElement) {
109 Entries.back().Index += N;
110 return;
111 }
112 if (OnePastTheEnd && N == (uint64_t)-1)
113 OnePastTheEnd = false;
114 else if (!OnePastTheEnd && N == 1)
115 OnePastTheEnd = true;
116 else if (N != 0)
117 setInvalid();
118 }
119 };
120
Richard Smith0b0a0b62011-10-29 20:57:55 +0000121 /// A core constant value. This can be the value of any constant expression,
122 /// or a pointer or reference to a non-static object or function parameter.
123 class CCValue : public APValue {
124 typedef llvm::APSInt APSInt;
125 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000126 /// If the value is a reference or pointer into a parameter or temporary,
127 /// this is the corresponding call stack frame.
128 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000129 /// If the value is a reference or pointer, this is a description of how the
130 /// subobject was specified.
131 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000132 public:
Richard Smithfec09922011-11-01 16:57:24 +0000133 struct GlobalValue {};
134
Richard Smith0b0a0b62011-10-29 20:57:55 +0000135 CCValue() {}
136 explicit CCValue(const APSInt &I) : APValue(I) {}
137 explicit CCValue(const APFloat &F) : APValue(F) {}
138 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
139 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
140 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000141 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000142 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
143 const SubobjectDesignator &D) :
144 APValue(B, O), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000145 CCValue(const APValue &V, GlobalValue) :
Richard Smith96e0c102011-11-04 02:25:55 +0000146 APValue(V), CallFrame(0), Designator() {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000147
Richard Smithfec09922011-11-01 16:57:24 +0000148 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000149 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000150 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000151 }
Richard Smith96e0c102011-11-04 02:25:55 +0000152 SubobjectDesignator &getLValueDesignator() {
153 assert(getKind() == LValue);
154 return Designator;
155 }
156 const SubobjectDesignator &getLValueDesignator() const {
157 return const_cast<CCValue*>(this)->getLValueDesignator();
158 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000159 };
160
Richard Smith254a73d2011-10-28 22:34:42 +0000161 /// A stack frame in the constexpr call stack.
162 struct CallStackFrame {
163 EvalInfo &Info;
164
165 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000166 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000167
168 /// ParmBindings - Parameter bindings for this function call, indexed by
169 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000170 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000171
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000172 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
173 typedef MapTy::const_iterator temp_iterator;
174 /// Temporaries - Temporary lvalues materialized within this stack frame.
175 MapTy Temporaries;
176
177 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
178 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000179 };
180
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000181 struct EvalInfo {
182 const ASTContext &Ctx;
183
184 /// EvalStatus - Contains information about the evaluation.
185 Expr::EvalStatus &EvalStatus;
186
187 /// CurrentCall - The top of the constexpr call stack.
188 CallStackFrame *CurrentCall;
189
190 /// NumCalls - The number of calls we've evaluated so far.
191 unsigned NumCalls;
192
193 /// CallStackDepth - The number of calls in the call stack right now.
194 unsigned CallStackDepth;
195
196 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
197 /// OpaqueValues - Values used as the common expression in a
198 /// BinaryConditionalOperator.
199 MapTy OpaqueValues;
200
201 /// BottomFrame - The frame in which evaluation started. This must be
202 /// initialized last.
203 CallStackFrame BottomFrame;
204
205
206 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
207 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
208 BottomFrame(*this, 0) {}
209
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000210 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
211 MapTy::const_iterator i = OpaqueValues.find(e);
212 if (i == OpaqueValues.end()) return 0;
213 return &i->second;
214 }
215
216 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
217 };
218
219 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smithfec09922011-11-01 16:57:24 +0000220 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000221 Info.CurrentCall = this;
222 ++Info.CallStackDepth;
223 }
224
225 CallStackFrame::~CallStackFrame() {
226 assert(Info.CurrentCall == this && "calls retired out of order");
227 --Info.CallStackDepth;
228 Info.CurrentCall = Caller;
229 }
230
John McCall93d91dc2010-05-07 17:22:02 +0000231 struct ComplexValue {
232 private:
233 bool IsInt;
234
235 public:
236 APSInt IntReal, IntImag;
237 APFloat FloatReal, FloatImag;
238
239 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
240
241 void makeComplexFloat() { IsInt = false; }
242 bool isComplexFloat() const { return !IsInt; }
243 APFloat &getComplexFloatReal() { return FloatReal; }
244 APFloat &getComplexFloatImag() { return FloatImag; }
245
246 void makeComplexInt() { IsInt = true; }
247 bool isComplexInt() const { return IsInt; }
248 APSInt &getComplexIntReal() { return IntReal; }
249 APSInt &getComplexIntImag() { return IntImag; }
250
Richard Smith0b0a0b62011-10-29 20:57:55 +0000251 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000252 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000253 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000254 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000255 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000256 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000257 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000258 assert(v.isComplexFloat() || v.isComplexInt());
259 if (v.isComplexFloat()) {
260 makeComplexFloat();
261 FloatReal = v.getComplexFloatReal();
262 FloatImag = v.getComplexFloatImag();
263 } else {
264 makeComplexInt();
265 IntReal = v.getComplexIntReal();
266 IntImag = v.getComplexIntImag();
267 }
268 }
John McCall93d91dc2010-05-07 17:22:02 +0000269 };
John McCall45d55e42010-05-07 21:00:08 +0000270
271 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000272 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000273 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000274 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000275 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000276
Richard Smith8b3497e2011-10-31 01:37:14 +0000277 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000278 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000279 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000280 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000281 SubobjectDesignator &getLValueDesignator() { return Designator; }
282 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000283
Richard Smith0b0a0b62011-10-29 20:57:55 +0000284 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000285 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000286 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000287 void setFrom(const CCValue &V) {
288 assert(V.isLValue());
289 Base = V.getLValueBase();
290 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000291 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000292 Designator = V.getLValueDesignator();
293 }
294
295 void setExpr(const Expr *E, CallStackFrame *F = 0) {
296 Base = E;
297 Offset = CharUnits::Zero();
298 Frame = F;
299 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000300 }
John McCall45d55e42010-05-07 21:00:08 +0000301 };
John McCall93d91dc2010-05-07 17:22:02 +0000302}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000303
Richard Smith0b0a0b62011-10-29 20:57:55 +0000304static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000305static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
306 const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000307static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
308static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000309static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000310static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000311 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000312static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000313static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000314
315//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000316// Misc utilities
317//===----------------------------------------------------------------------===//
318
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000319static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000320 if (!E) return true;
321
322 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
323 if (isa<FunctionDecl>(DRE->getDecl()))
324 return true;
325 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
326 return VD->hasGlobalStorage();
327 return false;
328 }
329
330 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
331 return CLE->isFileScope();
332
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smith11562c52011-10-28 17:51:58 +0000334 return false;
335
John McCall95007602010-05-10 23:27:23 +0000336 return true;
337}
338
Richard Smith0b0a0b62011-10-29 20:57:55 +0000339/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000340/// constant expression, and if it is, produce the corresponding constant value.
341static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
342 if (CCValue.isLValue() && !IsGlobalLValue(CCValue.getLValueBase()))
343 return false;
344
345 // Slice off the extra bits.
346 Value = CCValue;
347 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000348}
349
Richard Smith83c68212011-10-31 05:11:32 +0000350const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
351 if (!LVal.Base)
352 return 0;
353
354 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
355 return DRE->getDecl();
356
357 // FIXME: Static data members accessed via a MemberExpr are represented as
358 // that MemberExpr. We should use the Decl directly instead.
359 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
360 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
361 return ME->getMemberDecl();
362 }
363
364 return 0;
365}
366
367static bool IsLiteralLValue(const LValue &Value) {
368 return Value.Base &&
369 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000370 !isa<MemberExpr>(Value.Base) &&
371 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000372}
373
Richard Smithcecf1842011-11-01 21:06:14 +0000374static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000375 return Decl->hasAttr<WeakAttr>() ||
376 Decl->hasAttr<WeakRefAttr>() ||
377 Decl->isWeakImported();
378}
379
Richard Smithcecf1842011-11-01 21:06:14 +0000380static bool IsWeakLValue(const LValue &Value) {
381 const ValueDecl *Decl = GetLValueBaseDecl(Value);
382 return Decl && IsWeakDecl(Decl);
383}
384
Richard Smith11562c52011-10-28 17:51:58 +0000385static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000386 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000387
John McCalleb3e4f32010-05-07 21:34:32 +0000388 // A null base expression indicates a null pointer. These are always
389 // evaluatable, and they are false unless the offset is zero.
390 if (!Base) {
391 Result = !Value.Offset.isZero();
392 return true;
393 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000394
John McCall95007602010-05-10 23:27:23 +0000395 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000396 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000397 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000398
John McCalleb3e4f32010-05-07 21:34:32 +0000399 // We have a non-null base expression. These are generally known to
400 // be true, but if it'a decl-ref to a weak symbol it can be null at
401 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000402 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000403 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000404}
405
Richard Smith0b0a0b62011-10-29 20:57:55 +0000406static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000407 switch (Val.getKind()) {
408 case APValue::Uninitialized:
409 return false;
410 case APValue::Int:
411 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000412 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000413 case APValue::Float:
414 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000415 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000416 case APValue::ComplexInt:
417 Result = Val.getComplexIntReal().getBoolValue() ||
418 Val.getComplexIntImag().getBoolValue();
419 return true;
420 case APValue::ComplexFloat:
421 Result = !Val.getComplexFloatReal().isZero() ||
422 !Val.getComplexFloatImag().isZero();
423 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000424 case APValue::LValue: {
425 LValue PointerResult;
426 PointerResult.setFrom(Val);
427 return EvalPointerValueAsBool(PointerResult, Result);
428 }
Richard Smith11562c52011-10-28 17:51:58 +0000429 case APValue::Vector:
430 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000431 }
432
Richard Smith11562c52011-10-28 17:51:58 +0000433 llvm_unreachable("unknown APValue kind");
434}
435
436static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
437 EvalInfo &Info) {
438 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000439 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000440 if (!Evaluate(Val, Info, E))
441 return false;
442 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000443}
444
Mike Stump11289f42009-09-09 15:08:12 +0000445static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000446 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000447 unsigned DestWidth = Ctx.getIntWidth(DestType);
448 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000449 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000450
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000451 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000452 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000453 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000454 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
455 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000456}
457
Mike Stump11289f42009-09-09 15:08:12 +0000458static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000459 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000460 bool ignored;
461 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000462 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000463 APFloat::rmNearestTiesToEven, &ignored);
464 return Result;
465}
466
Mike Stump11289f42009-09-09 15:08:12 +0000467static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000468 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000469 unsigned DestWidth = Ctx.getIntWidth(DestType);
470 APSInt Result = Value;
471 // Figure out if this is a truncate, extend or noop cast.
472 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000473 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000474 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000475 return Result;
476}
477
Mike Stump11289f42009-09-09 15:08:12 +0000478static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000479 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000480
481 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
482 Result.convertFromAPInt(Value, Value.isSigned(),
483 APFloat::rmNearestTiesToEven);
484 return Result;
485}
486
Richard Smith27908702011-10-24 17:54:18 +0000487/// Try to evaluate the initializer for a variable declaration.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000488static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000489 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000490 // If this is a parameter to an active constexpr function call, perform
491 // argument substitution.
492 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000493 if (!Frame || !Frame->Arguments)
494 return false;
495 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
496 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000497 }
Richard Smith27908702011-10-24 17:54:18 +0000498
Richard Smithcecf1842011-11-01 21:06:14 +0000499 // Never evaluate the initializer of a weak variable. We can't be sure that
500 // this is the definition which will be used.
501 if (IsWeakDecl(VD))
502 return false;
503
Richard Smith27908702011-10-24 17:54:18 +0000504 const Expr *Init = VD->getAnyInitializer();
505 if (!Init)
Richard Smith0b0a0b62011-10-29 20:57:55 +0000506 return false;
Richard Smith27908702011-10-24 17:54:18 +0000507
Richard Smith0b0a0b62011-10-29 20:57:55 +0000508 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000509 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000510 return !Result.isUninit();
511 }
Richard Smith27908702011-10-24 17:54:18 +0000512
513 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000514 return false;
Richard Smith27908702011-10-24 17:54:18 +0000515
516 VD->setEvaluatingValue();
517
Richard Smith0b0a0b62011-10-29 20:57:55 +0000518 Expr::EvalStatus EStatus;
519 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith11562c52011-10-28 17:51:58 +0000520 // FIXME: The caller will need to know whether the value was a constant
521 // expression. If not, we should propagate up a diagnostic.
Richard Smithed5165f2011-11-04 05:33:44 +0000522 APValue EvalResult;
523 if (!EvaluateConstantExpression(EvalResult, InitInfo, Init)) {
Richard Smith27908702011-10-24 17:54:18 +0000524 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000525 return false;
526 }
Richard Smith27908702011-10-24 17:54:18 +0000527
Richard Smithed5165f2011-11-04 05:33:44 +0000528 VD->setEvaluatedValue(EvalResult);
529 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000530 return true;
Richard Smith27908702011-10-24 17:54:18 +0000531}
532
Richard Smith11562c52011-10-28 17:51:58 +0000533static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000534 Qualifiers Quals = T.getQualifiers();
535 return Quals.hasConst() && !Quals.hasVolatile();
536}
537
Richard Smith11562c52011-10-28 17:51:58 +0000538bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000539 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000540 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000541 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000542
543 // FIXME: Indirection through a null pointer deserves a diagnostic.
544 if (!Base)
545 return false;
546
Richard Smith8b3497e2011-10-31 01:37:14 +0000547 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000548 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
549 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000550 // expressions are constant expressions too. Inside constexpr functions,
551 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000552 // In C, such things can also be folded, although they are not ICEs.
553 //
Richard Smith254a73d2011-10-28 22:34:42 +0000554 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
555 // interpretation of C++11 suggests that volatile parameters are OK if
556 // they're never read (there's no prohibition against constructing volatile
557 // objects in constant expressions), but lvalue-to-rvalue conversions on
558 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000559 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000560 QualType VT = VD->getType();
561 if (!VD)
562 return false;
563 if (!isa<ParmVarDecl>(VD)) {
564 if (!IsConstNonVolatile(VT))
565 return false;
566 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType())
567 return false;
568 }
569 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000570 return false;
571
Richard Smith0b0a0b62011-10-29 20:57:55 +0000572 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smith96e0c102011-11-04 02:25:55 +0000573 // If the lvalue refers to a subobject or has been cast to some other
574 // type, don't use it.
575 return LVal.Offset.isZero() &&
576 Info.Ctx.hasSameUnqualifiedType(Type, VT);
Richard Smith11562c52011-10-28 17:51:58 +0000577
578 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
579 // conversion. This happens when the declaration and the lvalue should be
580 // considered synonymous, for instance when initializing an array of char
581 // from a string literal. Continue as if the initializer lvalue was the
582 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000583 assert(RVal.getLValueOffset().isZero() &&
584 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000585 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000586 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000587 }
588
Richard Smith96e0c102011-11-04 02:25:55 +0000589 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
590 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
591 const SubobjectDesignator &Designator = LVal.Designator;
592 if (Designator.Invalid || Designator.Entries.size() != 1)
593 return false;
594
595 assert(Type->isIntegerType() && "string element not integer type");
596 uint64_t Index = Designator.Entries[0].Index;
597 if (Index > S->getLength())
598 return false;
599 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
600 Type->isUnsignedIntegerType());
601 if (Index < S->getLength())
602 Value = S->getCodeUnit(Index);
603 RVal = CCValue(Value);
604 return true;
605 }
606
607 // FIXME: Support accessing subobjects of objects of literal types. A simple
608 // byte offset is insufficient for C++11 semantics: we need to know how the
609 // reference was formed (which union member was named, for instance).
610
611 // Beyond this point, we don't support accessing subobjects.
612 if (!LVal.Offset.isZero() ||
613 !Info.Ctx.hasSameUnqualifiedType(Type, Base->getType()))
614 return false;
615
Richard Smithfec09922011-11-01 16:57:24 +0000616 // If this is a temporary expression with a nontrivial initializer, grab the
617 // value from the relevant stack frame.
618 if (Frame) {
619 RVal = Frame->Temporaries[Base];
620 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000621 }
Richard Smith11562c52011-10-28 17:51:58 +0000622
623 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
624 // initializer until now for such expressions. Such an expression can't be
625 // an ICE in C, so this only matters for fold.
626 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
627 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
628 return Evaluate(RVal, Info, CLE->getInitializer());
629 }
630
631 return false;
632}
633
Mike Stump876387b2009-10-27 22:09:17 +0000634namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000635enum EvalStmtResult {
636 /// Evaluation failed.
637 ESR_Failed,
638 /// Hit a 'return' statement.
639 ESR_Returned,
640 /// Evaluation succeeded.
641 ESR_Succeeded
642};
643}
644
645// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000646static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000647 const Stmt *S) {
648 switch (S->getStmtClass()) {
649 default:
650 return ESR_Failed;
651
652 case Stmt::NullStmtClass:
653 case Stmt::DeclStmtClass:
654 return ESR_Succeeded;
655
656 case Stmt::ReturnStmtClass:
657 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
658 return ESR_Returned;
659 return ESR_Failed;
660
661 case Stmt::CompoundStmtClass: {
662 const CompoundStmt *CS = cast<CompoundStmt>(S);
663 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
664 BE = CS->body_end(); BI != BE; ++BI) {
665 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
666 if (ESR != ESR_Succeeded)
667 return ESR;
668 }
669 return ESR_Succeeded;
670 }
671 }
672}
673
674/// Evaluate a function call.
675static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith0b0a0b62011-10-29 20:57:55 +0000676 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000677 // FIXME: Implement a proper call limit, along with a command-line flag.
678 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
679 return false;
680
Richard Smith0b0a0b62011-10-29 20:57:55 +0000681 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smith254a73d2011-10-28 22:34:42 +0000682 // FIXME: Deal with default arguments and 'this'.
683 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
684 I != E; ++I)
685 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
686 return false;
687
688 CallStackFrame Frame(Info, ArgValues.data());
689 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
690}
691
692namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000693class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000694 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000695 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000696public:
697
Richard Smith725810a2011-10-16 21:26:27 +0000698 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000699
700 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000701 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000702 return true;
703 }
704
Peter Collingbournee9200682011-05-13 03:29:01 +0000705 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
706 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000707 return Visit(E->getResultExpr());
708 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000709 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000710 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000711 return true;
712 return false;
713 }
John McCall31168b02011-06-15 23:02:42 +0000714 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000715 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000716 return true;
717 return false;
718 }
719 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000720 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000721 return true;
722 return false;
723 }
724
Mike Stump876387b2009-10-27 22:09:17 +0000725 // We don't want to evaluate BlockExprs multiple times, as they generate
726 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000727 bool VisitBlockExpr(const BlockExpr *E) { return true; }
728 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
729 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000730 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000731 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
732 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
733 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
734 bool VisitStringLiteral(const StringLiteral *E) { return false; }
735 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
736 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000737 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000738 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000739 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000740 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000741 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000742 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
743 bool VisitBinAssign(const BinaryOperator *E) { return true; }
744 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
745 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000746 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000747 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
748 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
749 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
750 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
751 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000752 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000753 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000754 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000755 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000756 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000757
758 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000759 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000760 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
761 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000762 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000763 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000764 return false;
765 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000766
Peter Collingbournee9200682011-05-13 03:29:01 +0000767 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000768};
769
John McCallc07a0c72011-02-17 10:25:35 +0000770class OpaqueValueEvaluation {
771 EvalInfo &info;
772 OpaqueValueExpr *opaqueValue;
773
774public:
775 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
776 Expr *value)
777 : info(info), opaqueValue(opaqueValue) {
778
779 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000780 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000781 this->opaqueValue = 0;
782 return;
783 }
John McCallc07a0c72011-02-17 10:25:35 +0000784 }
785
786 bool hasError() const { return opaqueValue == 0; }
787
788 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000789 // FIXME: This will not work for recursive constexpr functions using opaque
790 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000791 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
792 }
793};
794
Mike Stump876387b2009-10-27 22:09:17 +0000795} // end anonymous namespace
796
Eli Friedman9a156e52008-11-12 09:44:48 +0000797//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000798// Generic Evaluation
799//===----------------------------------------------------------------------===//
800namespace {
801
802template <class Derived, typename RetTy=void>
803class ExprEvaluatorBase
804 : public ConstStmtVisitor<Derived, RetTy> {
805private:
Richard Smith0b0a0b62011-10-29 20:57:55 +0000806 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000807 return static_cast<Derived*>(this)->Success(V, E);
808 }
809 RetTy DerivedError(const Expr *E) {
810 return static_cast<Derived*>(this)->Error(E);
811 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000812 RetTy DerivedValueInitialization(const Expr *E) {
813 return static_cast<Derived*>(this)->ValueInitialization(E);
814 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000815
816protected:
817 EvalInfo &Info;
818 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
819 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
820
Richard Smith4ce706a2011-10-11 21:43:33 +0000821 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
822
Richard Smithfec09922011-11-01 16:57:24 +0000823 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
824 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
825 return false;
Richard Smith96e0c102011-11-04 02:25:55 +0000826 Result.setExpr(Key, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +0000827 return true;
828 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000829public:
830 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
831
832 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000833 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000834 }
835 RetTy VisitExpr(const Expr *E) {
836 return DerivedError(E);
837 }
838
839 RetTy VisitParenExpr(const ParenExpr *E)
840 { return StmtVisitorTy::Visit(E->getSubExpr()); }
841 RetTy VisitUnaryExtension(const UnaryOperator *E)
842 { return StmtVisitorTy::Visit(E->getSubExpr()); }
843 RetTy VisitUnaryPlus(const UnaryOperator *E)
844 { return StmtVisitorTy::Visit(E->getSubExpr()); }
845 RetTy VisitChooseExpr(const ChooseExpr *E)
846 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
847 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
848 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000849 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
850 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000851
852 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
853 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
854 if (opaque.hasError())
855 return DerivedError(E);
856
857 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000858 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000859 return DerivedError(E);
860
861 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
862 }
863
864 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
865 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000866 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000867 return DerivedError(E);
868
Richard Smith11562c52011-10-28 17:51:58 +0000869 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000870 return StmtVisitorTy::Visit(EvalExpr);
871 }
872
873 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000874 const CCValue *Value = Info.getOpaqueValue(E);
875 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +0000876 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
877 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +0000878 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000879 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000880
Richard Smith254a73d2011-10-28 22:34:42 +0000881 RetTy VisitCallExpr(const CallExpr *E) {
882 const Expr *Callee = E->getCallee();
883 QualType CalleeType = Callee->getType();
884
885 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
886 // non-static member function.
887 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
888 return DerivedError(E);
889
890 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
891 return DerivedError(E);
892
Richard Smith0b0a0b62011-10-29 20:57:55 +0000893 CCValue Call;
Richard Smith254a73d2011-10-28 22:34:42 +0000894 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
895 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
896 return DerivedError(Callee);
897
898 const FunctionDecl *FD = 0;
899 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
900 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
901 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
902 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
903 if (!FD)
904 return DerivedError(Callee);
905
906 // Don't call function pointers which have been cast to some other type.
907 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
908 return DerivedError(E);
909
910 const FunctionDecl *Definition;
911 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +0000912 CCValue CCResult;
913 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +0000914 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
915
916 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smithed5165f2011-11-04 05:33:44 +0000917 HandleFunctionCall(Args, Body, Info, CCResult) &&
918 CheckConstantExpression(CCResult, Result))
919 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +0000920
921 return DerivedError(E);
922 }
923
Richard Smith11562c52011-10-28 17:51:58 +0000924 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
925 return StmtVisitorTy::Visit(E->getInitializer());
926 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000927 RetTy VisitInitListExpr(const InitListExpr *E) {
928 if (Info.getLangOpts().CPlusPlus0x) {
929 if (E->getNumInits() == 0)
930 return DerivedValueInitialization(E);
931 if (E->getNumInits() == 1)
932 return StmtVisitorTy::Visit(E->getInit(0));
933 }
934 return DerivedError(E);
935 }
936 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
937 return DerivedValueInitialization(E);
938 }
939 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
940 return DerivedValueInitialization(E);
941 }
942
Richard Smith11562c52011-10-28 17:51:58 +0000943 RetTy VisitCastExpr(const CastExpr *E) {
944 switch (E->getCastKind()) {
945 default:
946 break;
947
948 case CK_NoOp:
949 return StmtVisitorTy::Visit(E->getSubExpr());
950
951 case CK_LValueToRValue: {
952 LValue LVal;
953 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000954 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +0000955 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
956 return DerivedSuccess(RVal, E);
957 }
958 break;
959 }
960 }
961
962 return DerivedError(E);
963 }
964
Richard Smith4a678122011-10-24 18:44:57 +0000965 /// Visit a value which is evaluated, but whose value is ignored.
966 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000967 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +0000968 if (!Evaluate(Scratch, Info, E))
969 Info.EvalStatus.HasSideEffects = true;
970 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000971};
972
973}
974
975//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000976// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000977//
978// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
979// function designators (in C), decl references to void objects (in C), and
980// temporaries (if building with -Wno-address-of-temporary).
981//
982// LValue evaluation produces values comprising a base expression of one of the
983// following types:
984// * DeclRefExpr
985// * MemberExpr for a static member
986// * CompoundLiteralExpr in C
987// * StringLiteral
988// * PredefinedExpr
989// * ObjCEncodeExpr
990// * AddrLabelExpr
991// * BlockExpr
992// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +0000993// plus an offset in bytes. It can also produce lvalues referring to locals. In
994// that case, the Frame will point to a stack frame, and the Expr is used as a
995// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +0000996//===----------------------------------------------------------------------===//
997namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000998class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000999 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001000 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001001 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +00001002
Peter Collingbournee9200682011-05-13 03:29:01 +00001003 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001004 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001005 return true;
1006 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001007public:
Mike Stump11289f42009-09-09 15:08:12 +00001008
John McCall45d55e42010-05-07 21:00:08 +00001009 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001010 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001011
Richard Smith0b0a0b62011-10-29 20:57:55 +00001012 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001013 Result.setFrom(V);
1014 return true;
1015 }
1016 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001017 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001018 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001019
Richard Smith11562c52011-10-28 17:51:58 +00001020 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1021
Peter Collingbournee9200682011-05-13 03:29:01 +00001022 bool VisitDeclRefExpr(const DeclRefExpr *E);
1023 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001024 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001025 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1026 bool VisitMemberExpr(const MemberExpr *E);
1027 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1028 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1029 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1030 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001031
Peter Collingbournee9200682011-05-13 03:29:01 +00001032 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001033 switch (E->getCastKind()) {
1034 default:
Richard Smith11562c52011-10-28 17:51:58 +00001035 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001036
Eli Friedmance3e02a2011-10-11 00:13:24 +00001037 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001038 if (!Visit(E->getSubExpr()))
1039 return false;
1040 Result.Designator.setInvalid();
1041 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001042
Richard Smith11562c52011-10-28 17:51:58 +00001043 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1044 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +00001045 }
1046 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001047
Eli Friedman449fe542009-03-23 04:56:01 +00001048 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001049
Eli Friedman9a156e52008-11-12 09:44:48 +00001050};
1051} // end anonymous namespace
1052
Richard Smith11562c52011-10-28 17:51:58 +00001053/// Evaluate an expression as an lvalue. This can be legitimately called on
1054/// expressions which are not glvalues, in a few cases:
1055/// * function designators in C,
1056/// * "extern void" objects,
1057/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001058static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001059 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1060 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1061 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001062 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001063}
1064
Peter Collingbournee9200682011-05-13 03:29:01 +00001065bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001066 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001067 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001068 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1069 return VisitVarDecl(E, VD);
1070 return Error(E);
1071}
Richard Smith733237d2011-10-24 23:14:33 +00001072
Richard Smith11562c52011-10-28 17:51:58 +00001073bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001074 if (!VD->getType()->isReferenceType()) {
1075 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001076 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001077 return true;
1078 }
Richard Smith11562c52011-10-28 17:51:58 +00001079 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001080 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001081
Richard Smith0b0a0b62011-10-29 20:57:55 +00001082 CCValue V;
Richard Smithfec09922011-11-01 16:57:24 +00001083 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001084 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001085
1086 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001087}
1088
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001089bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1090 const MaterializeTemporaryExpr *E) {
Richard Smithfec09922011-11-01 16:57:24 +00001091 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001092}
1093
Peter Collingbournee9200682011-05-13 03:29:01 +00001094bool
1095LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001096 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1097 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1098 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001099 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001100}
1101
Peter Collingbournee9200682011-05-13 03:29:01 +00001102bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001103 // Handle static data members.
1104 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1105 VisitIgnoredValue(E->getBase());
1106 return VisitVarDecl(E, VD);
1107 }
1108
Richard Smith254a73d2011-10-28 22:34:42 +00001109 // Handle static member functions.
1110 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1111 if (MD->isStatic()) {
1112 VisitIgnoredValue(E->getBase());
1113 return Success(E);
1114 }
1115 }
1116
Eli Friedman9a156e52008-11-12 09:44:48 +00001117 QualType Ty;
1118 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001119 if (!EvaluatePointer(E->getBase(), Result, Info))
1120 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001121 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001122 } else {
John McCall45d55e42010-05-07 21:00:08 +00001123 if (!Visit(E->getBase()))
1124 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001125 Ty = E->getBase()->getType();
1126 }
1127
Peter Collingbournee9200682011-05-13 03:29:01 +00001128 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +00001129 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001130
Peter Collingbournee9200682011-05-13 03:29:01 +00001131 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001132 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +00001133 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001134
1135 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +00001136 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001137
Eli Friedmana3c122d2011-07-07 01:54:01 +00001138 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001139 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith96e0c102011-11-04 02:25:55 +00001140 Result.Designator.addDecl(FD);
John McCall45d55e42010-05-07 21:00:08 +00001141 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001142}
1143
Peter Collingbournee9200682011-05-13 03:29:01 +00001144bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001145 // FIXME: Deal with vectors as array subscript bases.
1146 if (E->getBase()->getType()->isVectorType())
1147 return false;
1148
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001149 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001150 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001151
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001152 APSInt Index;
1153 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001154 return false;
Richard Smith96e0c102011-11-04 02:25:55 +00001155 uint64_t IndexValue
1156 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1157 : Index.getZExtValue();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001158
Ken Dyck40775002010-01-11 17:06:35 +00001159 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith96e0c102011-11-04 02:25:55 +00001160 Result.Offset += IndexValue * ElementSize;
1161 Result.Designator.adjustIndex(IndexValue);
John McCall45d55e42010-05-07 21:00:08 +00001162 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001163}
Eli Friedman9a156e52008-11-12 09:44:48 +00001164
Peter Collingbournee9200682011-05-13 03:29:01 +00001165bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001166 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001167}
1168
Eli Friedman9a156e52008-11-12 09:44:48 +00001169//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001170// Pointer Evaluation
1171//===----------------------------------------------------------------------===//
1172
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001173namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001174class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001175 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001176 LValue &Result;
1177
Peter Collingbournee9200682011-05-13 03:29:01 +00001178 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001179 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001180 return true;
1181 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001182public:
Mike Stump11289f42009-09-09 15:08:12 +00001183
John McCall45d55e42010-05-07 21:00:08 +00001184 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001185 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001186
Richard Smith0b0a0b62011-10-29 20:57:55 +00001187 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001188 Result.setFrom(V);
1189 return true;
1190 }
1191 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001192 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001193 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001194 bool ValueInitialization(const Expr *E) {
1195 return Success((Expr*)0);
1196 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001197
John McCall45d55e42010-05-07 21:00:08 +00001198 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001199 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001200 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001201 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001202 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001203 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001204 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001205 bool VisitCallExpr(const CallExpr *E);
1206 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001207 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001208 return Success(E);
1209 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001210 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001211 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001212 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +00001213
Eli Friedman449fe542009-03-23 04:56:01 +00001214 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001215};
Chris Lattner05706e882008-07-11 18:11:29 +00001216} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001217
John McCall45d55e42010-05-07 21:00:08 +00001218static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001219 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001220 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001221}
1222
John McCall45d55e42010-05-07 21:00:08 +00001223bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001224 if (E->getOpcode() != BO_Add &&
1225 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001226 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001227
Chris Lattner05706e882008-07-11 18:11:29 +00001228 const Expr *PExp = E->getLHS();
1229 const Expr *IExp = E->getRHS();
1230 if (IExp->getType()->isPointerType())
1231 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001232
John McCall45d55e42010-05-07 21:00:08 +00001233 if (!EvaluatePointer(PExp, Result, Info))
1234 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall45d55e42010-05-07 21:00:08 +00001236 llvm::APSInt Offset;
1237 if (!EvaluateInteger(IExp, Offset, Info))
1238 return false;
1239 int64_t AdditionalOffset
1240 = Offset.isSigned() ? Offset.getSExtValue()
1241 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001242 if (E->getOpcode() == BO_Sub)
1243 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001244
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001245 // Compute the new offset in the appropriate width.
Daniel Dunbar4c43e312010-03-20 05:53:45 +00001246 QualType PointeeType =
1247 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +00001248 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +00001249
Anders Carlssonef56fba2009-02-19 04:55:58 +00001250 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1251 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +00001252 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +00001253 else
John McCall45d55e42010-05-07 21:00:08 +00001254 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +00001255
Richard Smith96e0c102011-11-04 02:25:55 +00001256 Result.Offset += AdditionalOffset * SizeOfPointee;
1257 Result.Designator.adjustIndex(AdditionalOffset);
John McCall45d55e42010-05-07 21:00:08 +00001258 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001259}
Eli Friedman9a156e52008-11-12 09:44:48 +00001260
John McCall45d55e42010-05-07 21:00:08 +00001261bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1262 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001263}
Mike Stump11289f42009-09-09 15:08:12 +00001264
Chris Lattner05706e882008-07-11 18:11:29 +00001265
Peter Collingbournee9200682011-05-13 03:29:01 +00001266bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1267 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001268
Eli Friedman847a2bc2009-12-27 05:43:15 +00001269 switch (E->getCastKind()) {
1270 default:
1271 break;
1272
John McCalle3027922010-08-25 11:45:40 +00001273 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001274 case CK_CPointerToObjCPointerCast:
1275 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001276 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001277 if (!Visit(SubExpr))
1278 return false;
1279 Result.Designator.setInvalid();
1280 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001281
Anders Carlsson18275092010-10-31 20:41:46 +00001282 case CK_DerivedToBase:
1283 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001284 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001285 return false;
1286
1287 // Now figure out the necessary offset to add to the baseLV to get from
1288 // the derived class to the base class.
Anders Carlsson18275092010-10-31 20:41:46 +00001289 QualType Ty = E->getSubExpr()->getType();
1290 const CXXRecordDecl *DerivedDecl =
1291 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1292
1293 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1294 PathE = E->path_end(); PathI != PathE; ++PathI) {
1295 const CXXBaseSpecifier *Base = *PathI;
1296
1297 // FIXME: If the base is virtual, we'd need to determine the type of the
1298 // most derived class and we don't support that right now.
1299 if (Base->isVirtual())
1300 return false;
1301
1302 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1303 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1304
Richard Smith0b0a0b62011-10-29 20:57:55 +00001305 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +00001306 DerivedDecl = BaseDecl;
1307 }
1308
Richard Smith96e0c102011-11-04 02:25:55 +00001309 // FIXME
1310 Result.Designator.setInvalid();
1311
Anders Carlsson18275092010-10-31 20:41:46 +00001312 return true;
1313 }
1314
Richard Smith0b0a0b62011-10-29 20:57:55 +00001315 case CK_NullToPointer:
1316 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001317
John McCalle3027922010-08-25 11:45:40 +00001318 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001319 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001320 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001321 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001322
John McCall45d55e42010-05-07 21:00:08 +00001323 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001324 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1325 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001326 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001327 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001328 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001329 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001330 return true;
1331 } else {
1332 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001333 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001334 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001335 }
1336 }
John McCalle3027922010-08-25 11:45:40 +00001337 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001338 // FIXME: Support array-to-pointer decay on array rvalues.
1339 if (!SubExpr->isGLValue())
1340 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001341 if (!EvaluateLValue(SubExpr, Result, Info))
1342 return false;
1343 // The result is a pointer to the first element of the array.
1344 Result.Designator.addIndex(0);
1345 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001346
John McCalle3027922010-08-25 11:45:40 +00001347 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001348 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001349 }
1350
Richard Smith11562c52011-10-28 17:51:58 +00001351 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001352}
Chris Lattner05706e882008-07-11 18:11:29 +00001353
Peter Collingbournee9200682011-05-13 03:29:01 +00001354bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +00001355 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +00001356 Builtin::BI__builtin___CFStringMakeConstantString ||
1357 E->isBuiltinCall(Info.Ctx) ==
1358 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +00001359 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001360
Peter Collingbournee9200682011-05-13 03:29:01 +00001361 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001362}
Chris Lattner05706e882008-07-11 18:11:29 +00001363
1364//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001365// Vector Evaluation
1366//===----------------------------------------------------------------------===//
1367
1368namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001369 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001370 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1371 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001372 public:
Mike Stump11289f42009-09-09 15:08:12 +00001373
Richard Smith2d406342011-10-22 21:10:00 +00001374 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1375 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001376
Richard Smith2d406342011-10-22 21:10:00 +00001377 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1378 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1379 // FIXME: remove this APValue copy.
1380 Result = APValue(V.data(), V.size());
1381 return true;
1382 }
Richard Smithed5165f2011-11-04 05:33:44 +00001383 bool Success(const CCValue &V, const Expr *E) {
1384 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00001385 Result = V;
1386 return true;
1387 }
1388 bool Error(const Expr *E) { return false; }
1389 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001390
Richard Smith2d406342011-10-22 21:10:00 +00001391 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001392 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001393 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001394 bool VisitInitListExpr(const InitListExpr *E);
1395 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001396 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001397 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001398 // shufflevector, ExtVectorElementExpr
1399 // (Note that these require implementing conversions
1400 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001401 };
1402} // end anonymous namespace
1403
1404static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001405 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001406 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001407}
1408
Richard Smith2d406342011-10-22 21:10:00 +00001409bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1410 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001411 QualType EltTy = VTy->getElementType();
1412 unsigned NElts = VTy->getNumElements();
1413 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001414
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001415 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001416 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001417
Eli Friedmanc757de22011-03-25 00:43:55 +00001418 switch (E->getCastKind()) {
1419 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001420 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001421 if (SETy->isIntegerType()) {
1422 APSInt IntResult;
1423 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001424 return Error(E);
1425 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001426 } else if (SETy->isRealFloatingType()) {
1427 APFloat F(0.0);
1428 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001429 return Error(E);
1430 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001431 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001432 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001433 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001434
1435 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001436 SmallVector<APValue, 4> Elts(NElts, Val);
1437 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001438 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001439 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001440 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001441 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001442 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001443
Eli Friedmanc757de22011-03-25 00:43:55 +00001444 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001445 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001446
Eli Friedmanc757de22011-03-25 00:43:55 +00001447 APSInt Init;
1448 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001449 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001450
Eli Friedmanc757de22011-03-25 00:43:55 +00001451 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1452 "Vectors must be composed of ints or floats");
1453
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001454 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001455 for (unsigned i = 0; i != NElts; ++i) {
1456 APSInt Tmp = Init.extOrTrunc(EltWidth);
1457
1458 if (EltTy->isIntegerType())
1459 Elts.push_back(APValue(Tmp));
1460 else
1461 Elts.push_back(APValue(APFloat(Tmp)));
1462
1463 Init >>= EltWidth;
1464 }
Richard Smith2d406342011-10-22 21:10:00 +00001465 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001466 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001467 default:
Richard Smith11562c52011-10-28 17:51:58 +00001468 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001469 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001470}
1471
Richard Smith2d406342011-10-22 21:10:00 +00001472bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001473VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001474 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001475 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001476 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001477
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001478 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001479 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001480
John McCall875679e2010-06-11 17:54:15 +00001481 // If a vector is initialized with a single element, that value
1482 // becomes every element of the vector, not just the first.
1483 // This is the behavior described in the IBM AltiVec documentation.
1484 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001485
1486 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001487 // vector (OpenCL 6.1.6).
1488 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001489 return Visit(E->getInit(0));
1490
John McCall875679e2010-06-11 17:54:15 +00001491 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001492 if (EltTy->isIntegerType()) {
1493 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001494 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001495 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001496 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001497 } else {
1498 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001499 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001500 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001501 InitValue = APValue(f);
1502 }
1503 for (unsigned i = 0; i < NumElements; i++) {
1504 Elements.push_back(InitValue);
1505 }
1506 } else {
1507 for (unsigned i = 0; i < NumElements; i++) {
1508 if (EltTy->isIntegerType()) {
1509 llvm::APSInt sInt(32);
1510 if (i < NumInits) {
1511 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001512 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001513 } else {
1514 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1515 }
1516 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001517 } else {
John McCall875679e2010-06-11 17:54:15 +00001518 llvm::APFloat f(0.0);
1519 if (i < NumInits) {
1520 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001521 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001522 } else {
1523 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1524 }
1525 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001526 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001527 }
1528 }
Richard Smith2d406342011-10-22 21:10:00 +00001529 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001530}
1531
Richard Smith2d406342011-10-22 21:10:00 +00001532bool
1533VectorExprEvaluator::ValueInitialization(const Expr *E) {
1534 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001535 QualType EltTy = VT->getElementType();
1536 APValue ZeroElement;
1537 if (EltTy->isIntegerType())
1538 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1539 else
1540 ZeroElement =
1541 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1542
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001543 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001544 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001545}
1546
Richard Smith2d406342011-10-22 21:10:00 +00001547bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001548 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001549 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001550}
1551
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001552//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001553// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001554//
1555// As a GNU extension, we support casting pointers to sufficiently-wide integer
1556// types and back in constant folding. Integer values are thus represented
1557// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001558//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001559
1560namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001561class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001562 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001563 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001564public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001565 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001566 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001567
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001568 bool Success(const llvm::APSInt &SI, const Expr *E) {
1569 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001570 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001571 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001572 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001573 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001574 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001575 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001576 return true;
1577 }
1578
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001579 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001580 assert(E->getType()->isIntegralOrEnumerationType() &&
1581 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001582 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001583 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001584 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001585 Result.getInt().setIsUnsigned(
1586 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001587 return true;
1588 }
1589
1590 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001591 assert(E->getType()->isIntegralOrEnumerationType() &&
1592 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001593 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001594 return true;
1595 }
1596
Ken Dyckdbc01912011-03-11 02:13:43 +00001597 bool Success(CharUnits Size, const Expr *E) {
1598 return Success(Size.getQuantity(), E);
1599 }
1600
1601
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001602 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001603 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001604 if (Info.EvalStatus.Diag == 0) {
1605 Info.EvalStatus.DiagLoc = L;
1606 Info.EvalStatus.Diag = D;
1607 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001608 }
Chris Lattner99415702008-07-12 00:14:42 +00001609 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001610 }
Mike Stump11289f42009-09-09 15:08:12 +00001611
Richard Smith0b0a0b62011-10-29 20:57:55 +00001612 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00001613 if (V.isLValue()) {
1614 Result = V;
1615 return true;
1616 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001617 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001618 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001619 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001620 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001621 }
Mike Stump11289f42009-09-09 15:08:12 +00001622
Richard Smith4ce706a2011-10-11 21:43:33 +00001623 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1624
Peter Collingbournee9200682011-05-13 03:29:01 +00001625 //===--------------------------------------------------------------------===//
1626 // Visitor Methods
1627 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001628
Chris Lattner7174bf32008-07-12 00:38:25 +00001629 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001630 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001631 }
1632 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001633 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001634 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001635
1636 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1637 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001638 if (CheckReferencedDecl(E, E->getDecl()))
1639 return true;
1640
1641 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001642 }
1643 bool VisitMemberExpr(const MemberExpr *E) {
1644 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001645 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001646 return true;
1647 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001648
1649 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001650 }
1651
Peter Collingbournee9200682011-05-13 03:29:01 +00001652 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001653 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001654 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001655 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001656
Peter Collingbournee9200682011-05-13 03:29:01 +00001657 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001658 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001659
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001660 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001661 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001662 }
Mike Stump11289f42009-09-09 15:08:12 +00001663
Richard Smith4ce706a2011-10-11 21:43:33 +00001664 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001665 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001666 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001667 }
1668
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001669 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001670 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001671 }
1672
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001673 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1674 return Success(E->getValue(), E);
1675 }
1676
John Wiegley6242b6a2011-04-28 00:16:57 +00001677 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1678 return Success(E->getValue(), E);
1679 }
1680
John Wiegleyf9f65842011-04-25 06:54:41 +00001681 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1682 return Success(E->getValue(), E);
1683 }
1684
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001685 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001686 bool VisitUnaryImag(const UnaryOperator *E);
1687
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001688 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001689 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001690
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001691private:
Ken Dyck160146e2010-01-27 17:10:57 +00001692 CharUnits GetAlignOfExpr(const Expr *E);
1693 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001694 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001695 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001696 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001697};
Chris Lattner05706e882008-07-11 18:11:29 +00001698} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001699
Richard Smith11562c52011-10-28 17:51:58 +00001700/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1701/// produce either the integer value or a pointer.
1702///
1703/// GCC has a heinous extension which folds casts between pointer types and
1704/// pointer-sized integral types. We support this by allowing the evaluation of
1705/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1706/// Some simple arithmetic on such values is supported (they are treated much
1707/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00001708static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1709 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001710 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001711 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001712}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001713
Daniel Dunbarce399542009-02-20 18:22:23 +00001714static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001715 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00001716 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1717 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001718 Result = Val.getInt();
1719 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001720}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001721
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001722bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001723 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001724 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001725 // Check for signedness/width mismatches between E type and ECD value.
1726 bool SameSign = (ECD->getInitVal().isSigned()
1727 == E->getType()->isSignedIntegerOrEnumerationType());
1728 bool SameWidth = (ECD->getInitVal().getBitWidth()
1729 == Info.Ctx.getIntWidth(E->getType()));
1730 if (SameSign && SameWidth)
1731 return Success(ECD->getInitVal(), E);
1732 else {
1733 // Get rid of mismatch (otherwise Success assertions will fail)
1734 // by computing a new value matching the type of E.
1735 llvm::APSInt Val = ECD->getInitVal();
1736 if (!SameSign)
1737 Val.setIsSigned(!ECD->getInitVal().isSigned());
1738 if (!SameWidth)
1739 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1740 return Success(Val, E);
1741 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001742 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001743 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001744}
1745
Chris Lattner86ee2862008-10-06 06:40:35 +00001746/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1747/// as GCC.
1748static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1749 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001750 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001751 enum gcc_type_class {
1752 no_type_class = -1,
1753 void_type_class, integer_type_class, char_type_class,
1754 enumeral_type_class, boolean_type_class,
1755 pointer_type_class, reference_type_class, offset_type_class,
1756 real_type_class, complex_type_class,
1757 function_type_class, method_type_class,
1758 record_type_class, union_type_class,
1759 array_type_class, string_type_class,
1760 lang_type_class
1761 };
Mike Stump11289f42009-09-09 15:08:12 +00001762
1763 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001764 // ideal, however it is what gcc does.
1765 if (E->getNumArgs() == 0)
1766 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001767
Chris Lattner86ee2862008-10-06 06:40:35 +00001768 QualType ArgTy = E->getArg(0)->getType();
1769 if (ArgTy->isVoidType())
1770 return void_type_class;
1771 else if (ArgTy->isEnumeralType())
1772 return enumeral_type_class;
1773 else if (ArgTy->isBooleanType())
1774 return boolean_type_class;
1775 else if (ArgTy->isCharType())
1776 return string_type_class; // gcc doesn't appear to use char_type_class
1777 else if (ArgTy->isIntegerType())
1778 return integer_type_class;
1779 else if (ArgTy->isPointerType())
1780 return pointer_type_class;
1781 else if (ArgTy->isReferenceType())
1782 return reference_type_class;
1783 else if (ArgTy->isRealType())
1784 return real_type_class;
1785 else if (ArgTy->isComplexType())
1786 return complex_type_class;
1787 else if (ArgTy->isFunctionType())
1788 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001789 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001790 return record_type_class;
1791 else if (ArgTy->isUnionType())
1792 return union_type_class;
1793 else if (ArgTy->isArrayType())
1794 return array_type_class;
1795 else if (ArgTy->isUnionType())
1796 return union_type_class;
1797 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001798 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001799 return -1;
1800}
1801
John McCall95007602010-05-10 23:27:23 +00001802/// Retrieves the "underlying object type" of the given expression,
1803/// as used by __builtin_object_size.
1804QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1806 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1807 return VD->getType();
1808 } else if (isa<CompoundLiteralExpr>(E)) {
1809 return E->getType();
1810 }
1811
1812 return QualType();
1813}
1814
Peter Collingbournee9200682011-05-13 03:29:01 +00001815bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001816 // TODO: Perhaps we should let LLVM lower this?
1817 LValue Base;
1818 if (!EvaluatePointer(E->getArg(0), Base, Info))
1819 return false;
1820
1821 // If we can prove the base is null, lower to zero now.
1822 const Expr *LVBase = Base.getLValueBase();
1823 if (!LVBase) return Success(0, E);
1824
1825 QualType T = GetObjectType(LVBase);
1826 if (T.isNull() ||
1827 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001828 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001829 T->isVariablyModifiedType() ||
1830 T->isDependentType())
1831 return false;
1832
1833 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1834 CharUnits Offset = Base.getLValueOffset();
1835
1836 if (!Offset.isNegative() && Offset <= Size)
1837 Size -= Offset;
1838 else
1839 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001840 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001841}
1842
Peter Collingbournee9200682011-05-13 03:29:01 +00001843bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001844 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001845 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001846 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001847
1848 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001849 if (TryEvaluateBuiltinObjectSize(E))
1850 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001851
Eric Christopher99469702010-01-19 22:58:35 +00001852 // If evaluating the argument has side-effects we can't determine
1853 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001854 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001855 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001856 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001857 return Success(0, E);
1858 }
Mike Stump876387b2009-10-27 22:09:17 +00001859
Mike Stump722cedf2009-10-26 18:35:08 +00001860 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1861 }
1862
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001863 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001864 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001865
Anders Carlsson4c76e932008-11-24 04:21:33 +00001866 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001867 // __builtin_constant_p always has one operand: it returns true if that
1868 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001869 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001870
1871 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001872 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001873 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001874 return Success(Operand, E);
1875 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001876
1877 case Builtin::BI__builtin_expect:
1878 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001879
1880 case Builtin::BIstrlen:
1881 case Builtin::BI__builtin_strlen:
1882 // As an extension, we support strlen() and __builtin_strlen() as constant
1883 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001884 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001885 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1886 // The string literal may have embedded null characters. Find the first
1887 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001888 StringRef Str = S->getString();
1889 StringRef::size_type Pos = Str.find(0);
1890 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001891 Str = Str.substr(0, Pos);
1892
1893 return Success(Str.size(), E);
1894 }
1895
1896 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001897
1898 case Builtin::BI__atomic_is_lock_free: {
1899 APSInt SizeVal;
1900 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1901 return false;
1902
1903 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1904 // of two less than the maximum inline atomic width, we know it is
1905 // lock-free. If the size isn't a power of two, or greater than the
1906 // maximum alignment where we promote atomics, we know it is not lock-free
1907 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1908 // the answer can only be determined at runtime; for example, 16-byte
1909 // atomics have lock-free implementations on some, but not all,
1910 // x86-64 processors.
1911
1912 // Check power-of-two.
1913 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1914 if (!Size.isPowerOfTwo())
1915#if 0
1916 // FIXME: Suppress this folding until the ABI for the promotion width
1917 // settles.
1918 return Success(0, E);
1919#else
1920 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1921#endif
1922
1923#if 0
1924 // Check against promotion width.
1925 // FIXME: Suppress this folding until the ABI for the promotion width
1926 // settles.
1927 unsigned PromoteWidthBits =
1928 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1929 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1930 return Success(0, E);
1931#endif
1932
1933 // Check against inlining width.
1934 unsigned InlineWidthBits =
1935 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1936 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1937 return Success(1, E);
1938
1939 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1940 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001941 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001942}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001943
Richard Smith8b3497e2011-10-31 01:37:14 +00001944static bool HasSameBase(const LValue &A, const LValue &B) {
1945 if (!A.getLValueBase())
1946 return !B.getLValueBase();
1947 if (!B.getLValueBase())
1948 return false;
1949
1950 if (A.getLValueBase() != B.getLValueBase()) {
1951 const Decl *ADecl = GetLValueBaseDecl(A);
1952 if (!ADecl)
1953 return false;
1954 const Decl *BDecl = GetLValueBaseDecl(B);
1955 if (ADecl != BDecl)
1956 return false;
1957 }
1958
1959 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00001960 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00001961}
1962
Chris Lattnere13042c2008-07-11 19:10:17 +00001963bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001964 if (E->isAssignmentOp())
1965 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1966
John McCalle3027922010-08-25 11:45:40 +00001967 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001968 VisitIgnoredValue(E->getLHS());
1969 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001970 }
1971
1972 if (E->isLogicalOp()) {
1973 // These need to be handled specially because the operands aren't
1974 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001975 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001976
Richard Smith11562c52011-10-28 17:51:58 +00001977 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001978 // We were able to evaluate the LHS, see if we can get away with not
1979 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001980 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001981 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001982
Richard Smith11562c52011-10-28 17:51:58 +00001983 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001984 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001985 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001986 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001987 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001988 }
1989 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001990 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001991 // We can't evaluate the LHS; however, sometimes the result
1992 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001993 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1994 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001995 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001996 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001997 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001998
1999 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002000 }
2001 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00002002 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00002003
Eli Friedman5a332ea2008-11-13 06:09:17 +00002004 return false;
2005 }
2006
Anders Carlssonacc79812008-11-16 07:17:21 +00002007 QualType LHSTy = E->getLHS()->getType();
2008 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002009
2010 if (LHSTy->isAnyComplexType()) {
2011 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002012 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002013
2014 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2015 return false;
2016
2017 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2018 return false;
2019
2020 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002021 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002022 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002023 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002024 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2025
John McCalle3027922010-08-25 11:45:40 +00002026 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002027 return Success((CR_r == APFloat::cmpEqual &&
2028 CR_i == APFloat::cmpEqual), E);
2029 else {
John McCalle3027922010-08-25 11:45:40 +00002030 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002031 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002032 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002033 CR_r == APFloat::cmpLessThan ||
2034 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002035 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002036 CR_i == APFloat::cmpLessThan ||
2037 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002038 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002039 } else {
John McCalle3027922010-08-25 11:45:40 +00002040 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002041 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2042 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2043 else {
John McCalle3027922010-08-25 11:45:40 +00002044 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002045 "Invalid compex comparison.");
2046 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2047 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2048 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002049 }
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051
Anders Carlssonacc79812008-11-16 07:17:21 +00002052 if (LHSTy->isRealFloatingType() &&
2053 RHSTy->isRealFloatingType()) {
2054 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002055
Anders Carlssonacc79812008-11-16 07:17:21 +00002056 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2057 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002058
Anders Carlssonacc79812008-11-16 07:17:21 +00002059 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2060 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002061
Anders Carlssonacc79812008-11-16 07:17:21 +00002062 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002063
Anders Carlssonacc79812008-11-16 07:17:21 +00002064 switch (E->getOpcode()) {
2065 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002066 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002067 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002068 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002069 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002070 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002071 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002072 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002073 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002074 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002075 E);
John McCalle3027922010-08-25 11:45:40 +00002076 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002077 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002078 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002079 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002080 || CR == APFloat::cmpLessThan
2081 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002082 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Eli Friedmana38da572009-04-28 19:17:36 +00002085 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002086 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002087 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002088 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2089 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002090
John McCall45d55e42010-05-07 21:00:08 +00002091 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002092 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2093 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002094
Richard Smith8b3497e2011-10-31 01:37:14 +00002095 // Reject differing bases from the normal codepath; we special-case
2096 // comparisons to null.
2097 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002098 // Inequalities and subtractions between unrelated pointers have
2099 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002100 if (!E->isEqualityOp())
2101 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002102 // A constant address may compare equal to the address of a symbol.
2103 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002104 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002105 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2106 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2107 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002108 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002109 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002110 // distinct. However, we do know that the address of a literal will be
2111 // non-null.
2112 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2113 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002114 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002115 // We can't tell whether weak symbols will end up pointing to the same
2116 // object.
2117 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002118 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002119 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002120 // (Note that clang defaults to -fmerge-all-constants, which can
2121 // lead to inconsistent results for comparisons involving the address
2122 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002123 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002124 }
Eli Friedman64004332009-03-23 04:38:34 +00002125
John McCalle3027922010-08-25 11:45:40 +00002126 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002127 QualType Type = E->getLHS()->getType();
2128 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002129
Ken Dyck02990832010-01-15 12:37:54 +00002130 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00002131 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00002132 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00002133
Ken Dyck02990832010-01-15 12:37:54 +00002134 CharUnits Diff = LHSValue.getLValueOffset() -
2135 RHSValue.getLValueOffset();
2136 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002137 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002138
2139 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2140 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2141 switch (E->getOpcode()) {
2142 default: llvm_unreachable("missing comparison operator");
2143 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2144 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2145 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2146 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2147 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2148 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002149 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002150 }
2151 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002152 if (!LHSTy->isIntegralOrEnumerationType() ||
2153 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002154 // We can't continue from here for non-integral types, and they
2155 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002156 return false;
2157 }
2158
Anders Carlsson9c181652008-07-08 14:35:21 +00002159 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002160 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002161 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002162 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002163
Richard Smith11562c52011-10-28 17:51:58 +00002164 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002165 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002166 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002167
2168 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002169 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002170 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2171 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002172 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002173 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002174 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002175 LHSVal.getLValueOffset() -= AdditionalOffset;
2176 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002177 return true;
2178 }
2179
2180 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002181 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002182 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002183 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2184 LHSVal.getInt().getZExtValue());
2185 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002186 return true;
2187 }
2188
2189 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002190 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002191 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002192
Richard Smith11562c52011-10-28 17:51:58 +00002193 APSInt &LHS = LHSVal.getInt();
2194 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002195
Anders Carlsson9c181652008-07-08 14:35:21 +00002196 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002197 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002198 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002199 case BO_Mul: return Success(LHS * RHS, E);
2200 case BO_Add: return Success(LHS + RHS, E);
2201 case BO_Sub: return Success(LHS - RHS, E);
2202 case BO_And: return Success(LHS & RHS, E);
2203 case BO_Xor: return Success(LHS ^ RHS, E);
2204 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002205 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002206 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002207 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002208 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002209 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002210 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002211 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002212 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002213 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002214 // During constant-folding, a negative shift is an opposite shift.
2215 if (RHS.isSigned() && RHS.isNegative()) {
2216 RHS = -RHS;
2217 goto shift_right;
2218 }
2219
2220 shift_left:
2221 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002222 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2223 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002224 }
John McCalle3027922010-08-25 11:45:40 +00002225 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002226 // During constant-folding, a negative shift is an opposite shift.
2227 if (RHS.isSigned() && RHS.isNegative()) {
2228 RHS = -RHS;
2229 goto shift_left;
2230 }
2231
2232 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002233 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002234 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2235 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
Richard Smith11562c52011-10-28 17:51:58 +00002238 case BO_LT: return Success(LHS < RHS, E);
2239 case BO_GT: return Success(LHS > RHS, E);
2240 case BO_LE: return Success(LHS <= RHS, E);
2241 case BO_GE: return Success(LHS >= RHS, E);
2242 case BO_EQ: return Success(LHS == RHS, E);
2243 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002244 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002245}
2246
Ken Dyck160146e2010-01-27 17:10:57 +00002247CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002248 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2249 // the result is the size of the referenced type."
2250 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2251 // result shall be the alignment of the referenced type."
2252 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2253 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002254
2255 // __alignof is defined to return the preferred alignment.
2256 return Info.Ctx.toCharUnitsFromBits(
2257 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002258}
2259
Ken Dyck160146e2010-01-27 17:10:57 +00002260CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002261 E = E->IgnoreParens();
2262
2263 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002264 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002265 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002266 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2267 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002268
Chris Lattner68061312009-01-24 21:53:27 +00002269 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002270 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2271 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002272
Chris Lattner24aeeab2009-01-24 21:09:06 +00002273 return GetAlignOfType(E->getType());
2274}
2275
2276
Peter Collingbournee190dee2011-03-11 19:24:49 +00002277/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2278/// a result as the expression's type.
2279bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2280 const UnaryExprOrTypeTraitExpr *E) {
2281 switch(E->getKind()) {
2282 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002283 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002284 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002285 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002286 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002287 }
Eli Friedman64004332009-03-23 04:38:34 +00002288
Peter Collingbournee190dee2011-03-11 19:24:49 +00002289 case UETT_VecStep: {
2290 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002291
Peter Collingbournee190dee2011-03-11 19:24:49 +00002292 if (Ty->isVectorType()) {
2293 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002294
Peter Collingbournee190dee2011-03-11 19:24:49 +00002295 // The vec_step built-in functions that take a 3-component
2296 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2297 if (n == 3)
2298 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002299
Peter Collingbournee190dee2011-03-11 19:24:49 +00002300 return Success(n, E);
2301 } else
2302 return Success(1, E);
2303 }
2304
2305 case UETT_SizeOf: {
2306 QualType SrcTy = E->getTypeOfArgument();
2307 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2308 // the result is the size of the referenced type."
2309 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2310 // result shall be the alignment of the referenced type."
2311 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2312 SrcTy = Ref->getPointeeType();
2313
2314 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2315 // extension.
2316 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2317 return Success(1, E);
2318
2319 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2320 if (!SrcTy->isConstantSizeType())
2321 return false;
2322
2323 // Get information about the size.
2324 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2325 }
2326 }
2327
2328 llvm_unreachable("unknown expr/type trait");
2329 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002330}
2331
Peter Collingbournee9200682011-05-13 03:29:01 +00002332bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002333 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002334 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002335 if (n == 0)
2336 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002337 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002338 for (unsigned i = 0; i != n; ++i) {
2339 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2340 switch (ON.getKind()) {
2341 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002342 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002343 APSInt IdxResult;
2344 if (!EvaluateInteger(Idx, IdxResult, Info))
2345 return false;
2346 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2347 if (!AT)
2348 return false;
2349 CurrentType = AT->getElementType();
2350 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2351 Result += IdxResult.getSExtValue() * ElementSize;
2352 break;
2353 }
2354
2355 case OffsetOfExpr::OffsetOfNode::Field: {
2356 FieldDecl *MemberDecl = ON.getField();
2357 const RecordType *RT = CurrentType->getAs<RecordType>();
2358 if (!RT)
2359 return false;
2360 RecordDecl *RD = RT->getDecl();
2361 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002362 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002363 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002364 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002365 CurrentType = MemberDecl->getType().getNonReferenceType();
2366 break;
2367 }
2368
2369 case OffsetOfExpr::OffsetOfNode::Identifier:
2370 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002371 return false;
2372
2373 case OffsetOfExpr::OffsetOfNode::Base: {
2374 CXXBaseSpecifier *BaseSpec = ON.getBase();
2375 if (BaseSpec->isVirtual())
2376 return false;
2377
2378 // Find the layout of the class whose base we are looking into.
2379 const RecordType *RT = CurrentType->getAs<RecordType>();
2380 if (!RT)
2381 return false;
2382 RecordDecl *RD = RT->getDecl();
2383 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2384
2385 // Find the base class itself.
2386 CurrentType = BaseSpec->getType();
2387 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2388 if (!BaseRT)
2389 return false;
2390
2391 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00002392 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00002393 break;
2394 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002395 }
2396 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002397 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00002398}
2399
Chris Lattnere13042c2008-07-11 19:10:17 +00002400bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002401 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002402 // LNot's operand isn't necessarily an integer, so we handle it specially.
2403 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00002404 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00002405 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002406 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00002407 }
2408
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002409 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00002410 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00002411 return false;
2412
Richard Smith11562c52011-10-28 17:51:58 +00002413 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002414 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00002415 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00002416 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002417
Chris Lattnerf09ad162008-07-11 22:15:16 +00002418 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002419 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00002420 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2421 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002422 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00002423 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00002424 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2425 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002426 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002427 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002428 // The result is just the value.
2429 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002430 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002431 if (!Val.isInt()) return false;
2432 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002433 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002434 if (!Val.isInt()) return false;
2435 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002436 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002437}
Mike Stump11289f42009-09-09 15:08:12 +00002438
Chris Lattner477c4be2008-07-12 01:15:53 +00002439/// HandleCast - This is used to evaluate implicit or explicit casts where the
2440/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002441bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2442 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002443 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002444 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002445
Eli Friedmanc757de22011-03-25 00:43:55 +00002446 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002447 case CK_BaseToDerived:
2448 case CK_DerivedToBase:
2449 case CK_UncheckedDerivedToBase:
2450 case CK_Dynamic:
2451 case CK_ToUnion:
2452 case CK_ArrayToPointerDecay:
2453 case CK_FunctionToPointerDecay:
2454 case CK_NullToPointer:
2455 case CK_NullToMemberPointer:
2456 case CK_BaseToDerivedMemberPointer:
2457 case CK_DerivedToBaseMemberPointer:
2458 case CK_ConstructorConversion:
2459 case CK_IntegralToPointer:
2460 case CK_ToVoid:
2461 case CK_VectorSplat:
2462 case CK_IntegralToFloating:
2463 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002464 case CK_CPointerToObjCPointerCast:
2465 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002466 case CK_AnyPointerToBlockPointerCast:
2467 case CK_ObjCObjectLValueCast:
2468 case CK_FloatingRealToComplex:
2469 case CK_FloatingComplexToReal:
2470 case CK_FloatingComplexCast:
2471 case CK_FloatingComplexToIntegralComplex:
2472 case CK_IntegralRealToComplex:
2473 case CK_IntegralComplexCast:
2474 case CK_IntegralComplexToFloatingComplex:
2475 llvm_unreachable("invalid cast kind for integral value");
2476
Eli Friedman9faf2f92011-03-25 19:07:11 +00002477 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002478 case CK_Dependent:
2479 case CK_GetObjCProperty:
2480 case CK_LValueBitCast:
2481 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002482 case CK_ARCProduceObject:
2483 case CK_ARCConsumeObject:
2484 case CK_ARCReclaimReturnedObject:
2485 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002486 return false;
2487
2488 case CK_LValueToRValue:
2489 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002490 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002491
2492 case CK_MemberPointerToBoolean:
2493 case CK_PointerToBoolean:
2494 case CK_IntegralToBoolean:
2495 case CK_FloatingToBoolean:
2496 case CK_FloatingComplexToBoolean:
2497 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002498 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002499 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002500 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002501 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002502 }
2503
Eli Friedmanc757de22011-03-25 00:43:55 +00002504 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002505 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002506 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002507
Eli Friedman742421e2009-02-20 01:15:07 +00002508 if (!Result.isInt()) {
2509 // Only allow casts of lvalues if they are lossless.
2510 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2511 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002512
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002513 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002514 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002515 }
Mike Stump11289f42009-09-09 15:08:12 +00002516
Eli Friedmanc757de22011-03-25 00:43:55 +00002517 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002518 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002519 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002520 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002521
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002522 if (LV.getLValueBase()) {
2523 // Only allow based lvalue casts if they are lossless.
2524 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2525 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002526
John McCall45d55e42010-05-07 21:00:08 +00002527 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002528 return true;
2529 }
2530
Ken Dyck02990832010-01-15 12:37:54 +00002531 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2532 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002533 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002534 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002535
Eli Friedmanc757de22011-03-25 00:43:55 +00002536 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002537 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002538 if (!EvaluateComplex(SubExpr, C, Info))
2539 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002540 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002541 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002542
Eli Friedmanc757de22011-03-25 00:43:55 +00002543 case CK_FloatingToIntegral: {
2544 APFloat F(0.0);
2545 if (!EvaluateFloat(SubExpr, F, Info))
2546 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002547
Eli Friedmanc757de22011-03-25 00:43:55 +00002548 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2549 }
2550 }
Mike Stump11289f42009-09-09 15:08:12 +00002551
Eli Friedmanc757de22011-03-25 00:43:55 +00002552 llvm_unreachable("unknown cast resulting in integral value");
2553 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002554}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002555
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002556bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2557 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002558 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002559 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2560 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2561 return Success(LV.getComplexIntReal(), E);
2562 }
2563
2564 return Visit(E->getSubExpr());
2565}
2566
Eli Friedman4e7a2412009-02-27 04:45:43 +00002567bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002568 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002569 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002570 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2571 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2572 return Success(LV.getComplexIntImag(), E);
2573 }
2574
Richard Smith4a678122011-10-24 18:44:57 +00002575 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002576 return Success(0, E);
2577}
2578
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002579bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2580 return Success(E->getPackLength(), E);
2581}
2582
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002583bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2584 return Success(E->getValue(), E);
2585}
2586
Chris Lattner05706e882008-07-11 18:11:29 +00002587//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002588// Float Evaluation
2589//===----------------------------------------------------------------------===//
2590
2591namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002592class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002593 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002594 APFloat &Result;
2595public:
2596 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002597 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002598
Richard Smith0b0a0b62011-10-29 20:57:55 +00002599 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002600 Result = V.getFloat();
2601 return true;
2602 }
2603 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002604 return false;
2605 }
2606
Richard Smith4ce706a2011-10-11 21:43:33 +00002607 bool ValueInitialization(const Expr *E) {
2608 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2609 return true;
2610 }
2611
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002612 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002613
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002614 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002615 bool VisitBinaryOperator(const BinaryOperator *E);
2616 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002617 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002618
John McCallb1fb0d32010-05-07 22:08:54 +00002619 bool VisitUnaryReal(const UnaryOperator *E);
2620 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002621
John McCallb1fb0d32010-05-07 22:08:54 +00002622 // FIXME: Missing: array subscript of vector, member of vector,
2623 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002624};
2625} // end anonymous namespace
2626
2627static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002628 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002629 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002630}
2631
Jay Foad39c79802011-01-12 09:06:06 +00002632static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002633 QualType ResultTy,
2634 const Expr *Arg,
2635 bool SNaN,
2636 llvm::APFloat &Result) {
2637 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2638 if (!S) return false;
2639
2640 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2641
2642 llvm::APInt fill;
2643
2644 // Treat empty strings as if they were zero.
2645 if (S->getString().empty())
2646 fill = llvm::APInt(32, 0);
2647 else if (S->getString().getAsInteger(0, fill))
2648 return false;
2649
2650 if (SNaN)
2651 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2652 else
2653 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2654 return true;
2655}
2656
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002657bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002658 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002659 default:
2660 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2661
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002662 case Builtin::BI__builtin_huge_val:
2663 case Builtin::BI__builtin_huge_valf:
2664 case Builtin::BI__builtin_huge_vall:
2665 case Builtin::BI__builtin_inf:
2666 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002667 case Builtin::BI__builtin_infl: {
2668 const llvm::fltSemantics &Sem =
2669 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002670 Result = llvm::APFloat::getInf(Sem);
2671 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002672 }
Mike Stump11289f42009-09-09 15:08:12 +00002673
John McCall16291492010-02-28 13:00:19 +00002674 case Builtin::BI__builtin_nans:
2675 case Builtin::BI__builtin_nansf:
2676 case Builtin::BI__builtin_nansl:
2677 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2678 true, Result);
2679
Chris Lattner0b7282e2008-10-06 06:31:58 +00002680 case Builtin::BI__builtin_nan:
2681 case Builtin::BI__builtin_nanf:
2682 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002683 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002684 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002685 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2686 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002687
2688 case Builtin::BI__builtin_fabs:
2689 case Builtin::BI__builtin_fabsf:
2690 case Builtin::BI__builtin_fabsl:
2691 if (!EvaluateFloat(E->getArg(0), Result, Info))
2692 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002693
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002694 if (Result.isNegative())
2695 Result.changeSign();
2696 return true;
2697
Mike Stump11289f42009-09-09 15:08:12 +00002698 case Builtin::BI__builtin_copysign:
2699 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002700 case Builtin::BI__builtin_copysignl: {
2701 APFloat RHS(0.);
2702 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2703 !EvaluateFloat(E->getArg(1), RHS, Info))
2704 return false;
2705 Result.copySign(RHS);
2706 return true;
2707 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002708 }
2709}
2710
John McCallb1fb0d32010-05-07 22:08:54 +00002711bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002712 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2713 ComplexValue CV;
2714 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2715 return false;
2716 Result = CV.FloatReal;
2717 return true;
2718 }
2719
2720 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002721}
2722
2723bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002724 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2725 ComplexValue CV;
2726 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2727 return false;
2728 Result = CV.FloatImag;
2729 return true;
2730 }
2731
Richard Smith4a678122011-10-24 18:44:57 +00002732 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002733 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2734 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002735 return true;
2736}
2737
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002738bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002739 switch (E->getOpcode()) {
2740 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002741 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00002742 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00002743 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00002744 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2745 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002746 Result.changeSign();
2747 return true;
2748 }
2749}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002750
Eli Friedman24c01542008-08-22 00:06:13 +00002751bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002752 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002753 VisitIgnoredValue(E->getLHS());
2754 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002755 }
2756
Richard Smith472d4952011-10-28 23:26:52 +00002757 // We can't evaluate pointer-to-member operations or assignments.
2758 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00002759 return false;
2760
Eli Friedman24c01542008-08-22 00:06:13 +00002761 // FIXME: Diagnostics? I really don't understand how the warnings
2762 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002763 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002764 if (!EvaluateFloat(E->getLHS(), Result, Info))
2765 return false;
2766 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2767 return false;
2768
2769 switch (E->getOpcode()) {
2770 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002771 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002772 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2773 return true;
John McCalle3027922010-08-25 11:45:40 +00002774 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002775 Result.add(RHS, APFloat::rmNearestTiesToEven);
2776 return true;
John McCalle3027922010-08-25 11:45:40 +00002777 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002778 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2779 return true;
John McCalle3027922010-08-25 11:45:40 +00002780 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002781 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2782 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002783 }
2784}
2785
2786bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2787 Result = E->getValue();
2788 return true;
2789}
2790
Peter Collingbournee9200682011-05-13 03:29:01 +00002791bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2792 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002793
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002794 switch (E->getCastKind()) {
2795 default:
Richard Smith11562c52011-10-28 17:51:58 +00002796 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002797
2798 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002799 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002800 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002801 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002802 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002803 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002804 return true;
2805 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002806
2807 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002808 if (!Visit(SubExpr))
2809 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002810 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2811 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002812 return true;
2813 }
John McCalld7646252010-11-14 08:17:51 +00002814
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002815 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002816 ComplexValue V;
2817 if (!EvaluateComplex(SubExpr, V, Info))
2818 return false;
2819 Result = V.getComplexFloatReal();
2820 return true;
2821 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002822 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002823
2824 return false;
2825}
2826
Eli Friedman24c01542008-08-22 00:06:13 +00002827//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002828// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002829//===----------------------------------------------------------------------===//
2830
2831namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002832class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002833 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002834 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002835
Anders Carlsson537969c2008-11-16 20:27:53 +00002836public:
John McCall93d91dc2010-05-07 17:22:02 +00002837 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002838 : ExprEvaluatorBaseTy(info), Result(Result) {}
2839
Richard Smith0b0a0b62011-10-29 20:57:55 +00002840 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002841 Result.setFrom(V);
2842 return true;
2843 }
2844 bool Error(const Expr *E) {
2845 return false;
2846 }
Mike Stump11289f42009-09-09 15:08:12 +00002847
Anders Carlsson537969c2008-11-16 20:27:53 +00002848 //===--------------------------------------------------------------------===//
2849 // Visitor Methods
2850 //===--------------------------------------------------------------------===//
2851
Peter Collingbournee9200682011-05-13 03:29:01 +00002852 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002853
Peter Collingbournee9200682011-05-13 03:29:01 +00002854 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002855
John McCall93d91dc2010-05-07 17:22:02 +00002856 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002857 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002858 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002859};
2860} // end anonymous namespace
2861
John McCall93d91dc2010-05-07 17:22:02 +00002862static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2863 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002864 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002865 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002866}
2867
Peter Collingbournee9200682011-05-13 03:29:01 +00002868bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2869 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002870
2871 if (SubExpr->getType()->isRealFloatingType()) {
2872 Result.makeComplexFloat();
2873 APFloat &Imag = Result.FloatImag;
2874 if (!EvaluateFloat(SubExpr, Imag, Info))
2875 return false;
2876
2877 Result.FloatReal = APFloat(Imag.getSemantics());
2878 return true;
2879 } else {
2880 assert(SubExpr->getType()->isIntegerType() &&
2881 "Unexpected imaginary literal.");
2882
2883 Result.makeComplexInt();
2884 APSInt &Imag = Result.IntImag;
2885 if (!EvaluateInteger(SubExpr, Imag, Info))
2886 return false;
2887
2888 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2889 return true;
2890 }
2891}
2892
Peter Collingbournee9200682011-05-13 03:29:01 +00002893bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002894
John McCallfcef3cf2010-12-14 17:51:41 +00002895 switch (E->getCastKind()) {
2896 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002897 case CK_BaseToDerived:
2898 case CK_DerivedToBase:
2899 case CK_UncheckedDerivedToBase:
2900 case CK_Dynamic:
2901 case CK_ToUnion:
2902 case CK_ArrayToPointerDecay:
2903 case CK_FunctionToPointerDecay:
2904 case CK_NullToPointer:
2905 case CK_NullToMemberPointer:
2906 case CK_BaseToDerivedMemberPointer:
2907 case CK_DerivedToBaseMemberPointer:
2908 case CK_MemberPointerToBoolean:
2909 case CK_ConstructorConversion:
2910 case CK_IntegralToPointer:
2911 case CK_PointerToIntegral:
2912 case CK_PointerToBoolean:
2913 case CK_ToVoid:
2914 case CK_VectorSplat:
2915 case CK_IntegralCast:
2916 case CK_IntegralToBoolean:
2917 case CK_IntegralToFloating:
2918 case CK_FloatingToIntegral:
2919 case CK_FloatingToBoolean:
2920 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002921 case CK_CPointerToObjCPointerCast:
2922 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002923 case CK_AnyPointerToBlockPointerCast:
2924 case CK_ObjCObjectLValueCast:
2925 case CK_FloatingComplexToReal:
2926 case CK_FloatingComplexToBoolean:
2927 case CK_IntegralComplexToReal:
2928 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002929 case CK_ARCProduceObject:
2930 case CK_ARCConsumeObject:
2931 case CK_ARCReclaimReturnedObject:
2932 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002933 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002934
John McCallfcef3cf2010-12-14 17:51:41 +00002935 case CK_LValueToRValue:
2936 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002937 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002938
2939 case CK_Dependent:
2940 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002941 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002942 case CK_UserDefinedConversion:
2943 return false;
2944
2945 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002946 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002947 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002948 return false;
2949
John McCallfcef3cf2010-12-14 17:51:41 +00002950 Result.makeComplexFloat();
2951 Result.FloatImag = APFloat(Real.getSemantics());
2952 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002953 }
2954
John McCallfcef3cf2010-12-14 17:51:41 +00002955 case CK_FloatingComplexCast: {
2956 if (!Visit(E->getSubExpr()))
2957 return false;
2958
2959 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2960 QualType From
2961 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2962
2963 Result.FloatReal
2964 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2965 Result.FloatImag
2966 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2967 return true;
2968 }
2969
2970 case CK_FloatingComplexToIntegralComplex: {
2971 if (!Visit(E->getSubExpr()))
2972 return false;
2973
2974 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2975 QualType From
2976 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2977 Result.makeComplexInt();
2978 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2979 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2980 return true;
2981 }
2982
2983 case CK_IntegralRealToComplex: {
2984 APSInt &Real = Result.IntReal;
2985 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2986 return false;
2987
2988 Result.makeComplexInt();
2989 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2990 return true;
2991 }
2992
2993 case CK_IntegralComplexCast: {
2994 if (!Visit(E->getSubExpr()))
2995 return false;
2996
2997 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2998 QualType From
2999 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3000
3001 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3002 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3003 return true;
3004 }
3005
3006 case CK_IntegralComplexToFloatingComplex: {
3007 if (!Visit(E->getSubExpr()))
3008 return false;
3009
3010 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3011 QualType From
3012 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3013 Result.makeComplexFloat();
3014 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3015 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3016 return true;
3017 }
3018 }
3019
3020 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003021 return false;
3022}
3023
John McCall93d91dc2010-05-07 17:22:02 +00003024bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003025 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003026 VisitIgnoredValue(E->getLHS());
3027 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003028 }
John McCall93d91dc2010-05-07 17:22:02 +00003029 if (!Visit(E->getLHS()))
3030 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003031
John McCall93d91dc2010-05-07 17:22:02 +00003032 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003033 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003034 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003035
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003036 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3037 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003038 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003039 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003040 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003041 if (Result.isComplexFloat()) {
3042 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3043 APFloat::rmNearestTiesToEven);
3044 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3045 APFloat::rmNearestTiesToEven);
3046 } else {
3047 Result.getComplexIntReal() += RHS.getComplexIntReal();
3048 Result.getComplexIntImag() += RHS.getComplexIntImag();
3049 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003050 break;
John McCalle3027922010-08-25 11:45:40 +00003051 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003052 if (Result.isComplexFloat()) {
3053 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3054 APFloat::rmNearestTiesToEven);
3055 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3056 APFloat::rmNearestTiesToEven);
3057 } else {
3058 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3059 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3060 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003061 break;
John McCalle3027922010-08-25 11:45:40 +00003062 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003063 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003064 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003065 APFloat &LHS_r = LHS.getComplexFloatReal();
3066 APFloat &LHS_i = LHS.getComplexFloatImag();
3067 APFloat &RHS_r = RHS.getComplexFloatReal();
3068 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003069
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003070 APFloat Tmp = LHS_r;
3071 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3072 Result.getComplexFloatReal() = Tmp;
3073 Tmp = LHS_i;
3074 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3075 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3076
3077 Tmp = LHS_r;
3078 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3079 Result.getComplexFloatImag() = Tmp;
3080 Tmp = LHS_i;
3081 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3082 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3083 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003084 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003085 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003086 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3087 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003088 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003089 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3090 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3091 }
3092 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003093 case BO_Div:
3094 if (Result.isComplexFloat()) {
3095 ComplexValue LHS = Result;
3096 APFloat &LHS_r = LHS.getComplexFloatReal();
3097 APFloat &LHS_i = LHS.getComplexFloatImag();
3098 APFloat &RHS_r = RHS.getComplexFloatReal();
3099 APFloat &RHS_i = RHS.getComplexFloatImag();
3100 APFloat &Res_r = Result.getComplexFloatReal();
3101 APFloat &Res_i = Result.getComplexFloatImag();
3102
3103 APFloat Den = RHS_r;
3104 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3105 APFloat Tmp = RHS_i;
3106 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3107 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3108
3109 Res_r = LHS_r;
3110 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3111 Tmp = LHS_i;
3112 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3113 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3114 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3115
3116 Res_i = LHS_i;
3117 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3118 Tmp = LHS_r;
3119 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3120 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3121 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3122 } else {
3123 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3124 // FIXME: what about diagnostics?
3125 return false;
3126 }
3127 ComplexValue LHS = Result;
3128 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3129 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3130 Result.getComplexIntReal() =
3131 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3132 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3133 Result.getComplexIntImag() =
3134 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3135 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3136 }
3137 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003138 }
3139
John McCall93d91dc2010-05-07 17:22:02 +00003140 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003141}
3142
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003143bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3144 // Get the operand value into 'Result'.
3145 if (!Visit(E->getSubExpr()))
3146 return false;
3147
3148 switch (E->getOpcode()) {
3149 default:
3150 // FIXME: what about diagnostics?
3151 return false;
3152 case UO_Extension:
3153 return true;
3154 case UO_Plus:
3155 // The result is always just the subexpr.
3156 return true;
3157 case UO_Minus:
3158 if (Result.isComplexFloat()) {
3159 Result.getComplexFloatReal().changeSign();
3160 Result.getComplexFloatImag().changeSign();
3161 }
3162 else {
3163 Result.getComplexIntReal() = -Result.getComplexIntReal();
3164 Result.getComplexIntImag() = -Result.getComplexIntImag();
3165 }
3166 return true;
3167 case UO_Not:
3168 if (Result.isComplexFloat())
3169 Result.getComplexFloatImag().changeSign();
3170 else
3171 Result.getComplexIntImag() = -Result.getComplexIntImag();
3172 return true;
3173 }
3174}
3175
Anders Carlsson537969c2008-11-16 20:27:53 +00003176//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003177// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003178//===----------------------------------------------------------------------===//
3179
Richard Smith0b0a0b62011-10-29 20:57:55 +00003180static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003181 // In C, function designators are not lvalues, but we evaluate them as if they
3182 // are.
3183 if (E->isGLValue() || E->getType()->isFunctionType()) {
3184 LValue LV;
3185 if (!EvaluateLValue(E, LV, Info))
3186 return false;
3187 LV.moveInto(Result);
3188 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003189 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003190 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003191 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003192 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003193 return false;
John McCall45d55e42010-05-07 21:00:08 +00003194 } else if (E->getType()->hasPointerRepresentation()) {
3195 LValue LV;
3196 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003197 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003198 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003199 } else if (E->getType()->isRealFloatingType()) {
3200 llvm::APFloat F(0.0);
3201 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003202 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003203 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003204 } else if (E->getType()->isAnyComplexType()) {
3205 ComplexValue C;
3206 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003207 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003208 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00003209 } else if (E->getType()->isMemberPointerType()) {
3210 // FIXME: Implement evaluation of pointer-to-member types.
3211 return false;
3212 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
3213 // FIXME: Implement evaluation of array rvalues.
3214 return false;
3215 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3216 // FIXME: Implement evaluation of record rvalues.
3217 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003218 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003219 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003220
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003221 return true;
3222}
3223
Richard Smithed5165f2011-11-04 05:33:44 +00003224/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3225/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3226/// since later initializers for an object can indirectly refer to subobjects
3227/// which were initialized earlier.
3228static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3229 const Expr *E) {
3230 if (E->isRValue() && E->getType()->isLiteralType()) {
3231 // Evaluate arrays and record types in-place, so that later initializers can
3232 // refer to earlier-initialized members of the object.
3233 if (E->getType()->isArrayType())
3234 // FIXME: Implement evaluation of array rvalues.
3235 return false;
3236 else if (E->getType()->isRecordType())
3237 // FIXME: Implement evaluation of record rvalues.
3238 return false;
3239 }
3240
3241 // For any other type, in-place evaluation is unimportant.
3242 CCValue CoreConstResult;
3243 return Evaluate(CoreConstResult, Info, E) &&
3244 CheckConstantExpression(CoreConstResult, Result);
3245}
3246
Richard Smith11562c52011-10-28 17:51:58 +00003247
Richard Smith7b553f12011-10-29 00:50:52 +00003248/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003249/// any crazy technique (that has nothing to do with language standards) that
3250/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003251/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3252/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003253bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCallc07a0c72011-02-17 10:25:35 +00003254 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003255
Richard Smith0b0a0b62011-10-29 20:57:55 +00003256 CCValue Value;
3257 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003258 return false;
3259
3260 if (isGLValue()) {
3261 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003262 LV.setFrom(Value);
3263 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3264 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003265 }
3266
Richard Smith0b0a0b62011-10-29 20:57:55 +00003267 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00003268 // convert it to one.
3269 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00003270}
3271
Jay Foad39c79802011-01-12 09:06:06 +00003272bool Expr::EvaluateAsBooleanCondition(bool &Result,
3273 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003274 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003275 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003276 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003277 Result);
John McCall1be1c632010-01-05 23:42:56 +00003278}
3279
Richard Smithcaf33902011-10-10 18:28:20 +00003280bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003281 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003282 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003283 !ExprResult.Val.isInt()) {
3284 return false;
3285 }
3286 Result = ExprResult.Val.getInt();
3287 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003288}
3289
Jay Foad39c79802011-01-12 09:06:06 +00003290bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003291 EvalInfo Info(Ctx, Result);
3292
John McCall45d55e42010-05-07 21:00:08 +00003293 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00003294 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003295 IsGlobalLValue(LV.Base)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003296 Result.Val = APValue(LV.Base, LV.Offset);
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003297 return true;
3298 }
3299 return false;
3300}
3301
Jay Foad39c79802011-01-12 09:06:06 +00003302bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
3303 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003304 EvalInfo Info(Ctx, Result);
3305
3306 LValue LV;
Richard Smithfec09922011-11-01 16:57:24 +00003307 if (EvaluateLValue(this, LV, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003308 Result.Val = APValue(LV.Base, LV.Offset);
John McCall45d55e42010-05-07 21:00:08 +00003309 return true;
3310 }
3311 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00003312}
3313
Richard Smith7b553f12011-10-29 00:50:52 +00003314/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3315/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003316bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003317 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003318 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003319}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003320
Jay Foad39c79802011-01-12 09:06:06 +00003321bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003322 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003323}
3324
Richard Smithcaf33902011-10-10 18:28:20 +00003325APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003326 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003327 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003328 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003329 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003330 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003331
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003332 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003333}
John McCall864e3962010-05-07 05:32:02 +00003334
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003335 bool Expr::EvalResult::isGlobalLValue() const {
3336 assert(Val.isLValue());
3337 return IsGlobalLValue(Val.getLValueBase());
3338 }
3339
3340
John McCall864e3962010-05-07 05:32:02 +00003341/// isIntegerConstantExpr - this recursive routine will test if an expression is
3342/// an integer constant expression.
3343
3344/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3345/// comma, etc
3346///
3347/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3348/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3349/// cast+dereference.
3350
3351// CheckICE - This function does the fundamental ICE checking: the returned
3352// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3353// Note that to reduce code duplication, this helper does no evaluation
3354// itself; the caller checks whether the expression is evaluatable, and
3355// in the rare cases where CheckICE actually cares about the evaluated
3356// value, it calls into Evalute.
3357//
3358// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003359// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003360// 1: This expression is not an ICE, but if it isn't evaluated, it's
3361// a legal subexpression for an ICE. This return value is used to handle
3362// the comma operator in C99 mode.
3363// 2: This expression is not an ICE, and is not a legal subexpression for one.
3364
Dan Gohman28ade552010-07-26 21:25:24 +00003365namespace {
3366
John McCall864e3962010-05-07 05:32:02 +00003367struct ICEDiag {
3368 unsigned Val;
3369 SourceLocation Loc;
3370
3371 public:
3372 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3373 ICEDiag() : Val(0) {}
3374};
3375
Dan Gohman28ade552010-07-26 21:25:24 +00003376}
3377
3378static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003379
3380static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3381 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003382 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003383 !EVResult.Val.isInt()) {
3384 return ICEDiag(2, E->getLocStart());
3385 }
3386 return NoDiag();
3387}
3388
3389static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3390 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00003391 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00003392 return ICEDiag(2, E->getLocStart());
3393 }
3394
3395 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00003396#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00003397#define STMT(Node, Base) case Expr::Node##Class:
3398#define EXPR(Node, Base)
3399#include "clang/AST/StmtNodes.inc"
3400 case Expr::PredefinedExprClass:
3401 case Expr::FloatingLiteralClass:
3402 case Expr::ImaginaryLiteralClass:
3403 case Expr::StringLiteralClass:
3404 case Expr::ArraySubscriptExprClass:
3405 case Expr::MemberExprClass:
3406 case Expr::CompoundAssignOperatorClass:
3407 case Expr::CompoundLiteralExprClass:
3408 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00003409 case Expr::DesignatedInitExprClass:
3410 case Expr::ImplicitValueInitExprClass:
3411 case Expr::ParenListExprClass:
3412 case Expr::VAArgExprClass:
3413 case Expr::AddrLabelExprClass:
3414 case Expr::StmtExprClass:
3415 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00003416 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00003417 case Expr::CXXDynamicCastExprClass:
3418 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00003419 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00003420 case Expr::CXXNullPtrLiteralExprClass:
3421 case Expr::CXXThisExprClass:
3422 case Expr::CXXThrowExprClass:
3423 case Expr::CXXNewExprClass:
3424 case Expr::CXXDeleteExprClass:
3425 case Expr::CXXPseudoDestructorExprClass:
3426 case Expr::UnresolvedLookupExprClass:
3427 case Expr::DependentScopeDeclRefExprClass:
3428 case Expr::CXXConstructExprClass:
3429 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00003430 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00003431 case Expr::CXXTemporaryObjectExprClass:
3432 case Expr::CXXUnresolvedConstructExprClass:
3433 case Expr::CXXDependentScopeMemberExprClass:
3434 case Expr::UnresolvedMemberExprClass:
3435 case Expr::ObjCStringLiteralClass:
3436 case Expr::ObjCEncodeExprClass:
3437 case Expr::ObjCMessageExprClass:
3438 case Expr::ObjCSelectorExprClass:
3439 case Expr::ObjCProtocolExprClass:
3440 case Expr::ObjCIvarRefExprClass:
3441 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00003442 case Expr::ObjCIsaExprClass:
3443 case Expr::ShuffleVectorExprClass:
3444 case Expr::BlockExprClass:
3445 case Expr::BlockDeclRefExprClass:
3446 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00003447 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00003448 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00003449 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00003450 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00003451 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00003452 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00003453 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003454 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00003455 return ICEDiag(2, E->getLocStart());
3456
Sebastian Redl12757ab2011-09-24 17:48:14 +00003457 case Expr::InitListExprClass:
3458 if (Ctx.getLangOptions().CPlusPlus0x) {
3459 const InitListExpr *ILE = cast<InitListExpr>(E);
3460 if (ILE->getNumInits() == 0)
3461 return NoDiag();
3462 if (ILE->getNumInits() == 1)
3463 return CheckICE(ILE->getInit(0), Ctx);
3464 // Fall through for more than 1 expression.
3465 }
3466 return ICEDiag(2, E->getLocStart());
3467
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003468 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003469 case Expr::GNUNullExprClass:
3470 // GCC considers the GNU __null value to be an integral constant expression.
3471 return NoDiag();
3472
John McCall7c454bb2011-07-15 05:09:51 +00003473 case Expr::SubstNonTypeTemplateParmExprClass:
3474 return
3475 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3476
John McCall864e3962010-05-07 05:32:02 +00003477 case Expr::ParenExprClass:
3478 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003479 case Expr::GenericSelectionExprClass:
3480 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003481 case Expr::IntegerLiteralClass:
3482 case Expr::CharacterLiteralClass:
3483 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003484 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003485 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003486 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003487 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003488 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003489 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003490 return NoDiag();
3491 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003492 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003493 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3494 // constant expressions, but they can never be ICEs because an ICE cannot
3495 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003496 const CallExpr *CE = cast<CallExpr>(E);
3497 if (CE->isBuiltinCall(Ctx))
3498 return CheckEvalInICE(E, Ctx);
3499 return ICEDiag(2, E->getLocStart());
3500 }
3501 case Expr::DeclRefExprClass:
3502 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3503 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003504 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003505 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3506
3507 // Parameter variables are never constants. Without this check,
3508 // getAnyInitializer() can find a default argument, which leads
3509 // to chaos.
3510 if (isa<ParmVarDecl>(D))
3511 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3512
3513 // C++ 7.1.5.1p2
3514 // A variable of non-volatile const-qualified integral or enumeration
3515 // type initialized by an ICE can be used in ICEs.
3516 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003517 // Look for a declaration of this variable that has an initializer.
3518 const VarDecl *ID = 0;
3519 const Expr *Init = Dcl->getAnyInitializer(ID);
3520 if (Init) {
3521 if (ID->isInitKnownICE()) {
3522 // We have already checked whether this subexpression is an
3523 // integral constant expression.
3524 if (ID->isInitICE())
3525 return NoDiag();
3526 else
3527 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3528 }
3529
3530 // It's an ICE whether or not the definition we found is
3531 // out-of-line. See DR 721 and the discussion in Clang PR
3532 // 6206 for details.
3533
3534 if (Dcl->isCheckingICE()) {
3535 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3536 }
3537
3538 Dcl->setCheckingICE();
3539 ICEDiag Result = CheckICE(Init, Ctx);
3540 // Cache the result of the ICE test.
3541 Dcl->setInitKnownICE(Result.Val == 0);
3542 return Result;
3543 }
3544 }
3545 }
3546 return ICEDiag(2, E->getLocStart());
3547 case Expr::UnaryOperatorClass: {
3548 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3549 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003550 case UO_PostInc:
3551 case UO_PostDec:
3552 case UO_PreInc:
3553 case UO_PreDec:
3554 case UO_AddrOf:
3555 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003556 // C99 6.6/3 allows increment and decrement within unevaluated
3557 // subexpressions of constant expressions, but they can never be ICEs
3558 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003559 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003560 case UO_Extension:
3561 case UO_LNot:
3562 case UO_Plus:
3563 case UO_Minus:
3564 case UO_Not:
3565 case UO_Real:
3566 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003567 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003568 }
3569
3570 // OffsetOf falls through here.
3571 }
3572 case Expr::OffsetOfExprClass: {
3573 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00003574 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003575 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003576 // compliance: we should warn earlier for offsetof expressions with
3577 // array subscripts that aren't ICEs, and if the array subscripts
3578 // are ICEs, the value of the offsetof must be an integer constant.
3579 return CheckEvalInICE(E, Ctx);
3580 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003581 case Expr::UnaryExprOrTypeTraitExprClass: {
3582 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3583 if ((Exp->getKind() == UETT_SizeOf) &&
3584 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003585 return ICEDiag(2, E->getLocStart());
3586 return NoDiag();
3587 }
3588 case Expr::BinaryOperatorClass: {
3589 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3590 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003591 case BO_PtrMemD:
3592 case BO_PtrMemI:
3593 case BO_Assign:
3594 case BO_MulAssign:
3595 case BO_DivAssign:
3596 case BO_RemAssign:
3597 case BO_AddAssign:
3598 case BO_SubAssign:
3599 case BO_ShlAssign:
3600 case BO_ShrAssign:
3601 case BO_AndAssign:
3602 case BO_XorAssign:
3603 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003604 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3605 // constant expressions, but they can never be ICEs because an ICE cannot
3606 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003607 return ICEDiag(2, E->getLocStart());
3608
John McCalle3027922010-08-25 11:45:40 +00003609 case BO_Mul:
3610 case BO_Div:
3611 case BO_Rem:
3612 case BO_Add:
3613 case BO_Sub:
3614 case BO_Shl:
3615 case BO_Shr:
3616 case BO_LT:
3617 case BO_GT:
3618 case BO_LE:
3619 case BO_GE:
3620 case BO_EQ:
3621 case BO_NE:
3622 case BO_And:
3623 case BO_Xor:
3624 case BO_Or:
3625 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003626 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3627 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003628 if (Exp->getOpcode() == BO_Div ||
3629 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00003630 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00003631 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003632 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003633 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003634 if (REval == 0)
3635 return ICEDiag(1, E->getLocStart());
3636 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003637 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003638 if (LEval.isMinSignedValue())
3639 return ICEDiag(1, E->getLocStart());
3640 }
3641 }
3642 }
John McCalle3027922010-08-25 11:45:40 +00003643 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003644 if (Ctx.getLangOptions().C99) {
3645 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3646 // if it isn't evaluated.
3647 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3648 return ICEDiag(1, E->getLocStart());
3649 } else {
3650 // In both C89 and C++, commas in ICEs are illegal.
3651 return ICEDiag(2, E->getLocStart());
3652 }
3653 }
3654 if (LHSResult.Val >= RHSResult.Val)
3655 return LHSResult;
3656 return RHSResult;
3657 }
John McCalle3027922010-08-25 11:45:40 +00003658 case BO_LAnd:
3659 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003660 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003661
3662 // C++0x [expr.const]p2:
3663 // [...] subexpressions of logical AND (5.14), logical OR
3664 // (5.15), and condi- tional (5.16) operations that are not
3665 // evaluated are not considered.
3666 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3667 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003668 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003669 return LHSResult;
3670
3671 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003672 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003673 return LHSResult;
3674 }
3675
John McCall864e3962010-05-07 05:32:02 +00003676 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3677 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3678 // Rare case where the RHS has a comma "side-effect"; we need
3679 // to actually check the condition to see whether the side
3680 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003681 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003682 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003683 return RHSResult;
3684 return NoDiag();
3685 }
3686
3687 if (LHSResult.Val >= RHSResult.Val)
3688 return LHSResult;
3689 return RHSResult;
3690 }
3691 }
3692 }
3693 case Expr::ImplicitCastExprClass:
3694 case Expr::CStyleCastExprClass:
3695 case Expr::CXXFunctionalCastExprClass:
3696 case Expr::CXXStaticCastExprClass:
3697 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003698 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003699 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003700 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003701 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003702 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3703 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003704 switch (cast<CastExpr>(E)->getCastKind()) {
3705 case CK_LValueToRValue:
3706 case CK_NoOp:
3707 case CK_IntegralToBoolean:
3708 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003709 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003710 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003711 return ICEDiag(2, E->getLocStart());
3712 }
John McCall864e3962010-05-07 05:32:02 +00003713 }
John McCallc07a0c72011-02-17 10:25:35 +00003714 case Expr::BinaryConditionalOperatorClass: {
3715 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3716 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3717 if (CommonResult.Val == 2) return CommonResult;
3718 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3719 if (FalseResult.Val == 2) return FalseResult;
3720 if (CommonResult.Val == 1) return CommonResult;
3721 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003722 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003723 return FalseResult;
3724 }
John McCall864e3962010-05-07 05:32:02 +00003725 case Expr::ConditionalOperatorClass: {
3726 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3727 // If the condition (ignoring parens) is a __builtin_constant_p call,
3728 // then only the true side is actually considered in an integer constant
3729 // expression, and it is fully evaluated. This is an important GNU
3730 // extension. See GCC PR38377 for discussion.
3731 if (const CallExpr *CallCE
3732 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3733 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3734 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003735 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003736 !EVResult.Val.isInt()) {
3737 return ICEDiag(2, E->getLocStart());
3738 }
3739 return NoDiag();
3740 }
3741 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003742 if (CondResult.Val == 2)
3743 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003744
3745 // C++0x [expr.const]p2:
3746 // subexpressions of [...] conditional (5.16) operations that
3747 // are not evaluated are not considered
3748 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003749 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003750 : false;
3751 ICEDiag TrueResult = NoDiag();
3752 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3753 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3754 ICEDiag FalseResult = NoDiag();
3755 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3756 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3757
John McCall864e3962010-05-07 05:32:02 +00003758 if (TrueResult.Val == 2)
3759 return TrueResult;
3760 if (FalseResult.Val == 2)
3761 return FalseResult;
3762 if (CondResult.Val == 1)
3763 return CondResult;
3764 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3765 return NoDiag();
3766 // Rare case where the diagnostics depend on which side is evaluated
3767 // Note that if we get here, CondResult is 0, and at least one of
3768 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003769 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003770 return FalseResult;
3771 }
3772 return TrueResult;
3773 }
3774 case Expr::CXXDefaultArgExprClass:
3775 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3776 case Expr::ChooseExprClass: {
3777 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3778 }
3779 }
3780
3781 // Silence a GCC warning
3782 return ICEDiag(2, E->getLocStart());
3783}
3784
3785bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3786 SourceLocation *Loc, bool isEvaluated) const {
3787 ICEDiag d = CheckICE(this, Ctx);
3788 if (d.Val != 0) {
3789 if (Loc) *Loc = d.Loc;
3790 return false;
3791 }
Richard Smith11562c52011-10-28 17:51:58 +00003792 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003793 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003794 return true;
3795}