blob: 746b094619cafce44ad2ee16e690648d20319e5d [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-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 McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +000046 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000047 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000048
Richard Smith9a17a682011-11-07 05:07:52 +000049 /// Determine whether the described subobject is an array element.
50 static bool SubobjectIsArrayElement(QualType Base,
51 ArrayRef<APValue::LValuePathEntry> Path) {
52 bool IsArrayElement = false;
53 const Type *T = Base.getTypePtr();
54 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
55 IsArrayElement = T && T->isArrayType();
56 if (IsArrayElement)
57 T = T->getBaseElementTypeUnsafe();
58 else if (const FieldDecl *FD = dyn_cast<FieldDecl>(Path[I].BaseOrMember))
59 T = FD->getType().getTypePtr();
60 else
61 // Path[I] describes a base class.
62 T = 0;
63 }
64 return IsArrayElement;
65 }
66
Richard Smith0a3bdb62011-11-04 02:25:55 +000067 /// A path from a glvalue to a subobject of that glvalue.
68 struct SubobjectDesignator {
69 /// True if the subobject was named in a manner not supported by C++11. Such
70 /// lvalues can still be folded, but they are not core constant expressions
71 /// and we cannot perform lvalue-to-rvalue conversions on them.
72 bool Invalid : 1;
73
74 /// Whether this designates an array element.
75 bool ArrayElement : 1;
76
77 /// Whether this designates 'one past the end' of the current subobject.
78 bool OnePastTheEnd : 1;
79
Richard Smith9a17a682011-11-07 05:07:52 +000080 typedef APValue::LValuePathEntry PathEntry;
81
Richard Smith0a3bdb62011-11-04 02:25:55 +000082 /// The entries on the path from the glvalue to the designated subobject.
83 SmallVector<PathEntry, 8> Entries;
84
85 SubobjectDesignator() :
86 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
87
Richard Smith9a17a682011-11-07 05:07:52 +000088 SubobjectDesignator(const APValue &V) :
89 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
90 OnePastTheEnd(false) {
91 if (!Invalid) {
92 ArrayRef<PathEntry> VEntries = V.getLValuePath();
93 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
94 if (V.getLValueBase())
95 ArrayElement = SubobjectIsArrayElement(V.getLValueBase()->getType(),
96 V.getLValuePath());
97 else
98 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
99 }
100 }
101
Richard Smith0a3bdb62011-11-04 02:25:55 +0000102 void setInvalid() {
103 Invalid = true;
104 Entries.clear();
105 }
106 /// Update this designator to refer to the given element within this array.
107 void addIndex(uint64_t N) {
108 if (Invalid) return;
109 if (OnePastTheEnd) {
110 setInvalid();
111 return;
112 }
113 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000114 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000115 Entries.push_back(Entry);
116 ArrayElement = true;
117 }
118 /// Update this designator to refer to the given base or member of this
119 /// object.
120 void addDecl(const Decl *D) {
121 if (Invalid) return;
122 if (OnePastTheEnd) {
123 setInvalid();
124 return;
125 }
126 PathEntry Entry;
127 Entry.BaseOrMember = D;
128 Entries.push_back(Entry);
129 ArrayElement = false;
130 }
131 /// Add N to the address of this subobject.
132 void adjustIndex(uint64_t N) {
133 if (Invalid) return;
134 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000135 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000136 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000137 return;
138 }
139 if (OnePastTheEnd && N == (uint64_t)-1)
140 OnePastTheEnd = false;
141 else if (!OnePastTheEnd && N == 1)
142 OnePastTheEnd = true;
143 else if (N != 0)
144 setInvalid();
145 }
146 };
147
Richard Smith47a1eed2011-10-29 20:57:55 +0000148 /// A core constant value. This can be the value of any constant expression,
149 /// or a pointer or reference to a non-static object or function parameter.
150 class CCValue : public APValue {
151 typedef llvm::APSInt APSInt;
152 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000153 /// If the value is a reference or pointer into a parameter or temporary,
154 /// this is the corresponding call stack frame.
155 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000156 /// If the value is a reference or pointer, this is a description of how the
157 /// subobject was specified.
158 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000159 public:
Richard Smith177dce72011-11-01 16:57:24 +0000160 struct GlobalValue {};
161
Richard Smith47a1eed2011-10-29 20:57:55 +0000162 CCValue() {}
163 explicit CCValue(const APSInt &I) : APValue(I) {}
164 explicit CCValue(const APFloat &F) : APValue(F) {}
165 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
166 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
167 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000168 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000169 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
170 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000171 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000172 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000173 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000174
Richard Smith177dce72011-11-01 16:57:24 +0000175 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000176 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000177 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000178 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 SubobjectDesignator &getLValueDesignator() {
180 assert(getKind() == LValue);
181 return Designator;
182 }
183 const SubobjectDesignator &getLValueDesignator() const {
184 return const_cast<CCValue*>(this)->getLValueDesignator();
185 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 };
187
Richard Smithd0dccea2011-10-28 22:34:42 +0000188 /// A stack frame in the constexpr call stack.
189 struct CallStackFrame {
190 EvalInfo &Info;
191
192 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000193 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000194
195 /// ParmBindings - Parameter bindings for this function call, indexed by
196 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000197 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000198
Richard Smithbd552ef2011-10-31 05:52:43 +0000199 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
200 typedef MapTy::const_iterator temp_iterator;
201 /// Temporaries - Temporary lvalues materialized within this stack frame.
202 MapTy Temporaries;
203
204 CallStackFrame(EvalInfo &Info, const CCValue *Arguments);
205 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000206 };
207
Richard Smithbd552ef2011-10-31 05:52:43 +0000208 struct EvalInfo {
209 const ASTContext &Ctx;
210
211 /// EvalStatus - Contains information about the evaluation.
212 Expr::EvalStatus &EvalStatus;
213
214 /// CurrentCall - The top of the constexpr call stack.
215 CallStackFrame *CurrentCall;
216
217 /// NumCalls - The number of calls we've evaluated so far.
218 unsigned NumCalls;
219
220 /// CallStackDepth - The number of calls in the call stack right now.
221 unsigned CallStackDepth;
222
223 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
224 /// OpaqueValues - Values used as the common expression in a
225 /// BinaryConditionalOperator.
226 MapTy OpaqueValues;
227
228 /// BottomFrame - The frame in which evaluation started. This must be
229 /// initialized last.
230 CallStackFrame BottomFrame;
231
232
233 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
234 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
235 BottomFrame(*this, 0) {}
236
Richard Smithbd552ef2011-10-31 05:52:43 +0000237 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
238 MapTy::const_iterator i = OpaqueValues.find(e);
239 if (i == OpaqueValues.end()) return 0;
240 return &i->second;
241 }
242
243 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
244 };
245
246 CallStackFrame::CallStackFrame(EvalInfo &Info, const CCValue *Arguments)
Richard Smith177dce72011-11-01 16:57:24 +0000247 : Info(Info), Caller(Info.CurrentCall), Arguments(Arguments) {
Richard Smithbd552ef2011-10-31 05:52:43 +0000248 Info.CurrentCall = this;
249 ++Info.CallStackDepth;
250 }
251
252 CallStackFrame::~CallStackFrame() {
253 assert(Info.CurrentCall == this && "calls retired out of order");
254 --Info.CallStackDepth;
255 Info.CurrentCall = Caller;
256 }
257
John McCallf4cf1a12010-05-07 17:22:02 +0000258 struct ComplexValue {
259 private:
260 bool IsInt;
261
262 public:
263 APSInt IntReal, IntImag;
264 APFloat FloatReal, FloatImag;
265
266 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
267
268 void makeComplexFloat() { IsInt = false; }
269 bool isComplexFloat() const { return !IsInt; }
270 APFloat &getComplexFloatReal() { return FloatReal; }
271 APFloat &getComplexFloatImag() { return FloatImag; }
272
273 void makeComplexInt() { IsInt = true; }
274 bool isComplexInt() const { return IsInt; }
275 APSInt &getComplexIntReal() { return IntReal; }
276 APSInt &getComplexIntImag() { return IntImag; }
277
Richard Smith47a1eed2011-10-29 20:57:55 +0000278 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000279 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000280 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000281 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000282 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000283 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000284 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000285 assert(v.isComplexFloat() || v.isComplexInt());
286 if (v.isComplexFloat()) {
287 makeComplexFloat();
288 FloatReal = v.getComplexFloatReal();
289 FloatImag = v.getComplexFloatImag();
290 } else {
291 makeComplexInt();
292 IntReal = v.getComplexIntReal();
293 IntImag = v.getComplexIntImag();
294 }
295 }
John McCallf4cf1a12010-05-07 17:22:02 +0000296 };
John McCallefdb83e2010-05-07 21:00:08 +0000297
298 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000299 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000300 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000301 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000302 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000303
Richard Smith625b8072011-10-31 01:37:14 +0000304 const Expr *getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000305 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000306 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000307 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000308 SubobjectDesignator &getLValueDesignator() { return Designator; }
309 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000310
Richard Smith47a1eed2011-10-29 20:57:55 +0000311 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000312 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000313 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000314 void setFrom(const CCValue &V) {
315 assert(V.isLValue());
316 Base = V.getLValueBase();
317 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000318 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000319 Designator = V.getLValueDesignator();
320 }
321
322 void setExpr(const Expr *E, CallStackFrame *F = 0) {
323 Base = E;
324 Offset = CharUnits::Zero();
325 Frame = F;
326 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000327 }
John McCallefdb83e2010-05-07 21:00:08 +0000328 };
John McCallf4cf1a12010-05-07 17:22:02 +0000329}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000330
Richard Smith47a1eed2011-10-29 20:57:55 +0000331static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000332static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
333 const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000334static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
335static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000336static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000337static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000338 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000339static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000340static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000341
342//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000343// Misc utilities
344//===----------------------------------------------------------------------===//
345
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000346static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000347 if (!E) return true;
348
349 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
350 if (isa<FunctionDecl>(DRE->getDecl()))
351 return true;
352 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
353 return VD->hasGlobalStorage();
354 return false;
355 }
356
357 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
358 return CLE->isFileScope();
359
Richard Smithbd552ef2011-10-31 05:52:43 +0000360 if (isa<MemberExpr>(E) || isa<MaterializeTemporaryExpr>(E))
Richard Smithc49bd112011-10-28 17:51:58 +0000361 return false;
362
John McCall42c8f872010-05-10 23:27:23 +0000363 return true;
364}
365
Richard Smith9a17a682011-11-07 05:07:52 +0000366/// Check that this reference or pointer core constant expression is a valid
367/// value for a constant expression. Type T should be either LValue or CCValue.
368template<typename T>
369static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
370 if (!IsGlobalLValue(LVal.getLValueBase()))
371 return false;
372
373 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
374 // A constant expression must refer to an object or be a null pointer.
375 if (Designator.Invalid || Designator.OnePastTheEnd ||
376 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
377 // FIXME: Check for out-of-bounds array indices.
378 // FIXME: This is not a constant expression.
379 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
380 APValue::NoLValuePath());
381 return true;
382 }
383
384 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
385 Designator.Entries);
386 return true;
387}
388
Richard Smith47a1eed2011-10-29 20:57:55 +0000389/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000390/// constant expression, and if it is, produce the corresponding constant value.
391static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith9a17a682011-11-07 05:07:52 +0000392 if (!CCValue.isLValue()) {
393 Value = CCValue;
394 return true;
395 }
396 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith47a1eed2011-10-29 20:57:55 +0000397}
398
Richard Smith9e36b532011-10-31 05:11:32 +0000399const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
400 if (!LVal.Base)
401 return 0;
402
403 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
404 return DRE->getDecl();
405
406 // FIXME: Static data members accessed via a MemberExpr are represented as
407 // that MemberExpr. We should use the Decl directly instead.
408 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
409 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
410 return ME->getMemberDecl();
411 }
412
413 return 0;
414}
415
416static bool IsLiteralLValue(const LValue &Value) {
417 return Value.Base &&
418 !isa<DeclRefExpr>(Value.Base) &&
Richard Smithbd552ef2011-10-31 05:52:43 +0000419 !isa<MemberExpr>(Value.Base) &&
420 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith9e36b532011-10-31 05:11:32 +0000421}
422
Richard Smith65ac5982011-11-01 21:06:14 +0000423static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith9e36b532011-10-31 05:11:32 +0000424 return Decl->hasAttr<WeakAttr>() ||
425 Decl->hasAttr<WeakRefAttr>() ||
426 Decl->isWeakImported();
427}
428
Richard Smith65ac5982011-11-01 21:06:14 +0000429static bool IsWeakLValue(const LValue &Value) {
430 const ValueDecl *Decl = GetLValueBaseDecl(Value);
431 return Decl && IsWeakDecl(Decl);
432}
433
Richard Smithc49bd112011-10-28 17:51:58 +0000434static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCallefdb83e2010-05-07 21:00:08 +0000435 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000436
John McCall35542832010-05-07 21:34:32 +0000437 // A null base expression indicates a null pointer. These are always
438 // evaluatable, and they are false unless the offset is zero.
439 if (!Base) {
440 Result = !Value.Offset.isZero();
441 return true;
442 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000443
John McCall42c8f872010-05-10 23:27:23 +0000444 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000445 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000446 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000447
John McCall35542832010-05-07 21:34:32 +0000448 // We have a non-null base expression. These are generally known to
449 // be true, but if it'a decl-ref to a weak symbol it can be null at
450 // runtime.
John McCall35542832010-05-07 21:34:32 +0000451 Result = true;
Richard Smith9e36b532011-10-31 05:11:32 +0000452 return !IsWeakLValue(Value);
Eli Friedman5bc86102009-06-14 02:17:33 +0000453}
454
Richard Smith47a1eed2011-10-29 20:57:55 +0000455static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000456 switch (Val.getKind()) {
457 case APValue::Uninitialized:
458 return false;
459 case APValue::Int:
460 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000461 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000462 case APValue::Float:
463 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000464 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000465 case APValue::ComplexInt:
466 Result = Val.getComplexIntReal().getBoolValue() ||
467 Val.getComplexIntImag().getBoolValue();
468 return true;
469 case APValue::ComplexFloat:
470 Result = !Val.getComplexFloatReal().isZero() ||
471 !Val.getComplexFloatImag().isZero();
472 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +0000473 case APValue::LValue: {
474 LValue PointerResult;
475 PointerResult.setFrom(Val);
476 return EvalPointerValueAsBool(PointerResult, Result);
477 }
Richard Smithc49bd112011-10-28 17:51:58 +0000478 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000479 case APValue::Array:
Richard Smithc49bd112011-10-28 17:51:58 +0000480 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000481 }
482
Richard Smithc49bd112011-10-28 17:51:58 +0000483 llvm_unreachable("unknown APValue kind");
484}
485
486static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
487 EvalInfo &Info) {
488 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000489 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000490 if (!Evaluate(Val, Info, E))
491 return false;
492 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000493}
494
Mike Stump1eb44332009-09-09 15:08:12 +0000495static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000496 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000497 unsigned DestWidth = Ctx.getIntWidth(DestType);
498 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000499 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000501 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000502 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000503 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000504 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
505 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000506}
507
Mike Stump1eb44332009-09-09 15:08:12 +0000508static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000509 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000510 bool ignored;
511 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000512 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000513 APFloat::rmNearestTiesToEven, &ignored);
514 return Result;
515}
516
Mike Stump1eb44332009-09-09 15:08:12 +0000517static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000518 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000519 unsigned DestWidth = Ctx.getIntWidth(DestType);
520 APSInt Result = Value;
521 // Figure out if this is a truncate, extend or noop cast.
522 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000523 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000524 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000525 return Result;
526}
527
Mike Stump1eb44332009-09-09 15:08:12 +0000528static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000529 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000530
531 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
532 Result.convertFromAPInt(Value, Value.isSigned(),
533 APFloat::rmNearestTiesToEven);
534 return Result;
535}
536
Richard Smith03f96112011-10-24 17:54:18 +0000537/// Try to evaluate the initializer for a variable declaration.
Richard Smith47a1eed2011-10-29 20:57:55 +0000538static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +0000539 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000540 // If this is a parameter to an active constexpr function call, perform
541 // argument substitution.
542 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith177dce72011-11-01 16:57:24 +0000543 if (!Frame || !Frame->Arguments)
544 return false;
545 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
546 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +0000547 }
Richard Smith03f96112011-10-24 17:54:18 +0000548
Richard Smith65ac5982011-11-01 21:06:14 +0000549 // Never evaluate the initializer of a weak variable. We can't be sure that
550 // this is the definition which will be used.
551 if (IsWeakDecl(VD))
552 return false;
553
Richard Smith03f96112011-10-24 17:54:18 +0000554 const Expr *Init = VD->getAnyInitializer();
555 if (!Init)
Richard Smith47a1eed2011-10-29 20:57:55 +0000556 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000557
Richard Smith47a1eed2011-10-29 20:57:55 +0000558 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +0000559 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000560 return !Result.isUninit();
561 }
Richard Smith03f96112011-10-24 17:54:18 +0000562
563 if (VD->isEvaluatingValue())
Richard Smith47a1eed2011-10-29 20:57:55 +0000564 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000565
566 VD->setEvaluatingValue();
567
Richard Smith47a1eed2011-10-29 20:57:55 +0000568 Expr::EvalStatus EStatus;
569 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithc49bd112011-10-28 17:51:58 +0000570 // FIXME: The caller will need to know whether the value was a constant
571 // expression. If not, we should propagate up a diagnostic.
Richard Smith69c2c502011-11-04 05:33:44 +0000572 APValue EvalResult;
573 if (!EvaluateConstantExpression(EvalResult, InitInfo, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000574 // FIXME: If the evaluation failure was not permanent (for instance, if we
575 // hit a variable with no declaration yet, or a constexpr function with no
576 // definition yet), the standard is unclear as to how we should behave.
577 //
578 // Either the initializer should be evaluated when the variable is defined,
579 // or a failed evaluation of the initializer should be reattempted each time
580 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +0000581 VD->setEvaluatedValue(APValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000582 return false;
583 }
Richard Smith03f96112011-10-24 17:54:18 +0000584
Richard Smith69c2c502011-11-04 05:33:44 +0000585 VD->setEvaluatedValue(EvalResult);
586 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000587 return true;
Richard Smith03f96112011-10-24 17:54:18 +0000588}
589
Richard Smithc49bd112011-10-28 17:51:58 +0000590static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +0000591 Qualifiers Quals = T.getQualifiers();
592 return Quals.hasConst() && !Quals.hasVolatile();
593}
594
Richard Smithcc5d4f62011-11-07 09:22:26 +0000595/// Extract the designated sub-object of an rvalue.
596static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
597 const SubobjectDesignator &Sub, QualType SubType) {
598 if (Sub.Invalid || Sub.OnePastTheEnd)
599 return false;
600 if (Sub.Entries.empty()) {
601 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
602 "Unexpected subobject type");
603 return true;
604 }
605
606 assert(!Obj.isLValue() && "extracting subobject of lvalue");
607 const APValue *O = &Obj;
608 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
609 if (O->isUninit())
610 return false;
611 if (ObjType->isArrayType()) {
612 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
613 if (!CAT)
614 return false;
615 uint64_t Index = Sub.Entries[I].ArrayIndex;
616 if (CAT->getSize().ule(Index))
617 return false;
618 if (O->getArrayInitializedElts() > Index)
619 O = &O->getArrayInitializedElt(Index);
620 else
621 O = &O->getArrayFiller();
622 ObjType = CAT->getElementType();
623 } else {
624 // FIXME: Support handling of subobjects of structs and unions. Also
625 // for vector elements, if we want to support those?
626 }
627 }
628
629 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
630 "Unexpected subobject type");
631 Obj = CCValue(*O, CCValue::GlobalValue());
632 return true;
633}
634
635static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
636 const LValue &LVal, CCValue &RVal) {
Richard Smithc49bd112011-10-28 17:51:58 +0000637 const Expr *Base = LVal.Base;
Richard Smith177dce72011-11-01 16:57:24 +0000638 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +0000639
640 // FIXME: Indirection through a null pointer deserves a diagnostic.
641 if (!Base)
642 return false;
643
Richard Smith625b8072011-10-31 01:37:14 +0000644 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smithc49bd112011-10-28 17:51:58 +0000645 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
646 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +0000647 // expressions are constant expressions too. Inside constexpr functions,
648 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +0000649 // In C, such things can also be folded, although they are not ICEs.
650 //
Richard Smithd0dccea2011-10-28 22:34:42 +0000651 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
652 // interpretation of C++11 suggests that volatile parameters are OK if
653 // they're never read (there's no prohibition against constructing volatile
654 // objects in constant expressions), but lvalue-to-rvalue conversions on
655 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +0000656 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000657 QualType VT = VD->getType();
Richard Smithcd689922011-11-07 03:22:51 +0000658 if (!VD || VD->isInvalidDecl())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000659 return false;
660 if (!isa<ParmVarDecl>(VD)) {
661 if (!IsConstNonVolatile(VT))
662 return false;
Richard Smithcd689922011-11-07 03:22:51 +0000663 // FIXME: Allow folding of values of any literal type in all languages.
664 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
665 !VD->isConstexpr())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000666 return false;
667 }
668 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +0000669 return false;
670
Richard Smith47a1eed2011-10-29 20:57:55 +0000671 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithcc5d4f62011-11-07 09:22:26 +0000672 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000673
674 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
675 // conversion. This happens when the declaration and the lvalue should be
676 // considered synonymous, for instance when initializing an array of char
677 // from a string literal. Continue as if the initializer lvalue was the
678 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +0000679 assert(RVal.getLValueOffset().isZero() &&
680 "offset for lvalue init of non-reference");
Richard Smith47a1eed2011-10-29 20:57:55 +0000681 Base = RVal.getLValueBase();
Richard Smith177dce72011-11-01 16:57:24 +0000682 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +0000683 }
684
Richard Smith0a3bdb62011-11-04 02:25:55 +0000685 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
686 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
687 const SubobjectDesignator &Designator = LVal.Designator;
688 if (Designator.Invalid || Designator.Entries.size() != 1)
689 return false;
690
691 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +0000692 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000693 if (Index > S->getLength())
694 return false;
695 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
696 Type->isUnsignedIntegerType());
697 if (Index < S->getLength())
698 Value = S->getCodeUnit(Index);
699 RVal = CCValue(Value);
700 return true;
701 }
702
Richard Smithcc5d4f62011-11-07 09:22:26 +0000703 if (Frame) {
704 // If this is a temporary expression with a nontrivial initializer, grab the
705 // value from the relevant stack frame.
706 RVal = Frame->Temporaries[Base];
707 } else if (const CompoundLiteralExpr *CLE
708 = dyn_cast<CompoundLiteralExpr>(Base)) {
709 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
710 // initializer until now for such expressions. Such an expression can't be
711 // an ICE in C, so this only matters for fold.
712 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
713 if (!Evaluate(RVal, Info, CLE->getInitializer()))
714 return false;
715 } else
Richard Smith0a3bdb62011-11-04 02:25:55 +0000716 return false;
717
Richard Smithcc5d4f62011-11-07 09:22:26 +0000718 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000719}
720
Mike Stumpc4c90452009-10-27 22:09:17 +0000721namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +0000722enum EvalStmtResult {
723 /// Evaluation failed.
724 ESR_Failed,
725 /// Hit a 'return' statement.
726 ESR_Returned,
727 /// Evaluation succeeded.
728 ESR_Succeeded
729};
730}
731
732// Evaluate a statement.
Richard Smith47a1eed2011-10-29 20:57:55 +0000733static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +0000734 const Stmt *S) {
735 switch (S->getStmtClass()) {
736 default:
737 return ESR_Failed;
738
739 case Stmt::NullStmtClass:
740 case Stmt::DeclStmtClass:
741 return ESR_Succeeded;
742
743 case Stmt::ReturnStmtClass:
744 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
745 return ESR_Returned;
746 return ESR_Failed;
747
748 case Stmt::CompoundStmtClass: {
749 const CompoundStmt *CS = cast<CompoundStmt>(S);
750 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
751 BE = CS->body_end(); BI != BE; ++BI) {
752 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
753 if (ESR != ESR_Succeeded)
754 return ESR;
755 }
756 return ESR_Succeeded;
757 }
758 }
759}
760
761/// Evaluate a function call.
762static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith47a1eed2011-10-29 20:57:55 +0000763 EvalInfo &Info, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000764 // FIXME: Implement a proper call limit, along with a command-line flag.
765 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
766 return false;
767
Richard Smith47a1eed2011-10-29 20:57:55 +0000768 SmallVector<CCValue, 16> ArgValues(Args.size());
Richard Smithd0dccea2011-10-28 22:34:42 +0000769 // FIXME: Deal with default arguments and 'this'.
770 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
771 I != E; ++I)
772 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
773 return false;
774
775 CallStackFrame Frame(Info, ArgValues.data());
776 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
777}
778
779namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000780class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000781 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +0000782 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +0000783public:
784
Richard Smith1e12c592011-10-16 21:26:27 +0000785 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +0000786
787 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000788 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000789 return true;
790 }
791
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000792 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
793 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000794 return Visit(E->getResultExpr());
795 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000796 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000797 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000798 return true;
799 return false;
800 }
John McCallf85e1932011-06-15 23:02:42 +0000801 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000802 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000803 return true;
804 return false;
805 }
806 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000807 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +0000808 return true;
809 return false;
810 }
811
Mike Stumpc4c90452009-10-27 22:09:17 +0000812 // We don't want to evaluate BlockExprs multiple times, as they generate
813 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000814 bool VisitBlockExpr(const BlockExpr *E) { return true; }
815 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
816 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000817 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000818 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
819 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
820 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
821 bool VisitStringLiteral(const StringLiteral *E) { return false; }
822 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
823 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000824 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000825 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000826 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000827 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +0000828 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000829 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
830 bool VisitBinAssign(const BinaryOperator *E) { return true; }
831 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
832 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000833 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000834 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
835 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
836 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
837 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
838 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +0000839 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000840 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000841 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000842 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000843 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000844
845 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000846 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000847 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
848 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000849 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000850 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000851 return false;
852 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000853
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000854 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000855};
856
John McCall56ca35d2011-02-17 10:25:35 +0000857class OpaqueValueEvaluation {
858 EvalInfo &info;
859 OpaqueValueExpr *opaqueValue;
860
861public:
862 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
863 Expr *value)
864 : info(info), opaqueValue(opaqueValue) {
865
866 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +0000867 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +0000868 this->opaqueValue = 0;
869 return;
870 }
John McCall56ca35d2011-02-17 10:25:35 +0000871 }
872
873 bool hasError() const { return opaqueValue == 0; }
874
875 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +0000876 // FIXME: This will not work for recursive constexpr functions using opaque
877 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +0000878 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
879 }
880};
881
Mike Stumpc4c90452009-10-27 22:09:17 +0000882} // end anonymous namespace
883
Eli Friedman4efaa272008-11-12 09:44:48 +0000884//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000885// Generic Evaluation
886//===----------------------------------------------------------------------===//
887namespace {
888
889template <class Derived, typename RetTy=void>
890class ExprEvaluatorBase
891 : public ConstStmtVisitor<Derived, RetTy> {
892private:
Richard Smith47a1eed2011-10-29 20:57:55 +0000893 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000894 return static_cast<Derived*>(this)->Success(V, E);
895 }
896 RetTy DerivedError(const Expr *E) {
897 return static_cast<Derived*>(this)->Error(E);
898 }
Richard Smithf10d9172011-10-11 21:43:33 +0000899 RetTy DerivedValueInitialization(const Expr *E) {
900 return static_cast<Derived*>(this)->ValueInitialization(E);
901 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000902
903protected:
904 EvalInfo &Info;
905 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
906 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
907
Richard Smithf10d9172011-10-11 21:43:33 +0000908 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
909
Richard Smith177dce72011-11-01 16:57:24 +0000910 bool MakeTemporary(const Expr *Key, const Expr *Value, LValue &Result) {
911 if (!Evaluate(Info.CurrentCall->Temporaries[Key], Info, Value))
912 return false;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000913 Result.setExpr(Key, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +0000914 return true;
915 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000916public:
917 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
918
919 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000920 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000921 }
922 RetTy VisitExpr(const Expr *E) {
923 return DerivedError(E);
924 }
925
926 RetTy VisitParenExpr(const ParenExpr *E)
927 { return StmtVisitorTy::Visit(E->getSubExpr()); }
928 RetTy VisitUnaryExtension(const UnaryOperator *E)
929 { return StmtVisitorTy::Visit(E->getSubExpr()); }
930 RetTy VisitUnaryPlus(const UnaryOperator *E)
931 { return StmtVisitorTy::Visit(E->getSubExpr()); }
932 RetTy VisitChooseExpr(const ChooseExpr *E)
933 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
934 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
935 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000936 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
937 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000938
939 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
940 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
941 if (opaque.hasError())
942 return DerivedError(E);
943
944 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +0000945 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000946 return DerivedError(E);
947
948 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
949 }
950
951 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
952 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +0000953 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000954 return DerivedError(E);
955
Richard Smithc49bd112011-10-28 17:51:58 +0000956 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000957 return StmtVisitorTy::Visit(EvalExpr);
958 }
959
960 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000961 const CCValue *Value = Info.getOpaqueValue(E);
962 if (!Value)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000963 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
964 : DerivedError(E));
Richard Smith47a1eed2011-10-29 20:57:55 +0000965 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000966 }
Richard Smithf10d9172011-10-11 21:43:33 +0000967
Richard Smithd0dccea2011-10-28 22:34:42 +0000968 RetTy VisitCallExpr(const CallExpr *E) {
969 const Expr *Callee = E->getCallee();
970 QualType CalleeType = Callee->getType();
971
972 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
973 // non-static member function.
974 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
975 return DerivedError(E);
976
977 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
978 return DerivedError(E);
979
Richard Smith47a1eed2011-10-29 20:57:55 +0000980 CCValue Call;
Richard Smithd0dccea2011-10-28 22:34:42 +0000981 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
982 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
983 return DerivedError(Callee);
984
985 const FunctionDecl *FD = 0;
986 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
987 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
988 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
989 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
990 if (!FD)
991 return DerivedError(Callee);
992
993 // Don't call function pointers which have been cast to some other type.
994 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
995 return DerivedError(E);
996
997 const FunctionDecl *Definition;
998 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +0000999 CCValue CCResult;
1000 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001001 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
1002
1003 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smith69c2c502011-11-04 05:33:44 +00001004 HandleFunctionCall(Args, Body, Info, CCResult) &&
1005 CheckConstantExpression(CCResult, Result))
1006 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001007
1008 return DerivedError(E);
1009 }
1010
Richard Smithc49bd112011-10-28 17:51:58 +00001011 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1012 return StmtVisitorTy::Visit(E->getInitializer());
1013 }
Richard Smithf10d9172011-10-11 21:43:33 +00001014 RetTy VisitInitListExpr(const InitListExpr *E) {
1015 if (Info.getLangOpts().CPlusPlus0x) {
1016 if (E->getNumInits() == 0)
1017 return DerivedValueInitialization(E);
1018 if (E->getNumInits() == 1)
1019 return StmtVisitorTy::Visit(E->getInit(0));
1020 }
1021 return DerivedError(E);
1022 }
1023 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1024 return DerivedValueInitialization(E);
1025 }
1026 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1027 return DerivedValueInitialization(E);
1028 }
1029
Richard Smithc49bd112011-10-28 17:51:58 +00001030 RetTy VisitCastExpr(const CastExpr *E) {
1031 switch (E->getCastKind()) {
1032 default:
1033 break;
1034
1035 case CK_NoOp:
1036 return StmtVisitorTy::Visit(E->getSubExpr());
1037
1038 case CK_LValueToRValue: {
1039 LValue LVal;
1040 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001041 CCValue RVal;
Richard Smithc49bd112011-10-28 17:51:58 +00001042 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1043 return DerivedSuccess(RVal, E);
1044 }
1045 break;
1046 }
1047 }
1048
1049 return DerivedError(E);
1050 }
1051
Richard Smith8327fad2011-10-24 18:44:57 +00001052 /// Visit a value which is evaluated, but whose value is ignored.
1053 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001054 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00001055 if (!Evaluate(Scratch, Info, E))
1056 Info.EvalStatus.HasSideEffects = true;
1057 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001058};
1059
1060}
1061
1062//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00001063// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00001064//
1065// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1066// function designators (in C), decl references to void objects (in C), and
1067// temporaries (if building with -Wno-address-of-temporary).
1068//
1069// LValue evaluation produces values comprising a base expression of one of the
1070// following types:
1071// * DeclRefExpr
1072// * MemberExpr for a static member
1073// * CompoundLiteralExpr in C
1074// * StringLiteral
1075// * PredefinedExpr
1076// * ObjCEncodeExpr
1077// * AddrLabelExpr
1078// * BlockExpr
1079// * CallExpr for a MakeStringConstant builtin
Richard Smith177dce72011-11-01 16:57:24 +00001080// plus an offset in bytes. It can also produce lvalues referring to locals. In
1081// that case, the Frame will point to a stack frame, and the Expr is used as a
1082// key to find the relevant temporary's value.
Eli Friedman4efaa272008-11-12 09:44:48 +00001083//===----------------------------------------------------------------------===//
1084namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001085class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001086 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001087 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +00001088 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +00001089
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001090 bool Success(const Expr *E) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001091 Result.setExpr(E);
John McCallefdb83e2010-05-07 21:00:08 +00001092 return true;
1093 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001094public:
Mike Stump1eb44332009-09-09 15:08:12 +00001095
John McCallefdb83e2010-05-07 21:00:08 +00001096 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +00001097 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +00001098
Richard Smith47a1eed2011-10-29 20:57:55 +00001099 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001100 Result.setFrom(V);
1101 return true;
1102 }
1103 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001104 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001105 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001106
Richard Smithc49bd112011-10-28 17:51:58 +00001107 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1108
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001109 bool VisitDeclRefExpr(const DeclRefExpr *E);
1110 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00001111 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001112 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1113 bool VisitMemberExpr(const MemberExpr *E);
1114 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1115 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1116 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1117 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001118
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001119 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00001120 switch (E->getCastKind()) {
1121 default:
Richard Smithc49bd112011-10-28 17:51:58 +00001122 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001123
Eli Friedmandb924222011-10-11 00:13:24 +00001124 case CK_LValueBitCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001125 if (!Visit(E->getSubExpr()))
1126 return false;
1127 Result.Designator.setInvalid();
1128 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00001129
Richard Smithc49bd112011-10-28 17:51:58 +00001130 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
1131 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlsson26bc2202009-10-03 16:30:22 +00001132 }
1133 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00001134
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001135 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001136
Eli Friedman4efaa272008-11-12 09:44:48 +00001137};
1138} // end anonymous namespace
1139
Richard Smithc49bd112011-10-28 17:51:58 +00001140/// Evaluate an expression as an lvalue. This can be legitimately called on
1141/// expressions which are not glvalues, in a few cases:
1142/// * function designators in C,
1143/// * "extern void" objects,
1144/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00001145static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001146 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1147 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1148 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001149 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001150}
1151
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001152bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001153 if (isa<FunctionDecl>(E->getDecl()))
John McCallefdb83e2010-05-07 21:00:08 +00001154 return Success(E);
Richard Smithc49bd112011-10-28 17:51:58 +00001155 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1156 return VisitVarDecl(E, VD);
1157 return Error(E);
1158}
Richard Smith436c8892011-10-24 23:14:33 +00001159
Richard Smithc49bd112011-10-28 17:51:58 +00001160bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00001161 if (!VD->getType()->isReferenceType()) {
1162 if (isa<ParmVarDecl>(VD)) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001163 Result.setExpr(E, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00001164 return true;
1165 }
Richard Smithc49bd112011-10-28 17:51:58 +00001166 return Success(E);
Richard Smith177dce72011-11-01 16:57:24 +00001167 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00001168
Richard Smith47a1eed2011-10-29 20:57:55 +00001169 CCValue V;
Richard Smith177dce72011-11-01 16:57:24 +00001170 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith47a1eed2011-10-29 20:57:55 +00001171 return Success(V, E);
Richard Smithc49bd112011-10-28 17:51:58 +00001172
1173 return Error(E);
Anders Carlsson35873c42008-11-24 04:41:22 +00001174}
1175
Richard Smithbd552ef2011-10-31 05:52:43 +00001176bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1177 const MaterializeTemporaryExpr *E) {
Richard Smith177dce72011-11-01 16:57:24 +00001178 return MakeTemporary(E, E->GetTemporaryExpr(), Result);
Richard Smithbd552ef2011-10-31 05:52:43 +00001179}
1180
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001181bool
1182LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001183 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1184 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1185 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00001186 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001187}
1188
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001189bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001190 // Handle static data members.
1191 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1192 VisitIgnoredValue(E->getBase());
1193 return VisitVarDecl(E, VD);
1194 }
1195
Richard Smithd0dccea2011-10-28 22:34:42 +00001196 // Handle static member functions.
1197 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1198 if (MD->isStatic()) {
1199 VisitIgnoredValue(E->getBase());
1200 return Success(E);
1201 }
1202 }
1203
Eli Friedman4efaa272008-11-12 09:44:48 +00001204 QualType Ty;
1205 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +00001206 if (!EvaluatePointer(E->getBase(), Result, Info))
1207 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +00001208 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +00001209 } else {
John McCallefdb83e2010-05-07 21:00:08 +00001210 if (!Visit(E->getBase()))
1211 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001212 Ty = E->getBase()->getType();
1213 }
1214
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001215 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +00001216 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +00001217
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001218 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +00001219 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +00001220 return false;
Eli Friedman2be58612009-05-30 21:09:44 +00001221
1222 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +00001223 return false;
Eli Friedman2be58612009-05-30 21:09:44 +00001224
Eli Friedman82905742011-07-07 01:54:01 +00001225 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001226 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Richard Smith0a3bdb62011-11-04 02:25:55 +00001227 Result.Designator.addDecl(FD);
John McCallefdb83e2010-05-07 21:00:08 +00001228 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +00001229}
1230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001231bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001232 // FIXME: Deal with vectors as array subscript bases.
1233 if (E->getBase()->getType()->isVectorType())
1234 return false;
1235
Anders Carlsson3068d112008-11-16 19:01:22 +00001236 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001237 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001238
Anders Carlsson3068d112008-11-16 19:01:22 +00001239 APSInt Index;
1240 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001241 return false;
Richard Smith0a3bdb62011-11-04 02:25:55 +00001242 uint64_t IndexValue
1243 = Index.isSigned() ? static_cast<uint64_t>(Index.getSExtValue())
1244 : Index.getZExtValue();
Anders Carlsson3068d112008-11-16 19:01:22 +00001245
Ken Dyck199c3d62010-01-11 17:06:35 +00001246 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Richard Smith0a3bdb62011-11-04 02:25:55 +00001247 Result.Offset += IndexValue * ElementSize;
1248 Result.Designator.adjustIndex(IndexValue);
John McCallefdb83e2010-05-07 21:00:08 +00001249 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +00001250}
Eli Friedman4efaa272008-11-12 09:44:48 +00001251
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001252bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001253 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00001254}
1255
Eli Friedman4efaa272008-11-12 09:44:48 +00001256//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001257// Pointer Evaluation
1258//===----------------------------------------------------------------------===//
1259
Anders Carlssonc754aa62008-07-08 05:13:58 +00001260namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001261class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001262 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001263 LValue &Result;
1264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001265 bool Success(const Expr *E) {
Richard Smith0a3bdb62011-11-04 02:25:55 +00001266 Result.setExpr(E);
John McCallefdb83e2010-05-07 21:00:08 +00001267 return true;
1268 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001269public:
Mike Stump1eb44332009-09-09 15:08:12 +00001270
John McCallefdb83e2010-05-07 21:00:08 +00001271 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001272 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001273
Richard Smith47a1eed2011-10-29 20:57:55 +00001274 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001275 Result.setFrom(V);
1276 return true;
1277 }
1278 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +00001279 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001280 }
Richard Smithf10d9172011-10-11 21:43:33 +00001281 bool ValueInitialization(const Expr *E) {
1282 return Success((Expr*)0);
1283 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001284
John McCallefdb83e2010-05-07 21:00:08 +00001285 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001286 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00001287 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001288 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00001289 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001290 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00001291 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001292 bool VisitCallExpr(const CallExpr *E);
1293 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00001294 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00001295 return Success(E);
1296 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +00001297 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001298 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smithf10d9172011-10-11 21:43:33 +00001299 { return ValueInitialization(E); }
John McCall56ca35d2011-02-17 10:25:35 +00001300
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001301 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00001302};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001303} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001304
John McCallefdb83e2010-05-07 21:00:08 +00001305static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001306 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001307 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001308}
1309
John McCallefdb83e2010-05-07 21:00:08 +00001310bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001311 if (E->getOpcode() != BO_Add &&
1312 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +00001313 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001315 const Expr *PExp = E->getLHS();
1316 const Expr *IExp = E->getRHS();
1317 if (IExp->getType()->isPointerType())
1318 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00001319
John McCallefdb83e2010-05-07 21:00:08 +00001320 if (!EvaluatePointer(PExp, Result, Info))
1321 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001322
John McCallefdb83e2010-05-07 21:00:08 +00001323 llvm::APSInt Offset;
1324 if (!EvaluateInteger(IExp, Offset, Info))
1325 return false;
1326 int64_t AdditionalOffset
1327 = Offset.isSigned() ? Offset.getSExtValue()
1328 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00001329 if (E->getOpcode() == BO_Sub)
1330 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001331
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +00001332 // Compute the new offset in the appropriate width.
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +00001333 QualType PointeeType =
1334 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +00001335 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Anders Carlsson4d4c50d2009-02-19 04:55:58 +00001337 // Explicitly handle GNU void* and function pointer arithmetic extensions.
1338 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +00001339 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +00001340 else
John McCallefdb83e2010-05-07 21:00:08 +00001341 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +00001342
Richard Smith0a3bdb62011-11-04 02:25:55 +00001343 Result.Offset += AdditionalOffset * SizeOfPointee;
1344 Result.Designator.adjustIndex(AdditionalOffset);
John McCallefdb83e2010-05-07 21:00:08 +00001345 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001346}
Eli Friedman4efaa272008-11-12 09:44:48 +00001347
John McCallefdb83e2010-05-07 21:00:08 +00001348bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1349 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001350}
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001352
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001353bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1354 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001355
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001356 switch (E->getCastKind()) {
1357 default:
1358 break;
1359
John McCall2de56d12010-08-25 11:45:40 +00001360 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001361 case CK_CPointerToObjCPointerCast:
1362 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001363 case CK_AnyPointerToBlockPointerCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001364 if (!Visit(SubExpr))
1365 return false;
1366 Result.Designator.setInvalid();
1367 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001368
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001369 case CK_DerivedToBase:
1370 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001371 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001372 return false;
1373
1374 // Now figure out the necessary offset to add to the baseLV to get from
1375 // the derived class to the base class.
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001376 QualType Ty = E->getSubExpr()->getType();
1377 const CXXRecordDecl *DerivedDecl =
1378 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
1379
1380 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1381 PathE = E->path_end(); PathI != PathE; ++PathI) {
1382 const CXXBaseSpecifier *Base = *PathI;
1383
1384 // FIXME: If the base is virtual, we'd need to determine the type of the
1385 // most derived class and we don't support that right now.
1386 if (Base->isVirtual())
1387 return false;
1388
1389 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1390 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1391
Richard Smith47a1eed2011-10-29 20:57:55 +00001392 Result.getLValueOffset() += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001393 DerivedDecl = BaseDecl;
1394 }
1395
Richard Smith0a3bdb62011-11-04 02:25:55 +00001396 // FIXME
1397 Result.Designator.setInvalid();
1398
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001399 return true;
1400 }
1401
Richard Smith47a1eed2011-10-29 20:57:55 +00001402 case CK_NullToPointer:
1403 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00001404
John McCall2de56d12010-08-25 11:45:40 +00001405 case CK_IntegralToPointer: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001406 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00001407 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001408 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001409
John McCallefdb83e2010-05-07 21:00:08 +00001410 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001411 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1412 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCallefdb83e2010-05-07 21:00:08 +00001413 Result.Base = 0;
Richard Smith47a1eed2011-10-29 20:57:55 +00001414 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00001415 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00001416 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00001417 return true;
1418 } else {
1419 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00001420 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00001421 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001422 }
1423 }
John McCall2de56d12010-08-25 11:45:40 +00001424 case CK_ArrayToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001425 // FIXME: Support array-to-pointer decay on array rvalues.
1426 if (!SubExpr->isGLValue())
1427 return Error(E);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001428 if (!EvaluateLValue(SubExpr, Result, Info))
1429 return false;
1430 // The result is a pointer to the first element of the array.
1431 Result.Designator.addIndex(0);
1432 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00001433
John McCall2de56d12010-08-25 11:45:40 +00001434 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001435 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001436 }
1437
Richard Smithc49bd112011-10-28 17:51:58 +00001438 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001439}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001440
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001441bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +00001443 Builtin::BI__builtin___CFStringMakeConstantString ||
1444 E->isBuiltinCall(Info.Ctx) ==
1445 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +00001446 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00001447
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001448 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001449}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001450
1451//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00001452// Vector Evaluation
1453//===----------------------------------------------------------------------===//
1454
1455namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001456 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00001457 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1458 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00001459 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001460
Richard Smith07fc6572011-10-22 21:10:00 +00001461 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1462 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Richard Smith07fc6572011-10-22 21:10:00 +00001464 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1465 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1466 // FIXME: remove this APValue copy.
1467 Result = APValue(V.data(), V.size());
1468 return true;
1469 }
Richard Smith69c2c502011-11-04 05:33:44 +00001470 bool Success(const CCValue &V, const Expr *E) {
1471 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00001472 Result = V;
1473 return true;
1474 }
1475 bool Error(const Expr *E) { return false; }
1476 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Richard Smith07fc6572011-10-22 21:10:00 +00001478 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00001479 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00001480 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00001481 bool VisitInitListExpr(const InitListExpr *E);
1482 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001483 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00001484 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00001485 // shufflevector, ExtVectorElementExpr
1486 // (Note that these require implementing conversions
1487 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00001488 };
1489} // end anonymous namespace
1490
1491static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001492 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00001493 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00001494}
1495
Richard Smith07fc6572011-10-22 21:10:00 +00001496bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1497 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00001498 QualType EltTy = VTy->getElementType();
1499 unsigned NElts = VTy->getNumElements();
1500 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Nate Begeman59b5da62009-01-18 03:20:47 +00001502 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00001503 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00001504
Eli Friedman46a52322011-03-25 00:43:55 +00001505 switch (E->getCastKind()) {
1506 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00001507 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00001508 if (SETy->isIntegerType()) {
1509 APSInt IntResult;
1510 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001511 return Error(E);
1512 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00001513 } else if (SETy->isRealFloatingType()) {
1514 APFloat F(0.0);
1515 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001516 return Error(E);
1517 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00001518 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00001519 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00001520 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00001521
1522 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00001523 SmallVector<APValue, 4> Elts(NElts, Val);
1524 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00001525 }
Eli Friedman46a52322011-03-25 00:43:55 +00001526 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +00001527 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +00001528 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001529 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +00001530
Eli Friedman46a52322011-03-25 00:43:55 +00001531 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +00001532 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Eli Friedman46a52322011-03-25 00:43:55 +00001534 APSInt Init;
1535 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001536 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00001537
Eli Friedman46a52322011-03-25 00:43:55 +00001538 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1539 "Vectors must be composed of ints or floats");
1540
Chris Lattner5f9e2722011-07-23 10:55:15 +00001541 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +00001542 for (unsigned i = 0; i != NElts; ++i) {
1543 APSInt Tmp = Init.extOrTrunc(EltWidth);
1544
1545 if (EltTy->isIntegerType())
1546 Elts.push_back(APValue(Tmp));
1547 else
1548 Elts.push_back(APValue(APFloat(Tmp)));
1549
1550 Init >>= EltWidth;
1551 }
Richard Smith07fc6572011-10-22 21:10:00 +00001552 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00001553 }
Eli Friedman46a52322011-03-25 00:43:55 +00001554 default:
Richard Smithc49bd112011-10-28 17:51:58 +00001555 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00001556 }
Nate Begeman59b5da62009-01-18 03:20:47 +00001557}
1558
Richard Smith07fc6572011-10-22 21:10:00 +00001559bool
Nate Begeman59b5da62009-01-18 03:20:47 +00001560VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00001561 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00001562 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00001563 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Nate Begeman59b5da62009-01-18 03:20:47 +00001565 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001566 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00001567
John McCalla7d6c222010-06-11 17:54:15 +00001568 // If a vector is initialized with a single element, that value
1569 // becomes every element of the vector, not just the first.
1570 // This is the behavior described in the IBM AltiVec documentation.
1571 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00001572
1573 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00001574 // vector (OpenCL 6.1.6).
1575 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00001576 return Visit(E->getInit(0));
1577
John McCalla7d6c222010-06-11 17:54:15 +00001578 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00001579 if (EltTy->isIntegerType()) {
1580 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00001581 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001582 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001583 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00001584 } else {
1585 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00001586 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001587 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001588 InitValue = APValue(f);
1589 }
1590 for (unsigned i = 0; i < NumElements; i++) {
1591 Elements.push_back(InitValue);
1592 }
1593 } else {
1594 for (unsigned i = 0; i < NumElements; i++) {
1595 if (EltTy->isIntegerType()) {
1596 llvm::APSInt sInt(32);
1597 if (i < NumInits) {
1598 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001599 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001600 } else {
1601 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1602 }
1603 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00001604 } else {
John McCalla7d6c222010-06-11 17:54:15 +00001605 llvm::APFloat f(0.0);
1606 if (i < NumInits) {
1607 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00001608 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00001609 } else {
1610 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1611 }
1612 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00001613 }
Nate Begeman59b5da62009-01-18 03:20:47 +00001614 }
1615 }
Richard Smith07fc6572011-10-22 21:10:00 +00001616 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00001617}
1618
Richard Smith07fc6572011-10-22 21:10:00 +00001619bool
1620VectorExprEvaluator::ValueInitialization(const Expr *E) {
1621 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00001622 QualType EltTy = VT->getElementType();
1623 APValue ZeroElement;
1624 if (EltTy->isIntegerType())
1625 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1626 else
1627 ZeroElement =
1628 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1629
Chris Lattner5f9e2722011-07-23 10:55:15 +00001630 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00001631 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001632}
1633
Richard Smith07fc6572011-10-22 21:10:00 +00001634bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00001635 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00001636 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001637}
1638
Nate Begeman59b5da62009-01-18 03:20:47 +00001639//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00001640// Array Evaluation
1641//===----------------------------------------------------------------------===//
1642
1643namespace {
1644 class ArrayExprEvaluator
1645 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
1646 APValue &Result;
1647 public:
1648
1649 ArrayExprEvaluator(EvalInfo &Info, APValue &Result)
1650 : ExprEvaluatorBaseTy(Info), Result(Result) {}
1651
1652 bool Success(const APValue &V, const Expr *E) {
1653 assert(V.isArray() && "Expected array type");
1654 Result = V;
1655 return true;
1656 }
1657 bool Error(const Expr *E) { return false; }
1658
1659 bool VisitInitListExpr(const InitListExpr *E);
1660 };
1661} // end anonymous namespace
1662
1663static bool EvaluateArray(const Expr* E, APValue& Result, EvalInfo &Info) {
1664 assert(E->isRValue() && E->getType()->isArrayType() &&
1665 E->getType()->isLiteralType() && "not a literal array rvalue");
1666 return ArrayExprEvaluator(Info, Result).Visit(E);
1667}
1668
1669bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1670 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
1671 if (!CAT)
1672 return false;
1673
1674 Result = APValue(APValue::UninitArray(), E->getNumInits(),
1675 CAT->getSize().getZExtValue());
1676 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
1677 I != End; ++I)
1678 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(I-E->begin()),
1679 Info, cast<Expr>(*I)))
1680 return false;
1681
1682 if (!Result.hasArrayFiller()) return true;
1683 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
1684 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
1685 E->getArrayFiller());
1686}
1687
1688//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001689// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00001690//
1691// As a GNU extension, we support casting pointers to sufficiently-wide integer
1692// types and back in constant folding. Integer values are thus represented
1693// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001694//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001695
1696namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001697class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001698 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00001699 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00001700public:
Richard Smith47a1eed2011-10-29 20:57:55 +00001701 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001702 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001703
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001704 bool Success(const llvm::APSInt &SI, const Expr *E) {
1705 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001706 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001707 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001708 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001709 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001710 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00001711 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001712 return true;
1713 }
1714
Daniel Dunbar131eb432009-02-19 09:06:44 +00001715 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001716 assert(E->getType()->isIntegralOrEnumerationType() &&
1717 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001718 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001719 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00001720 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00001721 Result.getInt().setIsUnsigned(
1722 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00001723 return true;
1724 }
1725
1726 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001727 assert(E->getType()->isIntegralOrEnumerationType() &&
1728 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00001729 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00001730 return true;
1731 }
1732
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001733 bool Success(CharUnits Size, const Expr *E) {
1734 return Success(Size.getQuantity(), E);
1735 }
1736
1737
Anders Carlsson82206e22008-11-30 18:14:57 +00001738 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001739 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00001740 if (Info.EvalStatus.Diag == 0) {
1741 Info.EvalStatus.DiagLoc = L;
1742 Info.EvalStatus.Diag = D;
1743 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00001744 }
Chris Lattner54176fd2008-07-12 00:14:42 +00001745 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00001746 }
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Richard Smith47a1eed2011-10-29 20:57:55 +00001748 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00001749 if (V.isLValue()) {
1750 Result = V;
1751 return true;
1752 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001753 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00001754 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001755 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001756 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001757 }
Mike Stump1eb44332009-09-09 15:08:12 +00001758
Richard Smithf10d9172011-10-11 21:43:33 +00001759 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1760
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001761 //===--------------------------------------------------------------------===//
1762 // Visitor Methods
1763 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001764
Chris Lattner4c4867e2008-07-12 00:38:25 +00001765 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001766 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001767 }
1768 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001769 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001770 }
Eli Friedman04309752009-11-24 05:28:59 +00001771
1772 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1773 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001774 if (CheckReferencedDecl(E, E->getDecl()))
1775 return true;
1776
1777 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001778 }
1779 bool VisitMemberExpr(const MemberExpr *E) {
1780 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00001781 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00001782 return true;
1783 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001784
1785 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001786 }
1787
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001788 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001789 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001790 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001791 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001792
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001793 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001794 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001795
Anders Carlsson3068d112008-11-16 19:01:22 +00001796 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001797 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001798 }
Mike Stump1eb44332009-09-09 15:08:12 +00001799
Richard Smithf10d9172011-10-11 21:43:33 +00001800 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00001801 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00001802 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00001803 }
1804
Sebastian Redl64b45f72009-01-05 20:52:13 +00001805 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001806 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001807 }
1808
Francois Pichet6ad6f282010-12-07 00:08:36 +00001809 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1810 return Success(E->getValue(), E);
1811 }
1812
John Wiegley21ff2e52011-04-28 00:16:57 +00001813 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1814 return Success(E->getValue(), E);
1815 }
1816
John Wiegley55262202011-04-25 06:54:41 +00001817 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1818 return Success(E->getValue(), E);
1819 }
1820
Eli Friedman722c7172009-02-28 03:59:05 +00001821 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001822 bool VisitUnaryImag(const UnaryOperator *E);
1823
Sebastian Redl295995c2010-09-10 20:55:47 +00001824 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001825 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00001826
Chris Lattnerfcee0012008-07-11 21:24:13 +00001827private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001828 CharUnits GetAlignOfExpr(const Expr *E);
1829 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001830 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001831 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001832 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001833};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001834} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001835
Richard Smithc49bd112011-10-28 17:51:58 +00001836/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1837/// produce either the integer value or a pointer.
1838///
1839/// GCC has a heinous extension which folds casts between pointer types and
1840/// pointer-sized integral types. We support this by allowing the evaluation of
1841/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1842/// Some simple arithmetic on such values is supported (they are treated much
1843/// like char*).
Richard Smith47a1eed2011-10-29 20:57:55 +00001844static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
1845 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001846 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001847 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001848}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001849
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001850static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001851 CCValue Val;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001852 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1853 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001854 Result = Val.getInt();
1855 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001856}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001857
Eli Friedman04309752009-11-24 05:28:59 +00001858bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001859 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001860 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001861 // Check for signedness/width mismatches between E type and ECD value.
1862 bool SameSign = (ECD->getInitVal().isSigned()
1863 == E->getType()->isSignedIntegerOrEnumerationType());
1864 bool SameWidth = (ECD->getInitVal().getBitWidth()
1865 == Info.Ctx.getIntWidth(E->getType()));
1866 if (SameSign && SameWidth)
1867 return Success(ECD->getInitVal(), E);
1868 else {
1869 // Get rid of mismatch (otherwise Success assertions will fail)
1870 // by computing a new value matching the type of E.
1871 llvm::APSInt Val = ECD->getInitVal();
1872 if (!SameSign)
1873 Val.setIsSigned(!ECD->getInitVal().isSigned());
1874 if (!SameWidth)
1875 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1876 return Success(Val, E);
1877 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001878 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001879 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001880}
1881
Chris Lattnera4d55d82008-10-06 06:40:35 +00001882/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1883/// as GCC.
1884static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1885 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001886 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001887 enum gcc_type_class {
1888 no_type_class = -1,
1889 void_type_class, integer_type_class, char_type_class,
1890 enumeral_type_class, boolean_type_class,
1891 pointer_type_class, reference_type_class, offset_type_class,
1892 real_type_class, complex_type_class,
1893 function_type_class, method_type_class,
1894 record_type_class, union_type_class,
1895 array_type_class, string_type_class,
1896 lang_type_class
1897 };
Mike Stump1eb44332009-09-09 15:08:12 +00001898
1899 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001900 // ideal, however it is what gcc does.
1901 if (E->getNumArgs() == 0)
1902 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Chris Lattnera4d55d82008-10-06 06:40:35 +00001904 QualType ArgTy = E->getArg(0)->getType();
1905 if (ArgTy->isVoidType())
1906 return void_type_class;
1907 else if (ArgTy->isEnumeralType())
1908 return enumeral_type_class;
1909 else if (ArgTy->isBooleanType())
1910 return boolean_type_class;
1911 else if (ArgTy->isCharType())
1912 return string_type_class; // gcc doesn't appear to use char_type_class
1913 else if (ArgTy->isIntegerType())
1914 return integer_type_class;
1915 else if (ArgTy->isPointerType())
1916 return pointer_type_class;
1917 else if (ArgTy->isReferenceType())
1918 return reference_type_class;
1919 else if (ArgTy->isRealType())
1920 return real_type_class;
1921 else if (ArgTy->isComplexType())
1922 return complex_type_class;
1923 else if (ArgTy->isFunctionType())
1924 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001925 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001926 return record_type_class;
1927 else if (ArgTy->isUnionType())
1928 return union_type_class;
1929 else if (ArgTy->isArrayType())
1930 return array_type_class;
1931 else if (ArgTy->isUnionType())
1932 return union_type_class;
1933 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00001934 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00001935 return -1;
1936}
1937
John McCall42c8f872010-05-10 23:27:23 +00001938/// Retrieves the "underlying object type" of the given expression,
1939/// as used by __builtin_object_size.
1940QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1941 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1942 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1943 return VD->getType();
1944 } else if (isa<CompoundLiteralExpr>(E)) {
1945 return E->getType();
1946 }
1947
1948 return QualType();
1949}
1950
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001951bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001952 // TODO: Perhaps we should let LLVM lower this?
1953 LValue Base;
1954 if (!EvaluatePointer(E->getArg(0), Base, Info))
1955 return false;
1956
1957 // If we can prove the base is null, lower to zero now.
1958 const Expr *LVBase = Base.getLValueBase();
1959 if (!LVBase) return Success(0, E);
1960
1961 QualType T = GetObjectType(LVBase);
1962 if (T.isNull() ||
1963 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001964 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001965 T->isVariablyModifiedType() ||
1966 T->isDependentType())
1967 return false;
1968
1969 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1970 CharUnits Offset = Base.getLValueOffset();
1971
1972 if (!Offset.isNegative() && Offset <= Size)
1973 Size -= Offset;
1974 else
1975 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001976 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001977}
1978
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001979bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001980 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001981 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001982 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001983
1984 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001985 if (TryEvaluateBuiltinObjectSize(E))
1986 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001987
Eric Christopherb2aaf512010-01-19 22:58:35 +00001988 // If evaluating the argument has side-effects we can't determine
1989 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001990 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001991 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001992 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001993 return Success(0, E);
1994 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001995
Mike Stump64eda9e2009-10-26 18:35:08 +00001996 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1997 }
1998
Chris Lattner019f4e82008-10-06 05:28:25 +00001999 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002000 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002002 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00002003 // __builtin_constant_p always has one operand: it returns true if that
2004 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00002005 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002006
2007 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002008 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002009 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002010 return Success(Operand, E);
2011 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00002012
2013 case Builtin::BI__builtin_expect:
2014 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00002015
2016 case Builtin::BIstrlen:
2017 case Builtin::BI__builtin_strlen:
2018 // As an extension, we support strlen() and __builtin_strlen() as constant
2019 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002020 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00002021 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2022 // The string literal may have embedded null characters. Find the first
2023 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002024 StringRef Str = S->getString();
2025 StringRef::size_type Pos = Str.find(0);
2026 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00002027 Str = Str.substr(0, Pos);
2028
2029 return Success(Str.size(), E);
2030 }
2031
2032 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00002033
2034 case Builtin::BI__atomic_is_lock_free: {
2035 APSInt SizeVal;
2036 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2037 return false;
2038
2039 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2040 // of two less than the maximum inline atomic width, we know it is
2041 // lock-free. If the size isn't a power of two, or greater than the
2042 // maximum alignment where we promote atomics, we know it is not lock-free
2043 // (at least not in the sense of atomic_is_lock_free). Otherwise,
2044 // the answer can only be determined at runtime; for example, 16-byte
2045 // atomics have lock-free implementations on some, but not all,
2046 // x86-64 processors.
2047
2048 // Check power-of-two.
2049 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2050 if (!Size.isPowerOfTwo())
2051#if 0
2052 // FIXME: Suppress this folding until the ABI for the promotion width
2053 // settles.
2054 return Success(0, E);
2055#else
2056 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2057#endif
2058
2059#if 0
2060 // Check against promotion width.
2061 // FIXME: Suppress this folding until the ABI for the promotion width
2062 // settles.
2063 unsigned PromoteWidthBits =
2064 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2065 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2066 return Success(0, E);
2067#endif
2068
2069 // Check against inlining width.
2070 unsigned InlineWidthBits =
2071 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2072 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2073 return Success(1, E);
2074
2075 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2076 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002077 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00002078}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002079
Richard Smith625b8072011-10-31 01:37:14 +00002080static bool HasSameBase(const LValue &A, const LValue &B) {
2081 if (!A.getLValueBase())
2082 return !B.getLValueBase();
2083 if (!B.getLValueBase())
2084 return false;
2085
2086 if (A.getLValueBase() != B.getLValueBase()) {
2087 const Decl *ADecl = GetLValueBaseDecl(A);
2088 if (!ADecl)
2089 return false;
2090 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00002091 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00002092 return false;
2093 }
2094
2095 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00002096 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00002097}
2098
Chris Lattnerb542afe2008-07-11 19:10:17 +00002099bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002100 if (E->isAssignmentOp())
2101 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2102
John McCall2de56d12010-08-25 11:45:40 +00002103 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002104 VisitIgnoredValue(E->getLHS());
2105 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00002106 }
2107
2108 if (E->isLogicalOp()) {
2109 // These need to be handled specially because the operands aren't
2110 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002111 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Richard Smithc49bd112011-10-28 17:51:58 +00002113 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00002114 // We were able to evaluate the LHS, see if we can get away with not
2115 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00002116 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002117 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002118
Richard Smithc49bd112011-10-28 17:51:58 +00002119 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00002120 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002121 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002122 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00002123 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002124 }
2125 } else {
Richard Smithc49bd112011-10-28 17:51:58 +00002126 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002127 // We can't evaluate the LHS; however, sometimes the result
2128 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00002129 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2130 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002131 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002132 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00002133 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002134
2135 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002136 }
2137 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00002138 }
Eli Friedmana6afa762008-11-13 06:09:17 +00002139
Eli Friedmana6afa762008-11-13 06:09:17 +00002140 return false;
2141 }
2142
Anders Carlsson286f85e2008-11-16 07:17:21 +00002143 QualType LHSTy = E->getLHS()->getType();
2144 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00002145
2146 if (LHSTy->isAnyComplexType()) {
2147 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00002148 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00002149
2150 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2151 return false;
2152
2153 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2154 return false;
2155
2156 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002157 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002158 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00002159 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002160 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2161
John McCall2de56d12010-08-25 11:45:40 +00002162 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002163 return Success((CR_r == APFloat::cmpEqual &&
2164 CR_i == APFloat::cmpEqual), E);
2165 else {
John McCall2de56d12010-08-25 11:45:40 +00002166 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002167 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00002168 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002169 CR_r == APFloat::cmpLessThan ||
2170 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002171 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002172 CR_i == APFloat::cmpLessThan ||
2173 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00002174 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002175 } else {
John McCall2de56d12010-08-25 11:45:40 +00002176 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002177 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2178 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2179 else {
John McCall2de56d12010-08-25 11:45:40 +00002180 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002181 "Invalid compex comparison.");
2182 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2183 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2184 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002185 }
2186 }
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Anders Carlsson286f85e2008-11-16 07:17:21 +00002188 if (LHSTy->isRealFloatingType() &&
2189 RHSTy->isRealFloatingType()) {
2190 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00002191
Anders Carlsson286f85e2008-11-16 07:17:21 +00002192 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2193 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Anders Carlsson286f85e2008-11-16 07:17:21 +00002195 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2196 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Anders Carlsson286f85e2008-11-16 07:17:21 +00002198 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00002199
Anders Carlsson286f85e2008-11-16 07:17:21 +00002200 switch (E->getOpcode()) {
2201 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002202 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00002203 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002204 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002205 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002206 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002207 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002208 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002209 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00002210 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00002211 E);
John McCall2de56d12010-08-25 11:45:40 +00002212 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002213 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002214 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00002215 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00002216 || CR == APFloat::cmpLessThan
2217 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00002218 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00002219 }
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002221 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00002222 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00002223 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002224 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2225 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002226
John McCallefdb83e2010-05-07 21:00:08 +00002227 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002228 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2229 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002230
Richard Smith625b8072011-10-31 01:37:14 +00002231 // Reject differing bases from the normal codepath; we special-case
2232 // comparisons to null.
2233 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00002234 // Inequalities and subtractions between unrelated pointers have
2235 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00002236 if (!E->isEqualityOp())
2237 return false;
Eli Friedmanffbda402011-10-31 22:28:05 +00002238 // A constant address may compare equal to the address of a symbol.
2239 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00002240 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00002241 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2242 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2243 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002244 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00002245 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00002246 // distinct. However, we do know that the address of a literal will be
2247 // non-null.
2248 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2249 LHSValue.Base && RHSValue.Base)
Eli Friedman5bc86102009-06-14 02:17:33 +00002250 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002251 // We can't tell whether weak symbols will end up pointing to the same
2252 // object.
2253 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman5bc86102009-06-14 02:17:33 +00002254 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002255 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00002256 // (Note that clang defaults to -fmerge-all-constants, which can
2257 // lead to inconsistent results for comparisons involving the address
2258 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00002259 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00002260 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002261
Richard Smithcc5d4f62011-11-07 09:22:26 +00002262 // FIXME: Implement the C++11 restrictions:
2263 // - Pointer subtractions must be on elements of the same array.
2264 // - Pointer comparisons must be between members with the same access.
2265
John McCall2de56d12010-08-25 11:45:40 +00002266 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00002267 QualType Type = E->getLHS()->getType();
2268 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00002269
Ken Dycka7305832010-01-15 12:37:54 +00002270 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00002271 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00002272 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00002273
Ken Dycka7305832010-01-15 12:37:54 +00002274 CharUnits Diff = LHSValue.getLValueOffset() -
2275 RHSValue.getLValueOffset();
2276 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002277 }
Richard Smith625b8072011-10-31 01:37:14 +00002278
2279 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2280 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2281 switch (E->getOpcode()) {
2282 default: llvm_unreachable("missing comparison operator");
2283 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2284 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2285 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2286 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2287 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2288 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002289 }
Anders Carlsson3068d112008-11-16 19:01:22 +00002290 }
2291 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002292 if (!LHSTy->isIntegralOrEnumerationType() ||
2293 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00002294 // We can't continue from here for non-integral types, and they
2295 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00002296 return false;
2297 }
2298
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002299 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00002300 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00002301 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner54176fd2008-07-12 00:14:42 +00002302 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00002303
Richard Smithc49bd112011-10-28 17:51:58 +00002304 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002305 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00002306 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002307
2308 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00002309 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00002310 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2311 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00002312 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00002313 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002314 else
Richard Smith47a1eed2011-10-29 20:57:55 +00002315 LHSVal.getLValueOffset() -= AdditionalOffset;
2316 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002317 return true;
2318 }
2319
2320 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00002321 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00002322 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002323 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2324 LHSVal.getInt().getZExtValue());
2325 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00002326 return true;
2327 }
2328
2329 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00002330 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00002331 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00002332
Richard Smithc49bd112011-10-28 17:51:58 +00002333 APSInt &LHS = LHSVal.getInt();
2334 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00002335
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002336 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002337 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002338 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002339 case BO_Mul: return Success(LHS * RHS, E);
2340 case BO_Add: return Success(LHS + RHS, E);
2341 case BO_Sub: return Success(LHS - RHS, E);
2342 case BO_And: return Success(LHS & RHS, E);
2343 case BO_Xor: return Success(LHS ^ RHS, E);
2344 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002345 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00002346 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002347 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002348 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002349 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00002350 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002351 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002352 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002353 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00002354 // During constant-folding, a negative shift is an opposite shift.
2355 if (RHS.isSigned() && RHS.isNegative()) {
2356 RHS = -RHS;
2357 goto shift_right;
2358 }
2359
2360 shift_left:
2361 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00002362 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2363 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002364 }
John McCall2de56d12010-08-25 11:45:40 +00002365 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00002366 // During constant-folding, a negative shift is an opposite shift.
2367 if (RHS.isSigned() && RHS.isNegative()) {
2368 RHS = -RHS;
2369 goto shift_left;
2370 }
2371
2372 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00002373 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00002374 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2375 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002376 }
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Richard Smithc49bd112011-10-28 17:51:58 +00002378 case BO_LT: return Success(LHS < RHS, E);
2379 case BO_GT: return Success(LHS > RHS, E);
2380 case BO_LE: return Success(LHS <= RHS, E);
2381 case BO_GE: return Success(LHS >= RHS, E);
2382 case BO_EQ: return Success(LHS == RHS, E);
2383 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00002384 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002385}
2386
Ken Dyck8b752f12010-01-27 17:10:57 +00002387CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00002388 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2389 // the result is the size of the referenced type."
2390 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2391 // result shall be the alignment of the referenced type."
2392 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2393 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00002394
2395 // __alignof is defined to return the preferred alignment.
2396 return Info.Ctx.toCharUnitsFromBits(
2397 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00002398}
2399
Ken Dyck8b752f12010-01-27 17:10:57 +00002400CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00002401 E = E->IgnoreParens();
2402
2403 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00002404 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00002405 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002406 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2407 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00002408
Chris Lattneraf707ab2009-01-24 21:53:27 +00002409 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002410 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2411 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00002412
Chris Lattnere9feb472009-01-24 21:09:06 +00002413 return GetAlignOfType(E->getType());
2414}
2415
2416
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002417/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2418/// a result as the expression's type.
2419bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2420 const UnaryExprOrTypeTraitExpr *E) {
2421 switch(E->getKind()) {
2422 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00002423 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002424 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002425 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002426 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002427 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002428
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002429 case UETT_VecStep: {
2430 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00002431
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002432 if (Ty->isVectorType()) {
2433 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00002434
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002435 // The vec_step built-in functions that take a 3-component
2436 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2437 if (n == 3)
2438 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00002439
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002440 return Success(n, E);
2441 } else
2442 return Success(1, E);
2443 }
2444
2445 case UETT_SizeOf: {
2446 QualType SrcTy = E->getTypeOfArgument();
2447 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2448 // the result is the size of the referenced type."
2449 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2450 // result shall be the alignment of the referenced type."
2451 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2452 SrcTy = Ref->getPointeeType();
2453
2454 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2455 // extension.
2456 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
2457 return Success(1, E);
2458
2459 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2460 if (!SrcTy->isConstantSizeType())
2461 return false;
2462
2463 // Get information about the size.
2464 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
2465 }
2466 }
2467
2468 llvm_unreachable("unknown expr/type trait");
2469 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00002470}
2471
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002472bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002473 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002474 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002475 if (n == 0)
2476 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002477 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002478 for (unsigned i = 0; i != n; ++i) {
2479 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2480 switch (ON.getKind()) {
2481 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002482 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002483 APSInt IdxResult;
2484 if (!EvaluateInteger(Idx, IdxResult, Info))
2485 return false;
2486 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2487 if (!AT)
2488 return false;
2489 CurrentType = AT->getElementType();
2490 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2491 Result += IdxResult.getSExtValue() * ElementSize;
2492 break;
2493 }
2494
2495 case OffsetOfExpr::OffsetOfNode::Field: {
2496 FieldDecl *MemberDecl = ON.getField();
2497 const RecordType *RT = CurrentType->getAs<RecordType>();
2498 if (!RT)
2499 return false;
2500 RecordDecl *RD = RT->getDecl();
2501 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00002502 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00002503 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00002504 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002505 CurrentType = MemberDecl->getType().getNonReferenceType();
2506 break;
2507 }
2508
2509 case OffsetOfExpr::OffsetOfNode::Identifier:
2510 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00002511 return false;
2512
2513 case OffsetOfExpr::OffsetOfNode::Base: {
2514 CXXBaseSpecifier *BaseSpec = ON.getBase();
2515 if (BaseSpec->isVirtual())
2516 return false;
2517
2518 // Find the layout of the class whose base we are looking into.
2519 const RecordType *RT = CurrentType->getAs<RecordType>();
2520 if (!RT)
2521 return false;
2522 RecordDecl *RD = RT->getDecl();
2523 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
2524
2525 // Find the base class itself.
2526 CurrentType = BaseSpec->getType();
2527 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2528 if (!BaseRT)
2529 return false;
2530
2531 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00002532 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00002533 break;
2534 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002535 }
2536 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002537 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002538}
2539
Chris Lattnerb542afe2008-07-11 19:10:17 +00002540bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002541 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00002542 // LNot's operand isn't necessarily an integer, so we handle it specially.
2543 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00002544 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00002545 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002546 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00002547 }
2548
Daniel Dunbar4fff4812009-02-21 18:14:20 +00002549 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002550 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00002551 return false;
2552
Richard Smithc49bd112011-10-28 17:51:58 +00002553 // Get the operand value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002554 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00002555 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00002556 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002557
Chris Lattner75a48812008-07-11 22:15:16 +00002558 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00002559 default:
Chris Lattner75a48812008-07-11 22:15:16 +00002560 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2561 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002562 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00002563 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00002564 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2565 // If so, we could clear the diagnostic ID.
Richard Smithc49bd112011-10-28 17:51:58 +00002566 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00002567 case UO_Plus:
Richard Smithc49bd112011-10-28 17:51:58 +00002568 // The result is just the value.
2569 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00002570 case UO_Minus:
Richard Smithc49bd112011-10-28 17:51:58 +00002571 if (!Val.isInt()) return false;
2572 return Success(-Val.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00002573 case UO_Not:
Richard Smithc49bd112011-10-28 17:51:58 +00002574 if (!Val.isInt()) return false;
2575 return Success(~Val.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002576 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002577}
Mike Stump1eb44332009-09-09 15:08:12 +00002578
Chris Lattner732b2232008-07-12 01:15:53 +00002579/// HandleCast - This is used to evaluate implicit or explicit casts where the
2580/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002581bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2582 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00002583 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00002584 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00002585
Eli Friedman46a52322011-03-25 00:43:55 +00002586 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00002587 case CK_BaseToDerived:
2588 case CK_DerivedToBase:
2589 case CK_UncheckedDerivedToBase:
2590 case CK_Dynamic:
2591 case CK_ToUnion:
2592 case CK_ArrayToPointerDecay:
2593 case CK_FunctionToPointerDecay:
2594 case CK_NullToPointer:
2595 case CK_NullToMemberPointer:
2596 case CK_BaseToDerivedMemberPointer:
2597 case CK_DerivedToBaseMemberPointer:
2598 case CK_ConstructorConversion:
2599 case CK_IntegralToPointer:
2600 case CK_ToVoid:
2601 case CK_VectorSplat:
2602 case CK_IntegralToFloating:
2603 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002604 case CK_CPointerToObjCPointerCast:
2605 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00002606 case CK_AnyPointerToBlockPointerCast:
2607 case CK_ObjCObjectLValueCast:
2608 case CK_FloatingRealToComplex:
2609 case CK_FloatingComplexToReal:
2610 case CK_FloatingComplexCast:
2611 case CK_FloatingComplexToIntegralComplex:
2612 case CK_IntegralRealToComplex:
2613 case CK_IntegralComplexCast:
2614 case CK_IntegralComplexToFloatingComplex:
2615 llvm_unreachable("invalid cast kind for integral value");
2616
Eli Friedmane50c2972011-03-25 19:07:11 +00002617 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00002618 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00002619 case CK_LValueBitCast:
2620 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00002621 case CK_ARCProduceObject:
2622 case CK_ARCConsumeObject:
2623 case CK_ARCReclaimReturnedObject:
2624 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00002625 return false;
2626
2627 case CK_LValueToRValue:
2628 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00002629 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002630
2631 case CK_MemberPointerToBoolean:
2632 case CK_PointerToBoolean:
2633 case CK_IntegralToBoolean:
2634 case CK_FloatingToBoolean:
2635 case CK_FloatingComplexToBoolean:
2636 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002637 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00002638 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002639 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002640 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002641 }
2642
Eli Friedman46a52322011-03-25 00:43:55 +00002643 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00002644 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00002645 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002646
Eli Friedmanbe265702009-02-20 01:15:07 +00002647 if (!Result.isInt()) {
2648 // Only allow casts of lvalues if they are lossless.
2649 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2650 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002651
Daniel Dunbardd211642009-02-19 22:24:01 +00002652 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002653 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00002654 }
Mike Stump1eb44332009-09-09 15:08:12 +00002655
Eli Friedman46a52322011-03-25 00:43:55 +00002656 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00002657 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00002658 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00002659 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00002660
Daniel Dunbardd211642009-02-19 22:24:01 +00002661 if (LV.getLValueBase()) {
2662 // Only allow based lvalue casts if they are lossless.
2663 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2664 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00002665
John McCallefdb83e2010-05-07 21:00:08 +00002666 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00002667 return true;
2668 }
2669
Ken Dycka7305832010-01-15 12:37:54 +00002670 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2671 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00002672 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00002673 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002674
Eli Friedman46a52322011-03-25 00:43:55 +00002675 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00002676 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00002677 if (!EvaluateComplex(SubExpr, C, Info))
2678 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00002679 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00002680 }
Eli Friedman2217c872009-02-22 11:46:18 +00002681
Eli Friedman46a52322011-03-25 00:43:55 +00002682 case CK_FloatingToIntegral: {
2683 APFloat F(0.0);
2684 if (!EvaluateFloat(SubExpr, F, Info))
2685 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00002686
Eli Friedman46a52322011-03-25 00:43:55 +00002687 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2688 }
2689 }
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Eli Friedman46a52322011-03-25 00:43:55 +00002691 llvm_unreachable("unknown cast resulting in integral value");
2692 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002693}
Anders Carlsson2bad1682008-07-08 14:30:00 +00002694
Eli Friedman722c7172009-02-28 03:59:05 +00002695bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2696 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002697 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00002698 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2699 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2700 return Success(LV.getComplexIntReal(), E);
2701 }
2702
2703 return Visit(E->getSubExpr());
2704}
2705
Eli Friedman664a1042009-02-27 04:45:43 +00002706bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00002707 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002708 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00002709 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2710 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2711 return Success(LV.getComplexIntImag(), E);
2712 }
2713
Richard Smith8327fad2011-10-24 18:44:57 +00002714 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00002715 return Success(0, E);
2716}
2717
Douglas Gregoree8aff02011-01-04 17:33:58 +00002718bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2719 return Success(E->getPackLength(), E);
2720}
2721
Sebastian Redl295995c2010-09-10 20:55:47 +00002722bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2723 return Success(E->getValue(), E);
2724}
2725
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002726//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002727// Float Evaluation
2728//===----------------------------------------------------------------------===//
2729
2730namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002731class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002732 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002733 APFloat &Result;
2734public:
2735 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002736 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002737
Richard Smith47a1eed2011-10-29 20:57:55 +00002738 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002739 Result = V.getFloat();
2740 return true;
2741 }
2742 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002743 return false;
2744 }
2745
Richard Smithf10d9172011-10-11 21:43:33 +00002746 bool ValueInitialization(const Expr *E) {
2747 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2748 return true;
2749 }
2750
Chris Lattner019f4e82008-10-06 05:28:25 +00002751 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002752
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002753 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002754 bool VisitBinaryOperator(const BinaryOperator *E);
2755 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002756 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00002757
John McCallabd3a852010-05-07 22:08:54 +00002758 bool VisitUnaryReal(const UnaryOperator *E);
2759 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002760
John McCallabd3a852010-05-07 22:08:54 +00002761 // FIXME: Missing: array subscript of vector, member of vector,
2762 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002763};
2764} // end anonymous namespace
2765
2766static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002767 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002768 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002769}
2770
Jay Foad4ba2a172011-01-12 09:06:06 +00002771static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00002772 QualType ResultTy,
2773 const Expr *Arg,
2774 bool SNaN,
2775 llvm::APFloat &Result) {
2776 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2777 if (!S) return false;
2778
2779 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2780
2781 llvm::APInt fill;
2782
2783 // Treat empty strings as if they were zero.
2784 if (S->getString().empty())
2785 fill = llvm::APInt(32, 0);
2786 else if (S->getString().getAsInteger(0, fill))
2787 return false;
2788
2789 if (SNaN)
2790 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2791 else
2792 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2793 return true;
2794}
2795
Chris Lattner019f4e82008-10-06 05:28:25 +00002796bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002797 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002798 default:
2799 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2800
Chris Lattner019f4e82008-10-06 05:28:25 +00002801 case Builtin::BI__builtin_huge_val:
2802 case Builtin::BI__builtin_huge_valf:
2803 case Builtin::BI__builtin_huge_vall:
2804 case Builtin::BI__builtin_inf:
2805 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002806 case Builtin::BI__builtin_infl: {
2807 const llvm::fltSemantics &Sem =
2808 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002809 Result = llvm::APFloat::getInf(Sem);
2810 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002811 }
Mike Stump1eb44332009-09-09 15:08:12 +00002812
John McCalldb7b72a2010-02-28 13:00:19 +00002813 case Builtin::BI__builtin_nans:
2814 case Builtin::BI__builtin_nansf:
2815 case Builtin::BI__builtin_nansl:
2816 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2817 true, Result);
2818
Chris Lattner9e621712008-10-06 06:31:58 +00002819 case Builtin::BI__builtin_nan:
2820 case Builtin::BI__builtin_nanf:
2821 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002822 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002823 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002824 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2825 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002826
2827 case Builtin::BI__builtin_fabs:
2828 case Builtin::BI__builtin_fabsf:
2829 case Builtin::BI__builtin_fabsl:
2830 if (!EvaluateFloat(E->getArg(0), Result, Info))
2831 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002833 if (Result.isNegative())
2834 Result.changeSign();
2835 return true;
2836
Mike Stump1eb44332009-09-09 15:08:12 +00002837 case Builtin::BI__builtin_copysign:
2838 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002839 case Builtin::BI__builtin_copysignl: {
2840 APFloat RHS(0.);
2841 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2842 !EvaluateFloat(E->getArg(1), RHS, Info))
2843 return false;
2844 Result.copySign(RHS);
2845 return true;
2846 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002847 }
2848}
2849
John McCallabd3a852010-05-07 22:08:54 +00002850bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002851 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2852 ComplexValue CV;
2853 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2854 return false;
2855 Result = CV.FloatReal;
2856 return true;
2857 }
2858
2859 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002860}
2861
2862bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002863 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2864 ComplexValue CV;
2865 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2866 return false;
2867 Result = CV.FloatImag;
2868 return true;
2869 }
2870
Richard Smith8327fad2011-10-24 18:44:57 +00002871 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00002872 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2873 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002874 return true;
2875}
2876
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002877bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002878 switch (E->getOpcode()) {
2879 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002880 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00002881 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00002882 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00002883 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2884 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002885 Result.changeSign();
2886 return true;
2887 }
2888}
Chris Lattner019f4e82008-10-06 05:28:25 +00002889
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002890bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002891 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002892 VisitIgnoredValue(E->getLHS());
2893 return Visit(E->getRHS());
Eli Friedman7f92f032009-11-16 04:25:37 +00002894 }
2895
Richard Smithee591a92011-10-28 23:26:52 +00002896 // We can't evaluate pointer-to-member operations or assignments.
2897 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlsson96e93662010-10-31 01:21:47 +00002898 return false;
2899
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002900 // FIXME: Diagnostics? I really don't understand how the warnings
2901 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002902 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002903 if (!EvaluateFloat(E->getLHS(), Result, Info))
2904 return false;
2905 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2906 return false;
2907
2908 switch (E->getOpcode()) {
2909 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002910 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002911 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2912 return true;
John McCall2de56d12010-08-25 11:45:40 +00002913 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002914 Result.add(RHS, APFloat::rmNearestTiesToEven);
2915 return true;
John McCall2de56d12010-08-25 11:45:40 +00002916 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002917 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2918 return true;
John McCall2de56d12010-08-25 11:45:40 +00002919 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002920 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2921 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002922 }
2923}
2924
2925bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2926 Result = E->getValue();
2927 return true;
2928}
2929
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002930bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2931 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Eli Friedman2a523ee2011-03-25 00:54:52 +00002933 switch (E->getCastKind()) {
2934 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002935 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00002936
2937 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002938 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002939 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002940 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002941 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002942 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002943 return true;
2944 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002945
2946 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002947 if (!Visit(SubExpr))
2948 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002949 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2950 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002951 return true;
2952 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002953
Eli Friedman2a523ee2011-03-25 00:54:52 +00002954 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002955 ComplexValue V;
2956 if (!EvaluateComplex(SubExpr, V, Info))
2957 return false;
2958 Result = V.getComplexFloatReal();
2959 return true;
2960 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002961 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002962
2963 return false;
2964}
2965
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002966//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002967// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002968//===----------------------------------------------------------------------===//
2969
2970namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002971class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002972 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002973 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002975public:
John McCallf4cf1a12010-05-07 17:22:02 +00002976 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977 : ExprEvaluatorBaseTy(info), Result(Result) {}
2978
Richard Smith47a1eed2011-10-29 20:57:55 +00002979 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002980 Result.setFrom(V);
2981 return true;
2982 }
2983 bool Error(const Expr *E) {
2984 return false;
2985 }
Mike Stump1eb44332009-09-09 15:08:12 +00002986
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002987 //===--------------------------------------------------------------------===//
2988 // Visitor Methods
2989 //===--------------------------------------------------------------------===//
2990
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002991 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002993 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002994
John McCallf4cf1a12010-05-07 17:22:02 +00002995 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002996 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002997 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002998};
2999} // end anonymous namespace
3000
John McCallf4cf1a12010-05-07 17:22:02 +00003001static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3002 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003003 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003004 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003005}
3006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003007bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3008 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003009
3010 if (SubExpr->getType()->isRealFloatingType()) {
3011 Result.makeComplexFloat();
3012 APFloat &Imag = Result.FloatImag;
3013 if (!EvaluateFloat(SubExpr, Imag, Info))
3014 return false;
3015
3016 Result.FloatReal = APFloat(Imag.getSemantics());
3017 return true;
3018 } else {
3019 assert(SubExpr->getType()->isIntegerType() &&
3020 "Unexpected imaginary literal.");
3021
3022 Result.makeComplexInt();
3023 APSInt &Imag = Result.IntImag;
3024 if (!EvaluateInteger(SubExpr, Imag, Info))
3025 return false;
3026
3027 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3028 return true;
3029 }
3030}
3031
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003032bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003033
John McCall8786da72010-12-14 17:51:41 +00003034 switch (E->getCastKind()) {
3035 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00003036 case CK_BaseToDerived:
3037 case CK_DerivedToBase:
3038 case CK_UncheckedDerivedToBase:
3039 case CK_Dynamic:
3040 case CK_ToUnion:
3041 case CK_ArrayToPointerDecay:
3042 case CK_FunctionToPointerDecay:
3043 case CK_NullToPointer:
3044 case CK_NullToMemberPointer:
3045 case CK_BaseToDerivedMemberPointer:
3046 case CK_DerivedToBaseMemberPointer:
3047 case CK_MemberPointerToBoolean:
3048 case CK_ConstructorConversion:
3049 case CK_IntegralToPointer:
3050 case CK_PointerToIntegral:
3051 case CK_PointerToBoolean:
3052 case CK_ToVoid:
3053 case CK_VectorSplat:
3054 case CK_IntegralCast:
3055 case CK_IntegralToBoolean:
3056 case CK_IntegralToFloating:
3057 case CK_FloatingToIntegral:
3058 case CK_FloatingToBoolean:
3059 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003060 case CK_CPointerToObjCPointerCast:
3061 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00003062 case CK_AnyPointerToBlockPointerCast:
3063 case CK_ObjCObjectLValueCast:
3064 case CK_FloatingComplexToReal:
3065 case CK_FloatingComplexToBoolean:
3066 case CK_IntegralComplexToReal:
3067 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00003068 case CK_ARCProduceObject:
3069 case CK_ARCConsumeObject:
3070 case CK_ARCReclaimReturnedObject:
3071 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00003072 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00003073
John McCall8786da72010-12-14 17:51:41 +00003074 case CK_LValueToRValue:
3075 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003076 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00003077
3078 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003079 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00003080 case CK_UserDefinedConversion:
3081 return false;
3082
3083 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003084 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00003085 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003086 return false;
3087
John McCall8786da72010-12-14 17:51:41 +00003088 Result.makeComplexFloat();
3089 Result.FloatImag = APFloat(Real.getSemantics());
3090 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003091 }
3092
John McCall8786da72010-12-14 17:51:41 +00003093 case CK_FloatingComplexCast: {
3094 if (!Visit(E->getSubExpr()))
3095 return false;
3096
3097 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3098 QualType From
3099 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3100
3101 Result.FloatReal
3102 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3103 Result.FloatImag
3104 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3105 return true;
3106 }
3107
3108 case CK_FloatingComplexToIntegralComplex: {
3109 if (!Visit(E->getSubExpr()))
3110 return false;
3111
3112 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3113 QualType From
3114 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3115 Result.makeComplexInt();
3116 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3117 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3118 return true;
3119 }
3120
3121 case CK_IntegralRealToComplex: {
3122 APSInt &Real = Result.IntReal;
3123 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3124 return false;
3125
3126 Result.makeComplexInt();
3127 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3128 return true;
3129 }
3130
3131 case CK_IntegralComplexCast: {
3132 if (!Visit(E->getSubExpr()))
3133 return false;
3134
3135 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3136 QualType From
3137 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3138
3139 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3140 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3141 return true;
3142 }
3143
3144 case CK_IntegralComplexToFloatingComplex: {
3145 if (!Visit(E->getSubExpr()))
3146 return false;
3147
3148 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3149 QualType From
3150 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3151 Result.makeComplexFloat();
3152 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3153 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3154 return true;
3155 }
3156 }
3157
3158 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003159 return false;
3160}
3161
John McCallf4cf1a12010-05-07 17:22:02 +00003162bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003163 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003164 VisitIgnoredValue(E->getLHS());
3165 return Visit(E->getRHS());
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003166 }
John McCallf4cf1a12010-05-07 17:22:02 +00003167 if (!Visit(E->getLHS()))
3168 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003169
John McCallf4cf1a12010-05-07 17:22:02 +00003170 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003171 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00003172 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003173
Daniel Dunbar3f279872009-01-29 01:32:56 +00003174 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3175 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003176 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003177 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003178 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003179 if (Result.isComplexFloat()) {
3180 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3181 APFloat::rmNearestTiesToEven);
3182 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3183 APFloat::rmNearestTiesToEven);
3184 } else {
3185 Result.getComplexIntReal() += RHS.getComplexIntReal();
3186 Result.getComplexIntImag() += RHS.getComplexIntImag();
3187 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003188 break;
John McCall2de56d12010-08-25 11:45:40 +00003189 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003190 if (Result.isComplexFloat()) {
3191 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3192 APFloat::rmNearestTiesToEven);
3193 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3194 APFloat::rmNearestTiesToEven);
3195 } else {
3196 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3197 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3198 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003199 break;
John McCall2de56d12010-08-25 11:45:40 +00003200 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00003201 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003202 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00003203 APFloat &LHS_r = LHS.getComplexFloatReal();
3204 APFloat &LHS_i = LHS.getComplexFloatImag();
3205 APFloat &RHS_r = RHS.getComplexFloatReal();
3206 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Daniel Dunbar3f279872009-01-29 01:32:56 +00003208 APFloat Tmp = LHS_r;
3209 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3210 Result.getComplexFloatReal() = Tmp;
3211 Tmp = LHS_i;
3212 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3213 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3214
3215 Tmp = LHS_r;
3216 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3217 Result.getComplexFloatImag() = Tmp;
3218 Tmp = LHS_i;
3219 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3220 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3221 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00003222 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003223 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003224 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3225 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00003226 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003227 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3228 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3229 }
3230 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003231 case BO_Div:
3232 if (Result.isComplexFloat()) {
3233 ComplexValue LHS = Result;
3234 APFloat &LHS_r = LHS.getComplexFloatReal();
3235 APFloat &LHS_i = LHS.getComplexFloatImag();
3236 APFloat &RHS_r = RHS.getComplexFloatReal();
3237 APFloat &RHS_i = RHS.getComplexFloatImag();
3238 APFloat &Res_r = Result.getComplexFloatReal();
3239 APFloat &Res_i = Result.getComplexFloatImag();
3240
3241 APFloat Den = RHS_r;
3242 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3243 APFloat Tmp = RHS_i;
3244 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3245 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3246
3247 Res_r = LHS_r;
3248 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3249 Tmp = LHS_i;
3250 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3251 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3252 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3253
3254 Res_i = LHS_i;
3255 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3256 Tmp = LHS_r;
3257 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3258 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3259 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3260 } else {
3261 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3262 // FIXME: what about diagnostics?
3263 return false;
3264 }
3265 ComplexValue LHS = Result;
3266 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3267 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3268 Result.getComplexIntReal() =
3269 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3270 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3271 Result.getComplexIntImag() =
3272 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3273 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3274 }
3275 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003276 }
3277
John McCallf4cf1a12010-05-07 17:22:02 +00003278 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003279}
3280
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003281bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3282 // Get the operand value into 'Result'.
3283 if (!Visit(E->getSubExpr()))
3284 return false;
3285
3286 switch (E->getOpcode()) {
3287 default:
3288 // FIXME: what about diagnostics?
3289 return false;
3290 case UO_Extension:
3291 return true;
3292 case UO_Plus:
3293 // The result is always just the subexpr.
3294 return true;
3295 case UO_Minus:
3296 if (Result.isComplexFloat()) {
3297 Result.getComplexFloatReal().changeSign();
3298 Result.getComplexFloatImag().changeSign();
3299 }
3300 else {
3301 Result.getComplexIntReal() = -Result.getComplexIntReal();
3302 Result.getComplexIntImag() = -Result.getComplexIntImag();
3303 }
3304 return true;
3305 case UO_Not:
3306 if (Result.isComplexFloat())
3307 Result.getComplexFloatImag().changeSign();
3308 else
3309 Result.getComplexIntImag() = -Result.getComplexIntImag();
3310 return true;
3311 }
3312}
3313
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003314//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00003315// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003316//===----------------------------------------------------------------------===//
3317
Richard Smith47a1eed2011-10-29 20:57:55 +00003318static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003319 // In C, function designators are not lvalues, but we evaluate them as if they
3320 // are.
3321 if (E->isGLValue() || E->getType()->isFunctionType()) {
3322 LValue LV;
3323 if (!EvaluateLValue(E, LV, Info))
3324 return false;
3325 LV.moveInto(Result);
3326 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003327 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00003328 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00003329 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003330 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003331 return false;
John McCallefdb83e2010-05-07 21:00:08 +00003332 } else if (E->getType()->hasPointerRepresentation()) {
3333 LValue LV;
3334 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003335 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003336 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00003337 } else if (E->getType()->isRealFloatingType()) {
3338 llvm::APFloat F(0.0);
3339 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003340 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003341 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00003342 } else if (E->getType()->isAnyComplexType()) {
3343 ComplexValue C;
3344 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003345 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003346 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00003347 } else if (E->getType()->isMemberPointerType()) {
3348 // FIXME: Implement evaluation of pointer-to-member types.
3349 return false;
3350 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00003351 if (!EvaluateArray(E, Result, Info))
3352 return false;
Richard Smith69c2c502011-11-04 05:33:44 +00003353 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3354 // FIXME: Implement evaluation of record rvalues.
3355 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003356 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00003357 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003358
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00003359 return true;
3360}
3361
Richard Smith69c2c502011-11-04 05:33:44 +00003362/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3363/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3364/// since later initializers for an object can indirectly refer to subobjects
3365/// which were initialized earlier.
3366static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3367 const Expr *E) {
3368 if (E->isRValue() && E->getType()->isLiteralType()) {
3369 // Evaluate arrays and record types in-place, so that later initializers can
3370 // refer to earlier-initialized members of the object.
Richard Smithcc5d4f62011-11-07 09:22:26 +00003371 if (E->getType()->isArrayType()) {
3372 if (!EvaluateArray(E, Result, Info))
3373 return false;
3374 } else if (E->getType()->isRecordType())
Richard Smith69c2c502011-11-04 05:33:44 +00003375 // FIXME: Implement evaluation of record rvalues.
3376 return false;
3377 }
3378
3379 // For any other type, in-place evaluation is unimportant.
3380 CCValue CoreConstResult;
3381 return Evaluate(CoreConstResult, Info, E) &&
3382 CheckConstantExpression(CoreConstResult, Result);
3383}
3384
Richard Smithc49bd112011-10-28 17:51:58 +00003385
Richard Smith51f47082011-10-29 00:50:52 +00003386/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00003387/// any crazy technique (that has nothing to do with language standards) that
3388/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00003389/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3390/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00003391bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
John McCall56ca35d2011-02-17 10:25:35 +00003392 EvalInfo Info(Ctx, Result);
Richard Smithc49bd112011-10-28 17:51:58 +00003393
Richard Smith47a1eed2011-10-29 20:57:55 +00003394 CCValue Value;
3395 if (!::Evaluate(Value, Info, this))
Richard Smithc49bd112011-10-28 17:51:58 +00003396 return false;
3397
3398 if (isGLValue()) {
3399 LValue LV;
Richard Smith47a1eed2011-10-29 20:57:55 +00003400 LV.setFrom(Value);
3401 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3402 return false;
Richard Smithc49bd112011-10-28 17:51:58 +00003403 }
3404
Richard Smithcc5d4f62011-11-07 09:22:26 +00003405 // Don't produce array constants until CodeGen is taught to handle them.
3406 if (Value.isArray())
3407 return false;
3408
Richard Smith47a1eed2011-10-29 20:57:55 +00003409 // Check this core constant expression is a constant expression, and if so,
Richard Smith69c2c502011-11-04 05:33:44 +00003410 // convert it to one.
3411 return CheckConstantExpression(Value, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00003412}
3413
Jay Foad4ba2a172011-01-12 09:06:06 +00003414bool Expr::EvaluateAsBooleanCondition(bool &Result,
3415 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003416 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00003417 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00003418 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00003419 Result);
John McCallcd7a4452010-01-05 23:42:56 +00003420}
3421
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003422bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003423 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00003424 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithc49bd112011-10-28 17:51:58 +00003425 !ExprResult.Val.isInt()) {
3426 return false;
3427 }
3428 Result = ExprResult.Val.getInt();
3429 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003430}
3431
Jay Foad4ba2a172011-01-12 09:06:06 +00003432bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00003433 EvalInfo Info(Ctx, Result);
3434
John McCallefdb83e2010-05-07 21:00:08 +00003435 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00003436 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3437 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00003438}
3439
Richard Smith51f47082011-10-29 00:50:52 +00003440/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3441/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00003442bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00003443 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00003444 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00003445}
Anders Carlsson51fe9962008-11-22 21:04:56 +00003446
Jay Foad4ba2a172011-01-12 09:06:06 +00003447bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00003448 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003449}
3450
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003451APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003452 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00003453 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00003454 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00003455 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003456 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00003457
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003458 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00003459}
John McCalld905f5a2010-05-07 05:32:02 +00003460
Abramo Bagnarae17a6432010-05-14 17:07:14 +00003461 bool Expr::EvalResult::isGlobalLValue() const {
3462 assert(Val.isLValue());
3463 return IsGlobalLValue(Val.getLValueBase());
3464 }
3465
3466
John McCalld905f5a2010-05-07 05:32:02 +00003467/// isIntegerConstantExpr - this recursive routine will test if an expression is
3468/// an integer constant expression.
3469
3470/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3471/// comma, etc
3472///
3473/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3474/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3475/// cast+dereference.
3476
3477// CheckICE - This function does the fundamental ICE checking: the returned
3478// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3479// Note that to reduce code duplication, this helper does no evaluation
3480// itself; the caller checks whether the expression is evaluatable, and
3481// in the rare cases where CheckICE actually cares about the evaluated
3482// value, it calls into Evalute.
3483//
3484// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00003485// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00003486// 1: This expression is not an ICE, but if it isn't evaluated, it's
3487// a legal subexpression for an ICE. This return value is used to handle
3488// the comma operator in C99 mode.
3489// 2: This expression is not an ICE, and is not a legal subexpression for one.
3490
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003491namespace {
3492
John McCalld905f5a2010-05-07 05:32:02 +00003493struct ICEDiag {
3494 unsigned Val;
3495 SourceLocation Loc;
3496
3497 public:
3498 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3499 ICEDiag() : Val(0) {}
3500};
3501
Dan Gohman3c46e8d2010-07-26 21:25:24 +00003502}
3503
3504static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00003505
3506static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3507 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00003508 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00003509 !EVResult.Val.isInt()) {
3510 return ICEDiag(2, E->getLocStart());
3511 }
3512 return NoDiag();
3513}
3514
3515static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
3516 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003517 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00003518 return ICEDiag(2, E->getLocStart());
3519 }
3520
3521 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00003522#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00003523#define STMT(Node, Base) case Expr::Node##Class:
3524#define EXPR(Node, Base)
3525#include "clang/AST/StmtNodes.inc"
3526 case Expr::PredefinedExprClass:
3527 case Expr::FloatingLiteralClass:
3528 case Expr::ImaginaryLiteralClass:
3529 case Expr::StringLiteralClass:
3530 case Expr::ArraySubscriptExprClass:
3531 case Expr::MemberExprClass:
3532 case Expr::CompoundAssignOperatorClass:
3533 case Expr::CompoundLiteralExprClass:
3534 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003535 case Expr::DesignatedInitExprClass:
3536 case Expr::ImplicitValueInitExprClass:
3537 case Expr::ParenListExprClass:
3538 case Expr::VAArgExprClass:
3539 case Expr::AddrLabelExprClass:
3540 case Expr::StmtExprClass:
3541 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00003542 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003543 case Expr::CXXDynamicCastExprClass:
3544 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00003545 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003546 case Expr::CXXNullPtrLiteralExprClass:
3547 case Expr::CXXThisExprClass:
3548 case Expr::CXXThrowExprClass:
3549 case Expr::CXXNewExprClass:
3550 case Expr::CXXDeleteExprClass:
3551 case Expr::CXXPseudoDestructorExprClass:
3552 case Expr::UnresolvedLookupExprClass:
3553 case Expr::DependentScopeDeclRefExprClass:
3554 case Expr::CXXConstructExprClass:
3555 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00003556 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00003557 case Expr::CXXTemporaryObjectExprClass:
3558 case Expr::CXXUnresolvedConstructExprClass:
3559 case Expr::CXXDependentScopeMemberExprClass:
3560 case Expr::UnresolvedMemberExprClass:
3561 case Expr::ObjCStringLiteralClass:
3562 case Expr::ObjCEncodeExprClass:
3563 case Expr::ObjCMessageExprClass:
3564 case Expr::ObjCSelectorExprClass:
3565 case Expr::ObjCProtocolExprClass:
3566 case Expr::ObjCIvarRefExprClass:
3567 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003568 case Expr::ObjCIsaExprClass:
3569 case Expr::ShuffleVectorExprClass:
3570 case Expr::BlockExprClass:
3571 case Expr::BlockDeclRefExprClass:
3572 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00003573 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00003574 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00003575 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003576 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003577 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00003578 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00003579 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00003580 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003581 return ICEDiag(2, E->getLocStart());
3582
Sebastian Redlcea8d962011-09-24 17:48:14 +00003583 case Expr::InitListExprClass:
3584 if (Ctx.getLangOptions().CPlusPlus0x) {
3585 const InitListExpr *ILE = cast<InitListExpr>(E);
3586 if (ILE->getNumInits() == 0)
3587 return NoDiag();
3588 if (ILE->getNumInits() == 1)
3589 return CheckICE(ILE->getInit(0), Ctx);
3590 // Fall through for more than 1 expression.
3591 }
3592 return ICEDiag(2, E->getLocStart());
3593
Douglas Gregoree8aff02011-01-04 17:33:58 +00003594 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003595 case Expr::GNUNullExprClass:
3596 // GCC considers the GNU __null value to be an integral constant expression.
3597 return NoDiag();
3598
John McCall91a57552011-07-15 05:09:51 +00003599 case Expr::SubstNonTypeTemplateParmExprClass:
3600 return
3601 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3602
John McCalld905f5a2010-05-07 05:32:02 +00003603 case Expr::ParenExprClass:
3604 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00003605 case Expr::GenericSelectionExprClass:
3606 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003607 case Expr::IntegerLiteralClass:
3608 case Expr::CharacterLiteralClass:
3609 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00003610 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003611 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00003612 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00003613 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00003614 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00003615 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00003616 return NoDiag();
3617 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00003618 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00003619 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3620 // constant expressions, but they can never be ICEs because an ICE cannot
3621 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00003622 const CallExpr *CE = cast<CallExpr>(E);
3623 if (CE->isBuiltinCall(Ctx))
3624 return CheckEvalInICE(E, Ctx);
3625 return ICEDiag(2, E->getLocStart());
3626 }
3627 case Expr::DeclRefExprClass:
3628 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3629 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00003630 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00003631 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3632
3633 // Parameter variables are never constants. Without this check,
3634 // getAnyInitializer() can find a default argument, which leads
3635 // to chaos.
3636 if (isa<ParmVarDecl>(D))
3637 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3638
3639 // C++ 7.1.5.1p2
3640 // A variable of non-volatile const-qualified integral or enumeration
3641 // type initialized by an ICE can be used in ICEs.
3642 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCalld905f5a2010-05-07 05:32:02 +00003643 // Look for a declaration of this variable that has an initializer.
3644 const VarDecl *ID = 0;
3645 const Expr *Init = Dcl->getAnyInitializer(ID);
3646 if (Init) {
3647 if (ID->isInitKnownICE()) {
3648 // We have already checked whether this subexpression is an
3649 // integral constant expression.
3650 if (ID->isInitICE())
3651 return NoDiag();
3652 else
3653 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3654 }
3655
3656 // It's an ICE whether or not the definition we found is
3657 // out-of-line. See DR 721 and the discussion in Clang PR
3658 // 6206 for details.
3659
3660 if (Dcl->isCheckingICE()) {
3661 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3662 }
3663
3664 Dcl->setCheckingICE();
3665 ICEDiag Result = CheckICE(Init, Ctx);
3666 // Cache the result of the ICE test.
3667 Dcl->setInitKnownICE(Result.Val == 0);
3668 return Result;
3669 }
3670 }
3671 }
3672 return ICEDiag(2, E->getLocStart());
3673 case Expr::UnaryOperatorClass: {
3674 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3675 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00003676 case UO_PostInc:
3677 case UO_PostDec:
3678 case UO_PreInc:
3679 case UO_PreDec:
3680 case UO_AddrOf:
3681 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00003682 // C99 6.6/3 allows increment and decrement within unevaluated
3683 // subexpressions of constant expressions, but they can never be ICEs
3684 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00003685 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00003686 case UO_Extension:
3687 case UO_LNot:
3688 case UO_Plus:
3689 case UO_Minus:
3690 case UO_Not:
3691 case UO_Real:
3692 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00003693 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003694 }
3695
3696 // OffsetOf falls through here.
3697 }
3698 case Expr::OffsetOfExprClass: {
3699 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00003700 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00003701 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00003702 // compliance: we should warn earlier for offsetof expressions with
3703 // array subscripts that aren't ICEs, and if the array subscripts
3704 // are ICEs, the value of the offsetof must be an integer constant.
3705 return CheckEvalInICE(E, Ctx);
3706 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003707 case Expr::UnaryExprOrTypeTraitExprClass: {
3708 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3709 if ((Exp->getKind() == UETT_SizeOf) &&
3710 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00003711 return ICEDiag(2, E->getLocStart());
3712 return NoDiag();
3713 }
3714 case Expr::BinaryOperatorClass: {
3715 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3716 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00003717 case BO_PtrMemD:
3718 case BO_PtrMemI:
3719 case BO_Assign:
3720 case BO_MulAssign:
3721 case BO_DivAssign:
3722 case BO_RemAssign:
3723 case BO_AddAssign:
3724 case BO_SubAssign:
3725 case BO_ShlAssign:
3726 case BO_ShrAssign:
3727 case BO_AndAssign:
3728 case BO_XorAssign:
3729 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00003730 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3731 // constant expressions, but they can never be ICEs because an ICE cannot
3732 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00003733 return ICEDiag(2, E->getLocStart());
3734
John McCall2de56d12010-08-25 11:45:40 +00003735 case BO_Mul:
3736 case BO_Div:
3737 case BO_Rem:
3738 case BO_Add:
3739 case BO_Sub:
3740 case BO_Shl:
3741 case BO_Shr:
3742 case BO_LT:
3743 case BO_GT:
3744 case BO_LE:
3745 case BO_GE:
3746 case BO_EQ:
3747 case BO_NE:
3748 case BO_And:
3749 case BO_Xor:
3750 case BO_Or:
3751 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003752 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3753 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003754 if (Exp->getOpcode() == BO_Div ||
3755 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00003756 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00003757 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003758 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003759 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003760 if (REval == 0)
3761 return ICEDiag(1, E->getLocStart());
3762 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003763 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003764 if (LEval.isMinSignedValue())
3765 return ICEDiag(1, E->getLocStart());
3766 }
3767 }
3768 }
John McCall2de56d12010-08-25 11:45:40 +00003769 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003770 if (Ctx.getLangOptions().C99) {
3771 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3772 // if it isn't evaluated.
3773 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3774 return ICEDiag(1, E->getLocStart());
3775 } else {
3776 // In both C89 and C++, commas in ICEs are illegal.
3777 return ICEDiag(2, E->getLocStart());
3778 }
3779 }
3780 if (LHSResult.Val >= RHSResult.Val)
3781 return LHSResult;
3782 return RHSResult;
3783 }
John McCall2de56d12010-08-25 11:45:40 +00003784 case BO_LAnd:
3785 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003786 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00003787
3788 // C++0x [expr.const]p2:
3789 // [...] subexpressions of logical AND (5.14), logical OR
3790 // (5.15), and condi- tional (5.16) operations that are not
3791 // evaluated are not considered.
3792 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3793 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003794 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003795 return LHSResult;
3796
3797 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003798 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00003799 return LHSResult;
3800 }
3801
John McCalld905f5a2010-05-07 05:32:02 +00003802 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3803 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3804 // Rare case where the RHS has a comma "side-effect"; we need
3805 // to actually check the condition to see whether the side
3806 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003807 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003808 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00003809 return RHSResult;
3810 return NoDiag();
3811 }
3812
3813 if (LHSResult.Val >= RHSResult.Val)
3814 return LHSResult;
3815 return RHSResult;
3816 }
3817 }
3818 }
3819 case Expr::ImplicitCastExprClass:
3820 case Expr::CStyleCastExprClass:
3821 case Expr::CXXFunctionalCastExprClass:
3822 case Expr::CXXStaticCastExprClass:
3823 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00003824 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003825 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003826 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00003827 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00003828 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3829 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00003830 switch (cast<CastExpr>(E)->getCastKind()) {
3831 case CK_LValueToRValue:
3832 case CK_NoOp:
3833 case CK_IntegralToBoolean:
3834 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00003835 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00003836 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00003837 return ICEDiag(2, E->getLocStart());
3838 }
John McCalld905f5a2010-05-07 05:32:02 +00003839 }
John McCall56ca35d2011-02-17 10:25:35 +00003840 case Expr::BinaryConditionalOperatorClass: {
3841 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3842 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3843 if (CommonResult.Val == 2) return CommonResult;
3844 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3845 if (FalseResult.Val == 2) return FalseResult;
3846 if (CommonResult.Val == 1) return CommonResult;
3847 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003848 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00003849 return FalseResult;
3850 }
John McCalld905f5a2010-05-07 05:32:02 +00003851 case Expr::ConditionalOperatorClass: {
3852 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3853 // If the condition (ignoring parens) is a __builtin_constant_p call,
3854 // then only the true side is actually considered in an integer constant
3855 // expression, and it is fully evaluated. This is an important GNU
3856 // extension. See GCC PR38377 for discussion.
3857 if (const CallExpr *CallCE
3858 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3859 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3860 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00003861 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00003862 !EVResult.Val.isInt()) {
3863 return ICEDiag(2, E->getLocStart());
3864 }
3865 return NoDiag();
3866 }
3867 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003868 if (CondResult.Val == 2)
3869 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003870
3871 // C++0x [expr.const]p2:
3872 // subexpressions of [...] conditional (5.16) operations that
3873 // are not evaluated are not considered
3874 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003875 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00003876 : false;
3877 ICEDiag TrueResult = NoDiag();
3878 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3879 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3880 ICEDiag FalseResult = NoDiag();
3881 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3882 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3883
John McCalld905f5a2010-05-07 05:32:02 +00003884 if (TrueResult.Val == 2)
3885 return TrueResult;
3886 if (FalseResult.Val == 2)
3887 return FalseResult;
3888 if (CondResult.Val == 1)
3889 return CondResult;
3890 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3891 return NoDiag();
3892 // Rare case where the diagnostics depend on which side is evaluated
3893 // Note that if we get here, CondResult is 0, and at least one of
3894 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003895 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003896 return FalseResult;
3897 }
3898 return TrueResult;
3899 }
3900 case Expr::CXXDefaultArgExprClass:
3901 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3902 case Expr::ChooseExprClass: {
3903 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3904 }
3905 }
3906
3907 // Silence a GCC warning
3908 return ICEDiag(2, E->getLocStart());
3909}
3910
3911bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3912 SourceLocation *Loc, bool isEvaluated) const {
3913 ICEDiag d = CheckICE(this, Ctx);
3914 if (d.Val != 0) {
3915 if (Loc) *Loc = d.Loc;
3916 return false;
3917 }
Richard Smithc49bd112011-10-28 17:51:58 +00003918 if (!EvaluateAsInt(Result, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00003919 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00003920 return true;
3921}