blob: f461ec642906d50a8963d868f61dff6d7374f7a6 [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 Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith9a17a682011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith0a3bdb62011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith9a17a682011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
129 }
130 }
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 void setInvalid() {
133 Invalid = true;
134 Entries.clear();
135 }
136 /// Update this designator to refer to the given element within this array.
137 void addIndex(uint64_t N) {
138 if (Invalid) return;
139 if (OnePastTheEnd) {
140 setInvalid();
141 return;
142 }
143 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000144 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000145 Entries.push_back(Entry);
146 ArrayElement = true;
147 }
148 /// Update this designator to refer to the given base or member of this
149 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000150 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151 if (Invalid) return;
152 if (OnePastTheEnd) {
153 setInvalid();
154 return;
155 }
156 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000157 APValue::BaseOrMemberType Value(D, Virtual);
158 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159 Entries.push_back(Entry);
160 ArrayElement = false;
161 }
162 /// Add N to the address of this subobject.
163 void adjustIndex(uint64_t N) {
164 if (Invalid) return;
165 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000166 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000167 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000168 return;
169 }
170 if (OnePastTheEnd && N == (uint64_t)-1)
171 OnePastTheEnd = false;
172 else if (!OnePastTheEnd && N == 1)
173 OnePastTheEnd = true;
174 else if (N != 0)
175 setInvalid();
176 }
177 };
178
Richard Smith47a1eed2011-10-29 20:57:55 +0000179 /// A core constant value. This can be the value of any constant expression,
180 /// or a pointer or reference to a non-static object or function parameter.
181 class CCValue : public APValue {
182 typedef llvm::APSInt APSInt;
183 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000184 /// If the value is a reference or pointer into a parameter or temporary,
185 /// this is the corresponding call stack frame.
186 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000187 /// If the value is a reference or pointer, this is a description of how the
188 /// subobject was specified.
189 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000190 public:
Richard Smith177dce72011-11-01 16:57:24 +0000191 struct GlobalValue {};
192
Richard Smith47a1eed2011-10-29 20:57:55 +0000193 CCValue() {}
194 explicit CCValue(const APSInt &I) : APValue(I) {}
195 explicit CCValue(const APFloat &F) : APValue(F) {}
196 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
197 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
198 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000199 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000200 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000201 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000202 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000203 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000204 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000205
Richard Smith177dce72011-11-01 16:57:24 +0000206 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000207 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000208 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000209 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000210 SubobjectDesignator &getLValueDesignator() {
211 assert(getKind() == LValue);
212 return Designator;
213 }
214 const SubobjectDesignator &getLValueDesignator() const {
215 return const_cast<CCValue*>(this)->getLValueDesignator();
216 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 };
218
Richard Smithd0dccea2011-10-28 22:34:42 +0000219 /// A stack frame in the constexpr call stack.
220 struct CallStackFrame {
221 EvalInfo &Info;
222
223 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000224 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000225
Richard Smith180f4792011-11-10 06:34:14 +0000226 /// This - The binding for the this pointer in this call, if any.
227 const LValue *This;
228
Richard Smithd0dccea2011-10-28 22:34:42 +0000229 /// ParmBindings - Parameter bindings for this function call, indexed by
230 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000231 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000232
Richard Smithbd552ef2011-10-31 05:52:43 +0000233 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
234 typedef MapTy::const_iterator temp_iterator;
235 /// Temporaries - Temporary lvalues materialized within this stack frame.
236 MapTy Temporaries;
237
Richard Smith180f4792011-11-10 06:34:14 +0000238 CallStackFrame(EvalInfo &Info, const LValue *This,
239 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000240 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000241 };
242
Richard Smithbd552ef2011-10-31 05:52:43 +0000243 struct EvalInfo {
244 const ASTContext &Ctx;
245
246 /// EvalStatus - Contains information about the evaluation.
247 Expr::EvalStatus &EvalStatus;
248
249 /// CurrentCall - The top of the constexpr call stack.
250 CallStackFrame *CurrentCall;
251
252 /// NumCalls - The number of calls we've evaluated so far.
253 unsigned NumCalls;
254
255 /// CallStackDepth - The number of calls in the call stack right now.
256 unsigned CallStackDepth;
257
258 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
259 /// OpaqueValues - Values used as the common expression in a
260 /// BinaryConditionalOperator.
261 MapTy OpaqueValues;
262
263 /// BottomFrame - The frame in which evaluation started. This must be
264 /// initialized last.
265 CallStackFrame BottomFrame;
266
Richard Smith180f4792011-11-10 06:34:14 +0000267 /// EvaluatingDecl - This is the declaration whose initializer is being
268 /// evaluated, if any.
269 const VarDecl *EvaluatingDecl;
270
271 /// EvaluatingDeclValue - This is the value being constructed for the
272 /// declaration whose initializer is being evaluated, if any.
273 APValue *EvaluatingDeclValue;
274
Richard Smithbd552ef2011-10-31 05:52:43 +0000275
276 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
277 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
Richard Smith180f4792011-11-10 06:34:14 +0000278 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000279
Richard Smithbd552ef2011-10-31 05:52:43 +0000280 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
281 MapTy::const_iterator i = OpaqueValues.find(e);
282 if (i == OpaqueValues.end()) return 0;
283 return &i->second;
284 }
285
Richard Smith180f4792011-11-10 06:34:14 +0000286 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
287 EvaluatingDecl = VD;
288 EvaluatingDeclValue = &Value;
289 }
290
Richard Smithbd552ef2011-10-31 05:52:43 +0000291 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
292 };
293
Richard Smith180f4792011-11-10 06:34:14 +0000294 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
295 const CCValue *Arguments)
296 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smithbd552ef2011-10-31 05:52:43 +0000297 Info.CurrentCall = this;
298 ++Info.CallStackDepth;
299 }
300
301 CallStackFrame::~CallStackFrame() {
302 assert(Info.CurrentCall == this && "calls retired out of order");
303 --Info.CallStackDepth;
304 Info.CurrentCall = Caller;
305 }
306
John McCallf4cf1a12010-05-07 17:22:02 +0000307 struct ComplexValue {
308 private:
309 bool IsInt;
310
311 public:
312 APSInt IntReal, IntImag;
313 APFloat FloatReal, FloatImag;
314
315 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
316
317 void makeComplexFloat() { IsInt = false; }
318 bool isComplexFloat() const { return !IsInt; }
319 APFloat &getComplexFloatReal() { return FloatReal; }
320 APFloat &getComplexFloatImag() { return FloatImag; }
321
322 void makeComplexInt() { IsInt = true; }
323 bool isComplexInt() const { return IsInt; }
324 APSInt &getComplexIntReal() { return IntReal; }
325 APSInt &getComplexIntImag() { return IntImag; }
326
Richard Smith47a1eed2011-10-29 20:57:55 +0000327 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000328 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000329 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000330 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000331 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000332 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000333 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000334 assert(v.isComplexFloat() || v.isComplexInt());
335 if (v.isComplexFloat()) {
336 makeComplexFloat();
337 FloatReal = v.getComplexFloatReal();
338 FloatImag = v.getComplexFloatImag();
339 } else {
340 makeComplexInt();
341 IntReal = v.getComplexIntReal();
342 IntImag = v.getComplexIntImag();
343 }
344 }
John McCallf4cf1a12010-05-07 17:22:02 +0000345 };
John McCallefdb83e2010-05-07 21:00:08 +0000346
347 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000348 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000349 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000350 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000351 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000352
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000353 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000354 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000355 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000356 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000357 SubobjectDesignator &getLValueDesignator() { return Designator; }
358 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000359
Richard Smith47a1eed2011-10-29 20:57:55 +0000360 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000361 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000362 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000363 void setFrom(const CCValue &V) {
364 assert(V.isLValue());
365 Base = V.getLValueBase();
366 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000367 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000368 Designator = V.getLValueDesignator();
369 }
370
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000371 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
372 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000373 Offset = CharUnits::Zero();
374 Frame = F;
375 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000376 }
John McCallefdb83e2010-05-07 21:00:08 +0000377 };
John McCallf4cf1a12010-05-07 17:22:02 +0000378}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000379
Richard Smith47a1eed2011-10-29 20:57:55 +0000380static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000381static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +0000382 const LValue &This, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000383static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
384static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000385static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000386static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000387 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000388static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000389static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000390
391//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000392// Misc utilities
393//===----------------------------------------------------------------------===//
394
Richard Smith180f4792011-11-10 06:34:14 +0000395/// Should this call expression be treated as a string literal?
396static bool IsStringLiteralCall(const CallExpr *E) {
397 unsigned Builtin = E->isBuiltinCall();
398 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
399 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
400}
401
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000402static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000403 // C++11 [expr.const]p3 An address constant expression is a prvalue core
404 // constant expression of pointer type that evaluates to...
405
406 // ... a null pointer value, or a prvalue core constant expression of type
407 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000408 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000409
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000410 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
411 // ... the address of an object with static storage duration,
412 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
413 return VD->hasGlobalStorage();
414 // ... the address of a function,
415 return isa<FunctionDecl>(D);
416 }
417
418 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000419 switch (E->getStmtClass()) {
420 default:
421 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000422 case Expr::CompoundLiteralExprClass:
423 return cast<CompoundLiteralExpr>(E)->isFileScope();
424 // A string literal has static storage duration.
425 case Expr::StringLiteralClass:
426 case Expr::PredefinedExprClass:
427 case Expr::ObjCStringLiteralClass:
428 case Expr::ObjCEncodeExprClass:
429 return true;
430 case Expr::CallExprClass:
431 return IsStringLiteralCall(cast<CallExpr>(E));
432 // For GCC compatibility, &&label has static storage duration.
433 case Expr::AddrLabelExprClass:
434 return true;
435 // A Block literal expression may be used as the initialization value for
436 // Block variables at global or local static scope.
437 case Expr::BlockExprClass:
438 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
439 }
John McCall42c8f872010-05-10 23:27:23 +0000440}
441
Richard Smith9a17a682011-11-07 05:07:52 +0000442/// Check that this reference or pointer core constant expression is a valid
443/// value for a constant expression. Type T should be either LValue or CCValue.
444template<typename T>
445static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
446 if (!IsGlobalLValue(LVal.getLValueBase()))
447 return false;
448
449 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
450 // A constant expression must refer to an object or be a null pointer.
451 if (Designator.Invalid || Designator.OnePastTheEnd ||
452 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
453 // FIXME: Check for out-of-bounds array indices.
454 // FIXME: This is not a constant expression.
455 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
456 APValue::NoLValuePath());
457 return true;
458 }
459
Richard Smith180f4792011-11-10 06:34:14 +0000460 // FIXME: Null references are not constant expressions.
461
Richard Smith9a17a682011-11-07 05:07:52 +0000462 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
463 Designator.Entries);
464 return true;
465}
466
Richard Smith47a1eed2011-10-29 20:57:55 +0000467/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000468/// constant expression, and if it is, produce the corresponding constant value.
469static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith9a17a682011-11-07 05:07:52 +0000470 if (!CCValue.isLValue()) {
471 Value = CCValue;
472 return true;
473 }
474 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith47a1eed2011-10-29 20:57:55 +0000475}
476
Richard Smith9e36b532011-10-31 05:11:32 +0000477const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000478 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000479}
480
481static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000482 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000483}
484
Richard Smith65ac5982011-11-01 21:06:14 +0000485static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith9e36b532011-10-31 05:11:32 +0000486 return Decl->hasAttr<WeakAttr>() ||
487 Decl->hasAttr<WeakRefAttr>() ||
488 Decl->isWeakImported();
489}
490
Richard Smith65ac5982011-11-01 21:06:14 +0000491static bool IsWeakLValue(const LValue &Value) {
492 const ValueDecl *Decl = GetLValueBaseDecl(Value);
493 return Decl && IsWeakDecl(Decl);
494}
495
Richard Smithc49bd112011-10-28 17:51:58 +0000496static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000497 // A null base expression indicates a null pointer. These are always
498 // evaluatable, and they are false unless the offset is zero.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000499 if (!Value.Base) {
John McCall35542832010-05-07 21:34:32 +0000500 Result = !Value.Offset.isZero();
501 return true;
502 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000503
John McCall42c8f872010-05-10 23:27:23 +0000504 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000505 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000506 if (!IsGlobalLValue(Value.Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000507
John McCall35542832010-05-07 21:34:32 +0000508 // We have a non-null base expression. These are generally known to
509 // be true, but if it'a decl-ref to a weak symbol it can be null at
510 // runtime.
John McCall35542832010-05-07 21:34:32 +0000511 Result = true;
Richard Smith9e36b532011-10-31 05:11:32 +0000512 return !IsWeakLValue(Value);
Eli Friedman5bc86102009-06-14 02:17:33 +0000513}
514
Richard Smith47a1eed2011-10-29 20:57:55 +0000515static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000516 switch (Val.getKind()) {
517 case APValue::Uninitialized:
518 return false;
519 case APValue::Int:
520 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000521 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000522 case APValue::Float:
523 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000524 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000525 case APValue::ComplexInt:
526 Result = Val.getComplexIntReal().getBoolValue() ||
527 Val.getComplexIntImag().getBoolValue();
528 return true;
529 case APValue::ComplexFloat:
530 Result = !Val.getComplexFloatReal().isZero() ||
531 !Val.getComplexFloatImag().isZero();
532 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +0000533 case APValue::LValue: {
534 LValue PointerResult;
535 PointerResult.setFrom(Val);
536 return EvalPointerValueAsBool(PointerResult, Result);
537 }
Richard Smithc49bd112011-10-28 17:51:58 +0000538 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000539 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000540 case APValue::Struct:
541 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000542 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000543 }
544
Richard Smithc49bd112011-10-28 17:51:58 +0000545 llvm_unreachable("unknown APValue kind");
546}
547
548static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
549 EvalInfo &Info) {
550 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000551 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000552 if (!Evaluate(Val, Info, E))
553 return false;
554 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000555}
556
Mike Stump1eb44332009-09-09 15:08:12 +0000557static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000558 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000559 unsigned DestWidth = Ctx.getIntWidth(DestType);
560 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000561 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000563 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000564 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000565 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000566 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
567 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000568}
569
Mike Stump1eb44332009-09-09 15:08:12 +0000570static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000571 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000572 bool ignored;
573 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000574 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000575 APFloat::rmNearestTiesToEven, &ignored);
576 return Result;
577}
578
Mike Stump1eb44332009-09-09 15:08:12 +0000579static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000580 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000581 unsigned DestWidth = Ctx.getIntWidth(DestType);
582 APSInt Result = Value;
583 // Figure out if this is a truncate, extend or noop cast.
584 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000585 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000586 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000587 return Result;
588}
589
Mike Stump1eb44332009-09-09 15:08:12 +0000590static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000591 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000592
593 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
594 Result.convertFromAPInt(Value, Value.isSigned(),
595 APFloat::rmNearestTiesToEven);
596 return Result;
597}
598
Richard Smith180f4792011-11-10 06:34:14 +0000599/// If the given LValue refers to a base subobject of some object, find the most
600/// derived object and the corresponding complete record type. This is necessary
601/// in order to find the offset of a virtual base class.
602static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
603 const CXXRecordDecl *&MostDerivedType) {
604 SubobjectDesignator &D = Result.Designator;
605 if (D.Invalid || !Result.Base)
606 return false;
607
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000608 const Type *T = getType(Result.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000609
610 // Find path prefix which leads to the most-derived subobject.
611 unsigned MostDerivedPathLength = 0;
612 MostDerivedType = T->getAsCXXRecordDecl();
613 bool MostDerivedIsArrayElement = false;
614
615 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
616 bool IsArray = T && T->isArrayType();
617 if (IsArray)
618 T = T->getBaseElementTypeUnsafe();
619 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
620 T = FD->getType().getTypePtr();
621 else
622 T = 0;
623
624 if (T) {
625 MostDerivedType = T->getAsCXXRecordDecl();
626 MostDerivedPathLength = I + 1;
627 MostDerivedIsArrayElement = IsArray;
628 }
629 }
630
631 if (!MostDerivedType)
632 return false;
633
634 // (B*)&d + 1 has no most-derived object.
635 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
636 return false;
637
638 // Remove the trailing base class path entries and their offsets.
639 const RecordDecl *RD = MostDerivedType;
640 for (unsigned I = MostDerivedPathLength, N = D.Entries.size(); I != N; ++I) {
641 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
642 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
643 if (isVirtualBaseClass(D.Entries[I])) {
644 assert(I == MostDerivedPathLength &&
645 "virtual base class must be immediately after most-derived class");
646 Result.Offset -= Layout.getVBaseClassOffset(Base);
647 } else
648 Result.Offset -= Layout.getBaseClassOffset(Base);
649 RD = Base;
650 }
651 D.Entries.resize(MostDerivedPathLength);
652 D.ArrayElement = MostDerivedIsArrayElement;
653 return true;
654}
655
656static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
657 const CXXRecordDecl *Derived,
658 const CXXRecordDecl *Base,
659 const ASTRecordLayout *RL = 0) {
660 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
661 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
662 Obj.Designator.addDecl(Base, /*Virtual*/ false);
663}
664
665static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
666 const CXXRecordDecl *DerivedDecl,
667 const CXXBaseSpecifier *Base) {
668 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
669
670 if (!Base->isVirtual()) {
671 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
672 return true;
673 }
674
675 // Extract most-derived object and corresponding type.
676 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
677 return false;
678
679 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
680 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
681 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
682 return true;
683}
684
685/// Update LVal to refer to the given field, which must be a member of the type
686/// currently described by LVal.
687static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
688 const FieldDecl *FD,
689 const ASTRecordLayout *RL = 0) {
690 if (!RL)
691 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
692
693 unsigned I = FD->getFieldIndex();
694 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
695 LVal.Designator.addDecl(FD);
696}
697
698/// Get the size of the given type in char units.
699static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
700 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
701 // extension.
702 if (Type->isVoidType() || Type->isFunctionType()) {
703 Size = CharUnits::One();
704 return true;
705 }
706
707 if (!Type->isConstantSizeType()) {
708 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
709 return false;
710 }
711
712 Size = Info.Ctx.getTypeSizeInChars(Type);
713 return true;
714}
715
716/// Update a pointer value to model pointer arithmetic.
717/// \param Info - Information about the ongoing evaluation.
718/// \param LVal - The pointer value to be updated.
719/// \param EltTy - The pointee type represented by LVal.
720/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
721static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
722 QualType EltTy, int64_t Adjustment) {
723 CharUnits SizeOfPointee;
724 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
725 return false;
726
727 // Compute the new offset in the appropriate width.
728 LVal.Offset += Adjustment * SizeOfPointee;
729 LVal.Designator.adjustIndex(Adjustment);
730 return true;
731}
732
Richard Smith03f96112011-10-24 17:54:18 +0000733/// Try to evaluate the initializer for a variable declaration.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000734static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +0000735 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000736 // If this is a parameter to an active constexpr function call, perform
737 // argument substitution.
738 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith177dce72011-11-01 16:57:24 +0000739 if (!Frame || !Frame->Arguments)
740 return false;
741 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
742 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +0000743 }
Richard Smith03f96112011-10-24 17:54:18 +0000744
Richard Smith180f4792011-11-10 06:34:14 +0000745 // If we're currently evaluating the initializer of this declaration, use that
746 // in-flight value.
747 if (Info.EvaluatingDecl == VD) {
748 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
749 return !Result.isUninit();
750 }
751
Richard Smith65ac5982011-11-01 21:06:14 +0000752 // Never evaluate the initializer of a weak variable. We can't be sure that
753 // this is the definition which will be used.
754 if (IsWeakDecl(VD))
755 return false;
756
Richard Smith03f96112011-10-24 17:54:18 +0000757 const Expr *Init = VD->getAnyInitializer();
Richard Smithdb1822c2011-11-08 01:31:09 +0000758 if (!Init || Init->isValueDependent())
Richard Smith47a1eed2011-10-29 20:57:55 +0000759 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000760
Richard Smith47a1eed2011-10-29 20:57:55 +0000761 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +0000762 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000763 return !Result.isUninit();
764 }
Richard Smith03f96112011-10-24 17:54:18 +0000765
766 if (VD->isEvaluatingValue())
Richard Smith47a1eed2011-10-29 20:57:55 +0000767 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000768
769 VD->setEvaluatingValue();
770
Richard Smith47a1eed2011-10-29 20:57:55 +0000771 Expr::EvalStatus EStatus;
772 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +0000773 APValue EvalResult;
774 InitInfo.setEvaluatingDecl(VD, EvalResult);
775 LValue LVal;
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000776 LVal.set(VD);
Richard Smithc49bd112011-10-28 17:51:58 +0000777 // FIXME: The caller will need to know whether the value was a constant
778 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +0000779 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000780 // FIXME: If the evaluation failure was not permanent (for instance, if we
781 // hit a variable with no declaration yet, or a constexpr function with no
782 // definition yet), the standard is unclear as to how we should behave.
783 //
784 // Either the initializer should be evaluated when the variable is defined,
785 // or a failed evaluation of the initializer should be reattempted each time
786 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +0000787 VD->setEvaluatedValue(APValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000788 return false;
789 }
Richard Smith03f96112011-10-24 17:54:18 +0000790
Richard Smith69c2c502011-11-04 05:33:44 +0000791 VD->setEvaluatedValue(EvalResult);
792 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000793 return true;
Richard Smith03f96112011-10-24 17:54:18 +0000794}
795
Richard Smithc49bd112011-10-28 17:51:58 +0000796static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +0000797 Qualifiers Quals = T.getQualifiers();
798 return Quals.hasConst() && !Quals.hasVolatile();
799}
800
Richard Smith59efe262011-11-11 04:05:33 +0000801/// Get the base index of the given base class within an APValue representing
802/// the given derived class.
803static unsigned getBaseIndex(const CXXRecordDecl *Derived,
804 const CXXRecordDecl *Base) {
805 Base = Base->getCanonicalDecl();
806 unsigned Index = 0;
807 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
808 E = Derived->bases_end(); I != E; ++I, ++Index) {
809 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
810 return Index;
811 }
812
813 llvm_unreachable("base class missing from derived class's bases list");
814}
815
Richard Smithcc5d4f62011-11-07 09:22:26 +0000816/// Extract the designated sub-object of an rvalue.
817static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
818 const SubobjectDesignator &Sub, QualType SubType) {
819 if (Sub.Invalid || Sub.OnePastTheEnd)
820 return false;
Richard Smithf64699e2011-11-11 08:28:03 +0000821 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +0000822 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +0000823
824 assert(!Obj.isLValue() && "extracting subobject of lvalue");
825 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +0000826 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000827 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000828 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +0000829 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000830 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
831 if (!CAT)
832 return false;
833 uint64_t Index = Sub.Entries[I].ArrayIndex;
834 if (CAT->getSize().ule(Index))
835 return false;
836 if (O->getArrayInitializedElts() > Index)
837 O = &O->getArrayInitializedElt(Index);
838 else
839 O = &O->getArrayFiller();
840 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +0000841 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
842 // Next subobject is a class, struct or union field.
843 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
844 if (RD->isUnion()) {
845 const FieldDecl *UnionField = O->getUnionField();
846 if (!UnionField ||
847 UnionField->getCanonicalDecl() != Field->getCanonicalDecl())
848 return false;
849 O = &O->getUnionValue();
850 } else
851 O = &O->getStructField(Field->getFieldIndex());
852 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +0000853 } else {
Richard Smith180f4792011-11-10 06:34:14 +0000854 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +0000855 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
856 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
857 O = &O->getStructBase(getBaseIndex(Derived, Base));
858 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +0000859 }
Richard Smith180f4792011-11-10 06:34:14 +0000860
861 if (O->isUninit())
862 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +0000863 }
864
Richard Smithcc5d4f62011-11-07 09:22:26 +0000865 Obj = CCValue(*O, CCValue::GlobalValue());
866 return true;
867}
868
Richard Smith180f4792011-11-10 06:34:14 +0000869/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
870/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
871/// for looking up the glvalue referred to by an entity of reference type.
872///
873/// \param Info - Information about the ongoing evaluation.
874/// \param Type - The type we expect this conversion to produce.
875/// \param LVal - The glvalue on which we are attempting to perform this action.
876/// \param RVal - The produced value will be placed here.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000877static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
878 const LValue &LVal, CCValue &RVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000879 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +0000880 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +0000881
882 // FIXME: Indirection through a null pointer deserves a diagnostic.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000883 if (!LVal.Base)
Richard Smithc49bd112011-10-28 17:51:58 +0000884 return false;
885
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000886 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +0000887 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
888 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +0000889 // expressions are constant expressions too. Inside constexpr functions,
890 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +0000891 // In C, such things can also be folded, although they are not ICEs.
892 //
Richard Smithd0dccea2011-10-28 22:34:42 +0000893 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
894 // interpretation of C++11 suggests that volatile parameters are OK if
895 // they're never read (there's no prohibition against constructing volatile
896 // objects in constant expressions), but lvalue-to-rvalue conversions on
897 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +0000898 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithcd689922011-11-07 03:22:51 +0000899 if (!VD || VD->isInvalidDecl())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000900 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000901 QualType VT = VD->getType();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000902 if (!isa<ParmVarDecl>(VD)) {
903 if (!IsConstNonVolatile(VT))
904 return false;
Richard Smithcd689922011-11-07 03:22:51 +0000905 // FIXME: Allow folding of values of any literal type in all languages.
906 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
907 !VD->isConstexpr())
Richard Smith0a3bdb62011-11-04 02:25:55 +0000908 return false;
909 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000910 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +0000911 return false;
912
Richard Smith47a1eed2011-10-29 20:57:55 +0000913 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithcc5d4f62011-11-07 09:22:26 +0000914 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000915
916 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
917 // conversion. This happens when the declaration and the lvalue should be
918 // considered synonymous, for instance when initializing an array of char
919 // from a string literal. Continue as if the initializer lvalue was the
920 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +0000921 assert(RVal.getLValueOffset().isZero() &&
922 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000923 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +0000924 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +0000925 }
926
Richard Smith0a3bdb62011-11-04 02:25:55 +0000927 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
928 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
929 const SubobjectDesignator &Designator = LVal.Designator;
930 if (Designator.Invalid || Designator.Entries.size() != 1)
931 return false;
932
933 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +0000934 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000935 if (Index > S->getLength())
936 return false;
937 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
938 Type->isUnsignedIntegerType());
939 if (Index < S->getLength())
940 Value = S->getCodeUnit(Index);
941 RVal = CCValue(Value);
942 return true;
943 }
944
Richard Smithcc5d4f62011-11-07 09:22:26 +0000945 if (Frame) {
946 // If this is a temporary expression with a nontrivial initializer, grab the
947 // value from the relevant stack frame.
948 RVal = Frame->Temporaries[Base];
949 } else if (const CompoundLiteralExpr *CLE
950 = dyn_cast<CompoundLiteralExpr>(Base)) {
951 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
952 // initializer until now for such expressions. Such an expression can't be
953 // an ICE in C, so this only matters for fold.
954 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
955 if (!Evaluate(RVal, Info, CLE->getInitializer()))
956 return false;
957 } else
Richard Smith0a3bdb62011-11-04 02:25:55 +0000958 return false;
959
Richard Smithcc5d4f62011-11-07 09:22:26 +0000960 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +0000961}
962
Richard Smith59efe262011-11-11 04:05:33 +0000963/// Build an lvalue for the object argument of a member function call.
964static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
965 LValue &This) {
966 if (Object->getType()->isPointerType())
967 return EvaluatePointer(Object, This, Info);
968
969 if (Object->isGLValue())
970 return EvaluateLValue(Object, This, Info);
971
972 // Implicitly promote a prvalue *this object to a glvalue.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000973 This.set(Object, Info.CurrentCall);
Richard Smith59efe262011-11-11 04:05:33 +0000974 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[Object], Info,
975 This, Object);
976}
977
Mike Stumpc4c90452009-10-27 22:09:17 +0000978namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +0000979enum EvalStmtResult {
980 /// Evaluation failed.
981 ESR_Failed,
982 /// Hit a 'return' statement.
983 ESR_Returned,
984 /// Evaluation succeeded.
985 ESR_Succeeded
986};
987}
988
989// Evaluate a statement.
Richard Smith47a1eed2011-10-29 20:57:55 +0000990static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +0000991 const Stmt *S) {
992 switch (S->getStmtClass()) {
993 default:
994 return ESR_Failed;
995
996 case Stmt::NullStmtClass:
997 case Stmt::DeclStmtClass:
998 return ESR_Succeeded;
999
1000 case Stmt::ReturnStmtClass:
1001 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1002 return ESR_Returned;
1003 return ESR_Failed;
1004
1005 case Stmt::CompoundStmtClass: {
1006 const CompoundStmt *CS = cast<CompoundStmt>(S);
1007 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1008 BE = CS->body_end(); BI != BE; ++BI) {
1009 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1010 if (ESR != ESR_Succeeded)
1011 return ESR;
1012 }
1013 return ESR_Succeeded;
1014 }
1015 }
1016}
1017
Richard Smith180f4792011-11-10 06:34:14 +00001018namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001019typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001020}
1021
1022/// EvaluateArgs - Evaluate the arguments to a function call.
1023static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1024 EvalInfo &Info) {
1025 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1026 I != E; ++I)
1027 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1028 return false;
1029 return true;
1030}
1031
Richard Smithd0dccea2011-10-28 22:34:42 +00001032/// Evaluate a function call.
Richard Smith59efe262011-11-11 04:05:33 +00001033static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args,
1034 const Stmt *Body, EvalInfo &Info,
1035 CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001036 // FIXME: Implement a proper call limit, along with a command-line flag.
1037 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1038 return false;
1039
Richard Smith180f4792011-11-10 06:34:14 +00001040 ArgVector ArgValues(Args.size());
1041 if (!EvaluateArgs(Args, ArgValues, Info))
1042 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001043
Richard Smith180f4792011-11-10 06:34:14 +00001044 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001045 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1046}
1047
Richard Smith180f4792011-11-10 06:34:14 +00001048/// Evaluate a constructor call.
Richard Smith59efe262011-11-11 04:05:33 +00001049static bool HandleConstructorCall(const LValue &This,
1050 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001051 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001052 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001053 APValue &Result) {
1054 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1055 return false;
1056
1057 ArgVector ArgValues(Args.size());
1058 if (!EvaluateArgs(Args, ArgValues, Info))
1059 return false;
1060
1061 CallStackFrame Frame(Info, &This, ArgValues.data());
1062
1063 // If it's a delegating constructor, just delegate.
1064 if (Definition->isDelegatingConstructor()) {
1065 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1066 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1067 }
1068
1069 // Reserve space for the struct members.
1070 const CXXRecordDecl *RD = Definition->getParent();
1071 if (!RD->isUnion())
1072 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1073 std::distance(RD->field_begin(), RD->field_end()));
1074
1075 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1076
1077 unsigned BasesSeen = 0;
1078#ifndef NDEBUG
1079 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1080#endif
1081 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1082 E = Definition->init_end(); I != E; ++I) {
1083 if ((*I)->isBaseInitializer()) {
1084 QualType BaseType((*I)->getBaseClass(), 0);
1085#ifndef NDEBUG
1086 // Non-virtual base classes are initialized in the order in the class
1087 // definition. We cannot have a virtual base class for a literal type.
1088 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1089 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1090 "base class initializers not in expected order");
1091 ++BaseIt;
1092#endif
1093 LValue Subobject = This;
1094 HandleLValueDirectBase(Info, Subobject, RD,
1095 BaseType->getAsCXXRecordDecl(), &Layout);
1096 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1097 Subobject, (*I)->getInit()))
1098 return false;
1099 } else if (FieldDecl *FD = (*I)->getMember()) {
1100 LValue Subobject = This;
1101 HandleLValueMember(Info, Subobject, FD, &Layout);
1102 if (RD->isUnion()) {
1103 Result = APValue(FD);
1104 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1105 Subobject, (*I)->getInit()))
1106 return false;
1107 } else if (!EvaluateConstantExpression(
1108 Result.getStructField(FD->getFieldIndex()),
1109 Info, Subobject, (*I)->getInit()))
1110 return false;
1111 } else {
1112 // FIXME: handle indirect field initializers
1113 return false;
1114 }
1115 }
1116
1117 return true;
1118}
1119
Richard Smithd0dccea2011-10-28 22:34:42 +00001120namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001121class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001122 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001123 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001124public:
1125
Richard Smith1e12c592011-10-16 21:26:27 +00001126 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001127
1128 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001129 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001130 return true;
1131 }
1132
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001133 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1134 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001135 return Visit(E->getResultExpr());
1136 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001137 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001138 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001139 return true;
1140 return false;
1141 }
John McCallf85e1932011-06-15 23:02:42 +00001142 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001143 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001144 return true;
1145 return false;
1146 }
1147 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001148 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001149 return true;
1150 return false;
1151 }
1152
Mike Stumpc4c90452009-10-27 22:09:17 +00001153 // We don't want to evaluate BlockExprs multiple times, as they generate
1154 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001155 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1156 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1157 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001158 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001159 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1160 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1161 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1162 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1163 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1164 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001165 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001166 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001167 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001168 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001169 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001170 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1171 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1172 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1173 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001174 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001175 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1176 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1177 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1178 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1179 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001180 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001181 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001182 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001183 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001184 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001185
1186 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001187 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001188 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1189 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001190 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001191 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001192 return false;
1193 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001194
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001195 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001196};
1197
John McCall56ca35d2011-02-17 10:25:35 +00001198class OpaqueValueEvaluation {
1199 EvalInfo &info;
1200 OpaqueValueExpr *opaqueValue;
1201
1202public:
1203 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1204 Expr *value)
1205 : info(info), opaqueValue(opaqueValue) {
1206
1207 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001208 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001209 this->opaqueValue = 0;
1210 return;
1211 }
John McCall56ca35d2011-02-17 10:25:35 +00001212 }
1213
1214 bool hasError() const { return opaqueValue == 0; }
1215
1216 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001217 // FIXME: This will not work for recursive constexpr functions using opaque
1218 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001219 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1220 }
1221};
1222
Mike Stumpc4c90452009-10-27 22:09:17 +00001223} // end anonymous namespace
1224
Eli Friedman4efaa272008-11-12 09:44:48 +00001225//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001226// Generic Evaluation
1227//===----------------------------------------------------------------------===//
1228namespace {
1229
1230template <class Derived, typename RetTy=void>
1231class ExprEvaluatorBase
1232 : public ConstStmtVisitor<Derived, RetTy> {
1233private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001234 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001235 return static_cast<Derived*>(this)->Success(V, E);
1236 }
1237 RetTy DerivedError(const Expr *E) {
1238 return static_cast<Derived*>(this)->Error(E);
1239 }
Richard Smithf10d9172011-10-11 21:43:33 +00001240 RetTy DerivedValueInitialization(const Expr *E) {
1241 return static_cast<Derived*>(this)->ValueInitialization(E);
1242 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001243
1244protected:
1245 EvalInfo &Info;
1246 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1247 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1248
Richard Smithf10d9172011-10-11 21:43:33 +00001249 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1250
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001251public:
1252 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1253
1254 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001255 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001256 }
1257 RetTy VisitExpr(const Expr *E) {
1258 return DerivedError(E);
1259 }
1260
1261 RetTy VisitParenExpr(const ParenExpr *E)
1262 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1263 RetTy VisitUnaryExtension(const UnaryOperator *E)
1264 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1265 RetTy VisitUnaryPlus(const UnaryOperator *E)
1266 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1267 RetTy VisitChooseExpr(const ChooseExpr *E)
1268 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1269 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1270 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001271 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1272 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001273 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1274 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001275
1276 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1277 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1278 if (opaque.hasError())
1279 return DerivedError(E);
1280
1281 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001282 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001283 return DerivedError(E);
1284
1285 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1286 }
1287
1288 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1289 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001290 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001291 return DerivedError(E);
1292
Richard Smithc49bd112011-10-28 17:51:58 +00001293 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001294 return StmtVisitorTy::Visit(EvalExpr);
1295 }
1296
1297 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001298 const CCValue *Value = Info.getOpaqueValue(E);
1299 if (!Value)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001300 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
1301 : DerivedError(E));
Richard Smith47a1eed2011-10-29 20:57:55 +00001302 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001303 }
Richard Smithf10d9172011-10-11 21:43:33 +00001304
Richard Smithd0dccea2011-10-28 22:34:42 +00001305 RetTy VisitCallExpr(const CallExpr *E) {
1306 const Expr *Callee = E->getCallee();
1307 QualType CalleeType = Callee->getType();
1308
Richard Smithd0dccea2011-10-28 22:34:42 +00001309 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001310 LValue *This = 0, ThisVal;
1311 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001312
Richard Smith59efe262011-11-11 04:05:33 +00001313 // Extract function decl and 'this' pointer from the callee.
1314 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
1315 // Explicit bound member calls, such as x.f() or p->g();
1316 // FIXME: Handle a BinaryOperator callee ('.*' or '->*').
1317 const MemberExpr *ME = dyn_cast<MemberExpr>(Callee->IgnoreParens());
1318 if (!ME)
1319 return DerivedError(Callee);
1320 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
1321 return DerivedError(ME->getBase());
1322 This = &ThisVal;
1323 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1324 if (!FD)
1325 return DerivedError(ME);
1326 } else if (CalleeType->isFunctionPointerType()) {
1327 CCValue Call;
1328 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001329 !Call.getLValueOffset().isZero())
Richard Smith59efe262011-11-11 04:05:33 +00001330 return DerivedError(Callee);
1331
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001332 FD = dyn_cast_or_null<FunctionDecl>(
1333 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001334 if (!FD)
1335 return DerivedError(Callee);
1336
1337 // Overloaded operator calls to member functions are represented as normal
1338 // calls with '*this' as the first argument.
1339 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1340 if (MD && !MD->isStatic()) {
1341 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1342 return false;
1343 This = &ThisVal;
1344 Args = Args.slice(1);
1345 }
1346
1347 // Don't call function pointers which have been cast to some other type.
1348 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1349 return DerivedError(E);
1350 } else
Devang Patel6142ca72011-11-10 17:47:39 +00001351 return DerivedError(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001352
1353 const FunctionDecl *Definition;
1354 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001355 CCValue CCResult;
1356 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001357
1358 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smith59efe262011-11-11 04:05:33 +00001359 HandleFunctionCall(This, Args, Body, Info, CCResult) &&
Richard Smith69c2c502011-11-04 05:33:44 +00001360 CheckConstantExpression(CCResult, Result))
1361 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001362
1363 return DerivedError(E);
1364 }
1365
Richard Smithc49bd112011-10-28 17:51:58 +00001366 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1367 return StmtVisitorTy::Visit(E->getInitializer());
1368 }
Richard Smithf10d9172011-10-11 21:43:33 +00001369 RetTy VisitInitListExpr(const InitListExpr *E) {
1370 if (Info.getLangOpts().CPlusPlus0x) {
1371 if (E->getNumInits() == 0)
1372 return DerivedValueInitialization(E);
1373 if (E->getNumInits() == 1)
1374 return StmtVisitorTy::Visit(E->getInit(0));
1375 }
1376 return DerivedError(E);
1377 }
1378 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1379 return DerivedValueInitialization(E);
1380 }
1381 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1382 return DerivedValueInitialization(E);
1383 }
1384
Richard Smith180f4792011-11-10 06:34:14 +00001385 /// A member expression where the object is a prvalue is itself a prvalue.
1386 RetTy VisitMemberExpr(const MemberExpr *E) {
1387 assert(!E->isArrow() && "missing call to bound member function?");
1388
1389 CCValue Val;
1390 if (!Evaluate(Val, Info, E->getBase()))
1391 return false;
1392
1393 QualType BaseTy = E->getBase()->getType();
1394
1395 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1396 if (!FD) return false;
1397 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1398 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1399 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1400
1401 SubobjectDesignator Designator;
1402 Designator.addDecl(FD);
1403
1404 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1405 DerivedSuccess(Val, E);
1406 }
1407
Richard Smithc49bd112011-10-28 17:51:58 +00001408 RetTy VisitCastExpr(const CastExpr *E) {
1409 switch (E->getCastKind()) {
1410 default:
1411 break;
1412
1413 case CK_NoOp:
1414 return StmtVisitorTy::Visit(E->getSubExpr());
1415
1416 case CK_LValueToRValue: {
1417 LValue LVal;
1418 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001419 CCValue RVal;
Richard Smithc49bd112011-10-28 17:51:58 +00001420 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1421 return DerivedSuccess(RVal, E);
1422 }
1423 break;
1424 }
1425 }
1426
1427 return DerivedError(E);
1428 }
1429
Richard Smith8327fad2011-10-24 18:44:57 +00001430 /// Visit a value which is evaluated, but whose value is ignored.
1431 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001432 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00001433 if (!Evaluate(Scratch, Info, E))
1434 Info.EvalStatus.HasSideEffects = true;
1435 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001436};
1437
1438}
1439
1440//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00001441// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00001442//
1443// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1444// function designators (in C), decl references to void objects (in C), and
1445// temporaries (if building with -Wno-address-of-temporary).
1446//
1447// LValue evaluation produces values comprising a base expression of one of the
1448// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001449// - Declarations
1450// * VarDecl
1451// * FunctionDecl
1452// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00001453// * CompoundLiteralExpr in C
1454// * StringLiteral
1455// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00001456// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00001457// * ObjCEncodeExpr
1458// * AddrLabelExpr
1459// * BlockExpr
1460// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001461// - Locals and temporaries
1462// * Any Expr, with a Frame indicating the function in which the temporary was
1463// evaluated.
1464// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00001465//===----------------------------------------------------------------------===//
1466namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001467class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001468 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001469 LValue &Result;
Chandler Carruth01248392011-08-22 17:24:56 +00001470 const Decl *PrevDecl;
John McCallefdb83e2010-05-07 21:00:08 +00001471
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001472 bool Success(APValue::LValueBase B) {
1473 Result.set(B);
John McCallefdb83e2010-05-07 21:00:08 +00001474 return true;
1475 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001476public:
Mike Stump1eb44332009-09-09 15:08:12 +00001477
John McCallefdb83e2010-05-07 21:00:08 +00001478 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth01248392011-08-22 17:24:56 +00001479 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman4efaa272008-11-12 09:44:48 +00001480
Richard Smith47a1eed2011-10-29 20:57:55 +00001481 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001482 Result.setFrom(V);
1483 return true;
1484 }
1485 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001486 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001487 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001488
Richard Smithc49bd112011-10-28 17:51:58 +00001489 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1490
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001491 bool VisitDeclRefExpr(const DeclRefExpr *E);
1492 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00001493 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001494 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1495 bool VisitMemberExpr(const MemberExpr *E);
1496 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1497 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1498 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1499 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001500
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001501 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00001502 switch (E->getCastKind()) {
1503 default:
Richard Smithc49bd112011-10-28 17:51:58 +00001504 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001505
Eli Friedmandb924222011-10-11 00:13:24 +00001506 case CK_LValueBitCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001507 if (!Visit(E->getSubExpr()))
1508 return false;
1509 Result.Designator.setInvalid();
1510 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00001511
Richard Smith180f4792011-11-10 06:34:14 +00001512 case CK_DerivedToBase:
1513 case CK_UncheckedDerivedToBase: {
1514 if (!Visit(E->getSubExpr()))
1515 return false;
1516
1517 // Now figure out the necessary offset to add to the base LV to get from
1518 // the derived class to the base class.
1519 QualType Type = E->getSubExpr()->getType();
1520
1521 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1522 PathE = E->path_end(); PathI != PathE; ++PathI) {
1523 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
1524 return false;
1525 Type = (*PathI)->getType();
1526 }
1527
1528 return true;
1529 }
Anders Carlsson26bc2202009-10-03 16:30:22 +00001530 }
1531 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00001532
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001533 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001534
Eli Friedman4efaa272008-11-12 09:44:48 +00001535};
1536} // end anonymous namespace
1537
Richard Smithc49bd112011-10-28 17:51:58 +00001538/// Evaluate an expression as an lvalue. This can be legitimately called on
1539/// expressions which are not glvalues, in a few cases:
1540/// * function designators in C,
1541/// * "extern void" objects,
1542/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00001543static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001544 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1545 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1546 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001547 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001548}
1549
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001550bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001551 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
1552 return Success(FD);
1553 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00001554 return VisitVarDecl(E, VD);
1555 return Error(E);
1556}
Richard Smith436c8892011-10-24 23:14:33 +00001557
Richard Smithc49bd112011-10-28 17:51:58 +00001558bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00001559 if (!VD->getType()->isReferenceType()) {
1560 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001561 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00001562 return true;
1563 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001564 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00001565 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00001566
Richard Smith47a1eed2011-10-29 20:57:55 +00001567 CCValue V;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001568 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith47a1eed2011-10-29 20:57:55 +00001569 return Success(V, E);
Richard Smithc49bd112011-10-28 17:51:58 +00001570
1571 return Error(E);
Anders Carlsson35873c42008-11-24 04:41:22 +00001572}
1573
Richard Smithbd552ef2011-10-31 05:52:43 +00001574bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1575 const MaterializeTemporaryExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001576 Result.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00001577 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1578 Result, E->GetTemporaryExpr());
Richard Smithbd552ef2011-10-31 05:52:43 +00001579}
1580
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001581bool
1582LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001583 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1584 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1585 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00001586 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001587}
1588
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001589bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001590 // Handle static data members.
1591 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1592 VisitIgnoredValue(E->getBase());
1593 return VisitVarDecl(E, VD);
1594 }
1595
Richard Smithd0dccea2011-10-28 22:34:42 +00001596 // Handle static member functions.
1597 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1598 if (MD->isStatic()) {
1599 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001600 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00001601 }
1602 }
1603
Richard Smith180f4792011-11-10 06:34:14 +00001604 // Handle non-static data members.
1605 QualType BaseTy;
Eli Friedman4efaa272008-11-12 09:44:48 +00001606 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +00001607 if (!EvaluatePointer(E->getBase(), Result, Info))
1608 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001609 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +00001610 } else {
John McCallefdb83e2010-05-07 21:00:08 +00001611 if (!Visit(E->getBase()))
1612 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001613 BaseTy = E->getBase()->getType();
Eli Friedman4efaa272008-11-12 09:44:48 +00001614 }
1615
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001616 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smith180f4792011-11-10 06:34:14 +00001617 if (!FD) return false;
1618 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1619 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1620 (void)BaseTy;
Eli Friedman2be58612009-05-30 21:09:44 +00001621
Richard Smith180f4792011-11-10 06:34:14 +00001622 HandleLValueMember(Info, Result, FD);
Eli Friedman2be58612009-05-30 21:09:44 +00001623
Richard Smith180f4792011-11-10 06:34:14 +00001624 if (FD->getType()->isReferenceType()) {
1625 CCValue RefValue;
1626 if (!HandleLValueToRValueConversion(Info, FD->getType(), Result, RefValue))
1627 return false;
1628 return Success(RefValue, E);
1629 }
John McCallefdb83e2010-05-07 21:00:08 +00001630 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +00001631}
1632
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001633bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001634 // FIXME: Deal with vectors as array subscript bases.
1635 if (E->getBase()->getType()->isVectorType())
1636 return false;
1637
Anders Carlsson3068d112008-11-16 19:01:22 +00001638 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001639 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Anders Carlsson3068d112008-11-16 19:01:22 +00001641 APSInt Index;
1642 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001643 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001644 int64_t IndexValue
1645 = Index.isSigned() ? Index.getSExtValue()
1646 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00001647
Richard Smith180f4792011-11-10 06:34:14 +00001648 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00001649}
Eli Friedman4efaa272008-11-12 09:44:48 +00001650
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001651bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00001652 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00001653}
1654
Eli Friedman4efaa272008-11-12 09:44:48 +00001655//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001656// Pointer Evaluation
1657//===----------------------------------------------------------------------===//
1658
Anders Carlssonc754aa62008-07-08 05:13:58 +00001659namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001660class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001661 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00001662 LValue &Result;
1663
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001664 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001665 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00001666 return true;
1667 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001668public:
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John McCallefdb83e2010-05-07 21:00:08 +00001670 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001671 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001672
Richard Smith47a1eed2011-10-29 20:57:55 +00001673 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001674 Result.setFrom(V);
1675 return true;
1676 }
1677 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +00001678 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001679 }
Richard Smithf10d9172011-10-11 21:43:33 +00001680 bool ValueInitialization(const Expr *E) {
1681 return Success((Expr*)0);
1682 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00001683
John McCallefdb83e2010-05-07 21:00:08 +00001684 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001685 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00001686 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001687 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00001688 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001689 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00001690 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001691 bool VisitCallExpr(const CallExpr *E);
1692 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00001693 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00001694 return Success(E);
1695 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +00001696 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001697 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smithf10d9172011-10-11 21:43:33 +00001698 { return ValueInitialization(E); }
Richard Smith180f4792011-11-10 06:34:14 +00001699 bool VisitCXXThisExpr(const CXXThisExpr *E) {
1700 if (!Info.CurrentCall->This)
1701 return false;
1702 Result = *Info.CurrentCall->This;
1703 return true;
1704 }
John McCall56ca35d2011-02-17 10:25:35 +00001705
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001706 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00001707};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001708} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001709
John McCallefdb83e2010-05-07 21:00:08 +00001710static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001711 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001712 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001713}
1714
John McCallefdb83e2010-05-07 21:00:08 +00001715bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001716 if (E->getOpcode() != BO_Add &&
1717 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +00001718 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001719
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001720 const Expr *PExp = E->getLHS();
1721 const Expr *IExp = E->getRHS();
1722 if (IExp->getType()->isPointerType())
1723 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00001724
John McCallefdb83e2010-05-07 21:00:08 +00001725 if (!EvaluatePointer(PExp, Result, Info))
1726 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001727
John McCallefdb83e2010-05-07 21:00:08 +00001728 llvm::APSInt Offset;
1729 if (!EvaluateInteger(IExp, Offset, Info))
1730 return false;
1731 int64_t AdditionalOffset
1732 = Offset.isSigned() ? Offset.getSExtValue()
1733 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00001734 if (E->getOpcode() == BO_Sub)
1735 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001736
Richard Smith180f4792011-11-10 06:34:14 +00001737 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
1738 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001739}
Eli Friedman4efaa272008-11-12 09:44:48 +00001740
John McCallefdb83e2010-05-07 21:00:08 +00001741bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1742 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001743}
Mike Stump1eb44332009-09-09 15:08:12 +00001744
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001745bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1746 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001747
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001748 switch (E->getCastKind()) {
1749 default:
1750 break;
1751
John McCall2de56d12010-08-25 11:45:40 +00001752 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001753 case CK_CPointerToObjCPointerCast:
1754 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001755 case CK_AnyPointerToBlockPointerCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001756 if (!Visit(SubExpr))
1757 return false;
1758 Result.Designator.setInvalid();
1759 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001760
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001761 case CK_DerivedToBase:
1762 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001763 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001764 return false;
1765
Richard Smith180f4792011-11-10 06:34:14 +00001766 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001767 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00001768 QualType Type =
1769 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001770
Richard Smith180f4792011-11-10 06:34:14 +00001771 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001772 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00001773 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001774 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001775 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001776 }
1777
Anders Carlsson5c5a7642010-10-31 20:41:46 +00001778 return true;
1779 }
1780
Richard Smith47a1eed2011-10-29 20:57:55 +00001781 case CK_NullToPointer:
1782 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00001783
John McCall2de56d12010-08-25 11:45:40 +00001784 case CK_IntegralToPointer: {
Richard Smith47a1eed2011-10-29 20:57:55 +00001785 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00001786 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00001787 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001788
John McCallefdb83e2010-05-07 21:00:08 +00001789 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001790 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1791 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001792 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00001793 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00001794 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00001795 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00001796 return true;
1797 } else {
1798 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00001799 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00001800 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001801 }
1802 }
John McCall2de56d12010-08-25 11:45:40 +00001803 case CK_ArrayToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001804 // FIXME: Support array-to-pointer decay on array rvalues.
1805 if (!SubExpr->isGLValue())
1806 return Error(E);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001807 if (!EvaluateLValue(SubExpr, Result, Info))
1808 return false;
1809 // The result is a pointer to the first element of the array.
1810 Result.Designator.addIndex(0);
1811 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00001812
John McCall2de56d12010-08-25 11:45:40 +00001813 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00001814 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00001815 }
1816
Richard Smithc49bd112011-10-28 17:51:58 +00001817 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001818}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001819
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001820bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00001821 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00001822 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00001823
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001824 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001825}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001826
1827//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00001828// Record Evaluation
1829//===----------------------------------------------------------------------===//
1830
1831namespace {
1832 class RecordExprEvaluator
1833 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
1834 const LValue &This;
1835 APValue &Result;
1836 public:
1837
1838 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
1839 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
1840
1841 bool Success(const CCValue &V, const Expr *E) {
1842 return CheckConstantExpression(V, Result);
1843 }
1844 bool Error(const Expr *E) { return false; }
1845
Richard Smith59efe262011-11-11 04:05:33 +00001846 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00001847 bool VisitInitListExpr(const InitListExpr *E);
1848 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
1849 };
1850}
1851
Richard Smith59efe262011-11-11 04:05:33 +00001852bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
1853 switch (E->getCastKind()) {
1854 default:
1855 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1856
1857 case CK_ConstructorConversion:
1858 return Visit(E->getSubExpr());
1859
1860 case CK_DerivedToBase:
1861 case CK_UncheckedDerivedToBase: {
1862 CCValue DerivedObject;
1863 if (!Evaluate(DerivedObject, Info, E->getSubExpr()) ||
1864 !DerivedObject.isStruct())
1865 return false;
1866
1867 // Derived-to-base rvalue conversion: just slice off the derived part.
1868 APValue *Value = &DerivedObject;
1869 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
1870 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1871 PathE = E->path_end(); PathI != PathE; ++PathI) {
1872 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
1873 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
1874 Value = &Value->getStructBase(getBaseIndex(RD, Base));
1875 RD = Base;
1876 }
1877 Result = *Value;
1878 return true;
1879 }
1880 }
1881}
1882
Richard Smith180f4792011-11-10 06:34:14 +00001883bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1884 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
1885 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1886
1887 if (RD->isUnion()) {
1888 Result = APValue(E->getInitializedFieldInUnion());
1889 if (!E->getNumInits())
1890 return true;
1891 LValue Subobject = This;
1892 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
1893 &Layout);
1894 return EvaluateConstantExpression(Result.getUnionValue(), Info,
1895 Subobject, E->getInit(0));
1896 }
1897
1898 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
1899 "initializer list for class with base classes");
1900 Result = APValue(APValue::UninitStruct(), 0,
1901 std::distance(RD->field_begin(), RD->field_end()));
1902 unsigned ElementNo = 0;
1903 for (RecordDecl::field_iterator Field = RD->field_begin(),
1904 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
1905 // Anonymous bit-fields are not considered members of the class for
1906 // purposes of aggregate initialization.
1907 if (Field->isUnnamedBitfield())
1908 continue;
1909
1910 LValue Subobject = This;
1911 HandleLValueMember(Info, Subobject, *Field, &Layout);
1912
1913 if (ElementNo < E->getNumInits()) {
1914 if (!EvaluateConstantExpression(
1915 Result.getStructField((*Field)->getFieldIndex()),
1916 Info, Subobject, E->getInit(ElementNo++)))
1917 return false;
1918 } else {
1919 // Perform an implicit value-initialization for members beyond the end of
1920 // the initializer list.
1921 ImplicitValueInitExpr VIE(Field->getType());
1922 if (!EvaluateConstantExpression(
1923 Result.getStructField((*Field)->getFieldIndex()),
1924 Info, Subobject, &VIE))
1925 return false;
1926 }
1927 }
1928
1929 return true;
1930}
1931
1932bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1933 const CXXConstructorDecl *FD = E->getConstructor();
1934 const FunctionDecl *Definition = 0;
1935 FD->getBody(Definition);
1936
1937 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
1938 return false;
1939
1940 // FIXME: Elide the copy/move construction wherever we can.
1941 if (E->isElidable())
1942 if (const MaterializeTemporaryExpr *ME
1943 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
1944 return Visit(ME->GetTemporaryExpr());
1945
1946 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith59efe262011-11-11 04:05:33 +00001947 return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition),
1948 Info, Result);
Richard Smith180f4792011-11-10 06:34:14 +00001949}
1950
1951static bool EvaluateRecord(const Expr *E, const LValue &This,
1952 APValue &Result, EvalInfo &Info) {
1953 assert(E->isRValue() && E->getType()->isRecordType() &&
1954 E->getType()->isLiteralType() &&
1955 "can't evaluate expression as a record rvalue");
1956 return RecordExprEvaluator(Info, This, Result).Visit(E);
1957}
1958
1959//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00001960// Vector Evaluation
1961//===----------------------------------------------------------------------===//
1962
1963namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001964 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00001965 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1966 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00001967 public:
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Richard Smith07fc6572011-10-22 21:10:00 +00001969 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1970 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Richard Smith07fc6572011-10-22 21:10:00 +00001972 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1973 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1974 // FIXME: remove this APValue copy.
1975 Result = APValue(V.data(), V.size());
1976 return true;
1977 }
Richard Smith69c2c502011-11-04 05:33:44 +00001978 bool Success(const CCValue &V, const Expr *E) {
1979 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00001980 Result = V;
1981 return true;
1982 }
1983 bool Error(const Expr *E) { return false; }
1984 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00001985
Richard Smith07fc6572011-10-22 21:10:00 +00001986 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00001987 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00001988 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00001989 bool VisitInitListExpr(const InitListExpr *E);
1990 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00001991 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00001992 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00001993 // shufflevector, ExtVectorElementExpr
1994 // (Note that these require implementing conversions
1995 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00001996 };
1997} // end anonymous namespace
1998
1999static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002000 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002001 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002002}
2003
Richard Smith07fc6572011-10-22 21:10:00 +00002004bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2005 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002006 QualType EltTy = VTy->getElementType();
2007 unsigned NElts = VTy->getNumElements();
2008 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Nate Begeman59b5da62009-01-18 03:20:47 +00002010 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002011 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002012
Eli Friedman46a52322011-03-25 00:43:55 +00002013 switch (E->getCastKind()) {
2014 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002015 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002016 if (SETy->isIntegerType()) {
2017 APSInt IntResult;
2018 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002019 return Error(E);
2020 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002021 } else if (SETy->isRealFloatingType()) {
2022 APFloat F(0.0);
2023 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002024 return Error(E);
2025 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002026 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002027 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002028 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002029
2030 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002031 SmallVector<APValue, 4> Elts(NElts, Val);
2032 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002033 }
Eli Friedman46a52322011-03-25 00:43:55 +00002034 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +00002035 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +00002036 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002037 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002038
Eli Friedman46a52322011-03-25 00:43:55 +00002039 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +00002040 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002041
Eli Friedman46a52322011-03-25 00:43:55 +00002042 APSInt Init;
2043 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002044 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002045
Eli Friedman46a52322011-03-25 00:43:55 +00002046 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
2047 "Vectors must be composed of ints or floats");
2048
Chris Lattner5f9e2722011-07-23 10:55:15 +00002049 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +00002050 for (unsigned i = 0; i != NElts; ++i) {
2051 APSInt Tmp = Init.extOrTrunc(EltWidth);
2052
2053 if (EltTy->isIntegerType())
2054 Elts.push_back(APValue(Tmp));
2055 else
2056 Elts.push_back(APValue(APFloat(Tmp)));
2057
2058 Init >>= EltWidth;
2059 }
Richard Smith07fc6572011-10-22 21:10:00 +00002060 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002061 }
Eli Friedman46a52322011-03-25 00:43:55 +00002062 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002063 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002064 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002065}
2066
Richard Smith07fc6572011-10-22 21:10:00 +00002067bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002068VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002069 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002070 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002071 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002072
Nate Begeman59b5da62009-01-18 03:20:47 +00002073 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002074 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002075
John McCalla7d6c222010-06-11 17:54:15 +00002076 // If a vector is initialized with a single element, that value
2077 // becomes every element of the vector, not just the first.
2078 // This is the behavior described in the IBM AltiVec documentation.
2079 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002080
2081 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002082 // vector (OpenCL 6.1.6).
2083 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002084 return Visit(E->getInit(0));
2085
John McCalla7d6c222010-06-11 17:54:15 +00002086 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002087 if (EltTy->isIntegerType()) {
2088 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002089 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002090 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002091 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002092 } else {
2093 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002094 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002095 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002096 InitValue = APValue(f);
2097 }
2098 for (unsigned i = 0; i < NumElements; i++) {
2099 Elements.push_back(InitValue);
2100 }
2101 } else {
2102 for (unsigned i = 0; i < NumElements; i++) {
2103 if (EltTy->isIntegerType()) {
2104 llvm::APSInt sInt(32);
2105 if (i < NumInits) {
2106 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002107 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002108 } else {
2109 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2110 }
2111 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002112 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002113 llvm::APFloat f(0.0);
2114 if (i < NumInits) {
2115 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002116 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002117 } else {
2118 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2119 }
2120 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002121 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002122 }
2123 }
Richard Smith07fc6572011-10-22 21:10:00 +00002124 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002125}
2126
Richard Smith07fc6572011-10-22 21:10:00 +00002127bool
2128VectorExprEvaluator::ValueInitialization(const Expr *E) {
2129 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002130 QualType EltTy = VT->getElementType();
2131 APValue ZeroElement;
2132 if (EltTy->isIntegerType())
2133 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2134 else
2135 ZeroElement =
2136 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2137
Chris Lattner5f9e2722011-07-23 10:55:15 +00002138 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002139 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002140}
2141
Richard Smith07fc6572011-10-22 21:10:00 +00002142bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002143 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002144 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002145}
2146
Nate Begeman59b5da62009-01-18 03:20:47 +00002147//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002148// Array Evaluation
2149//===----------------------------------------------------------------------===//
2150
2151namespace {
2152 class ArrayExprEvaluator
2153 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002154 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002155 APValue &Result;
2156 public:
2157
Richard Smith180f4792011-11-10 06:34:14 +00002158 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2159 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002160
2161 bool Success(const APValue &V, const Expr *E) {
2162 assert(V.isArray() && "Expected array type");
2163 Result = V;
2164 return true;
2165 }
2166 bool Error(const Expr *E) { return false; }
2167
Richard Smith180f4792011-11-10 06:34:14 +00002168 bool ValueInitialization(const Expr *E) {
2169 const ConstantArrayType *CAT =
2170 Info.Ctx.getAsConstantArrayType(E->getType());
2171 if (!CAT)
2172 return false;
2173
2174 Result = APValue(APValue::UninitArray(), 0,
2175 CAT->getSize().getZExtValue());
2176 if (!Result.hasArrayFiller()) return true;
2177
2178 // Value-initialize all elements.
2179 LValue Subobject = This;
2180 Subobject.Designator.addIndex(0);
2181 ImplicitValueInitExpr VIE(CAT->getElementType());
2182 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2183 Subobject, &VIE);
2184 }
2185
2186 // FIXME: We also get CXXConstructExpr, in cases like:
2187 // struct S { constexpr S(); }; constexpr S s[10];
Richard Smithcc5d4f62011-11-07 09:22:26 +00002188 bool VisitInitListExpr(const InitListExpr *E);
2189 };
2190} // end anonymous namespace
2191
Richard Smith180f4792011-11-10 06:34:14 +00002192static bool EvaluateArray(const Expr *E, const LValue &This,
2193 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002194 assert(E->isRValue() && E->getType()->isArrayType() &&
2195 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002196 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002197}
2198
2199bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2200 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2201 if (!CAT)
2202 return false;
2203
2204 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2205 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002206 LValue Subobject = This;
2207 Subobject.Designator.addIndex(0);
2208 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002209 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00002210 I != End; ++I, ++Index) {
2211 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2212 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00002213 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002214 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2215 return false;
2216 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002217
2218 if (!Result.hasArrayFiller()) return true;
2219 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00002220 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2221 // but sometimes does:
2222 // struct S { constexpr S() : p(&p) {} void *p; };
2223 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00002224 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00002225 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00002226}
2227
2228//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002229// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002230//
2231// As a GNU extension, we support casting pointers to sufficiently-wide integer
2232// types and back in constant folding. Integer values are thus represented
2233// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002234//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002235
2236namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002237class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002238 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00002239 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00002240public:
Richard Smith47a1eed2011-10-29 20:57:55 +00002241 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002242 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002243
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002244 bool Success(const llvm::APSInt &SI, const Expr *E) {
2245 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002246 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002247 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002248 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002249 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002250 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002251 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002252 return true;
2253 }
2254
Daniel Dunbar131eb432009-02-19 09:06:44 +00002255 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002256 assert(E->getType()->isIntegralOrEnumerationType() &&
2257 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002258 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002259 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002260 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00002261 Result.getInt().setIsUnsigned(
2262 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00002263 return true;
2264 }
2265
2266 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002267 assert(E->getType()->isIntegralOrEnumerationType() &&
2268 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002269 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00002270 return true;
2271 }
2272
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002273 bool Success(CharUnits Size, const Expr *E) {
2274 return Success(Size.getQuantity(), E);
2275 }
2276
2277
Anders Carlsson82206e22008-11-30 18:14:57 +00002278 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002279 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00002280 if (Info.EvalStatus.Diag == 0) {
2281 Info.EvalStatus.DiagLoc = L;
2282 Info.EvalStatus.Diag = D;
2283 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00002284 }
Chris Lattner54176fd2008-07-12 00:14:42 +00002285 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00002286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Richard Smith47a1eed2011-10-29 20:57:55 +00002288 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00002289 if (V.isLValue()) {
2290 Result = V;
2291 return true;
2292 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00002294 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002295 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002296 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00002297 }
Mike Stump1eb44332009-09-09 15:08:12 +00002298
Richard Smithf10d9172011-10-11 21:43:33 +00002299 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2300
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002301 //===--------------------------------------------------------------------===//
2302 // Visitor Methods
2303 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00002304
Chris Lattner4c4867e2008-07-12 00:38:25 +00002305 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002306 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002307 }
2308 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002309 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002310 }
Eli Friedman04309752009-11-24 05:28:59 +00002311
2312 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2313 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314 if (CheckReferencedDecl(E, E->getDecl()))
2315 return true;
2316
2317 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002318 }
2319 bool VisitMemberExpr(const MemberExpr *E) {
2320 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00002321 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00002322 return true;
2323 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324
2325 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002326 }
2327
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002329 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002330 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002331 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00002332
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002334 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00002335
Anders Carlsson3068d112008-11-16 19:01:22 +00002336 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002337 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00002338 }
Mike Stump1eb44332009-09-09 15:08:12 +00002339
Richard Smithf10d9172011-10-11 21:43:33 +00002340 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00002341 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002342 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00002343 }
2344
Sebastian Redl64b45f72009-01-05 20:52:13 +00002345 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002346 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002347 }
2348
Francois Pichet6ad6f282010-12-07 00:08:36 +00002349 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2350 return Success(E->getValue(), E);
2351 }
2352
John Wiegley21ff2e52011-04-28 00:16:57 +00002353 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2354 return Success(E->getValue(), E);
2355 }
2356
John Wiegley55262202011-04-25 06:54:41 +00002357 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2358 return Success(E->getValue(), E);
2359 }
2360
Eli Friedman722c7172009-02-28 03:59:05 +00002361 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002362 bool VisitUnaryImag(const UnaryOperator *E);
2363
Sebastian Redl295995c2010-09-10 20:55:47 +00002364 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00002365 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002366
Chris Lattnerfcee0012008-07-11 21:24:13 +00002367private:
Ken Dyck8b752f12010-01-27 17:10:57 +00002368 CharUnits GetAlignOfExpr(const Expr *E);
2369 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002370 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002372 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002373};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002374} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002375
Richard Smithc49bd112011-10-28 17:51:58 +00002376/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2377/// produce either the integer value or a pointer.
2378///
2379/// GCC has a heinous extension which folds casts between pointer types and
2380/// pointer-sized integral types. We support this by allowing the evaluation of
2381/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2382/// Some simple arithmetic on such values is supported (they are treated much
2383/// like char*).
Richard Smith47a1eed2011-10-29 20:57:55 +00002384static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2385 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002386 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002388}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002389
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002390static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002391 CCValue Val;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002392 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2393 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002394 Result = Val.getInt();
2395 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00002396}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002397
Eli Friedman04309752009-11-24 05:28:59 +00002398bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00002399 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002400 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002401 // Check for signedness/width mismatches between E type and ECD value.
2402 bool SameSign = (ECD->getInitVal().isSigned()
2403 == E->getType()->isSignedIntegerOrEnumerationType());
2404 bool SameWidth = (ECD->getInitVal().getBitWidth()
2405 == Info.Ctx.getIntWidth(E->getType()));
2406 if (SameSign && SameWidth)
2407 return Success(ECD->getInitVal(), E);
2408 else {
2409 // Get rid of mismatch (otherwise Success assertions will fail)
2410 // by computing a new value matching the type of E.
2411 llvm::APSInt Val = ECD->getInitVal();
2412 if (!SameSign)
2413 Val.setIsSigned(!ECD->getInitVal().isSigned());
2414 if (!SameWidth)
2415 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2416 return Success(Val, E);
2417 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002418 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002419 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00002420}
2421
Chris Lattnera4d55d82008-10-06 06:40:35 +00002422/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2423/// as GCC.
2424static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2425 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002426 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00002427 enum gcc_type_class {
2428 no_type_class = -1,
2429 void_type_class, integer_type_class, char_type_class,
2430 enumeral_type_class, boolean_type_class,
2431 pointer_type_class, reference_type_class, offset_type_class,
2432 real_type_class, complex_type_class,
2433 function_type_class, method_type_class,
2434 record_type_class, union_type_class,
2435 array_type_class, string_type_class,
2436 lang_type_class
2437 };
Mike Stump1eb44332009-09-09 15:08:12 +00002438
2439 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00002440 // ideal, however it is what gcc does.
2441 if (E->getNumArgs() == 0)
2442 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00002443
Chris Lattnera4d55d82008-10-06 06:40:35 +00002444 QualType ArgTy = E->getArg(0)->getType();
2445 if (ArgTy->isVoidType())
2446 return void_type_class;
2447 else if (ArgTy->isEnumeralType())
2448 return enumeral_type_class;
2449 else if (ArgTy->isBooleanType())
2450 return boolean_type_class;
2451 else if (ArgTy->isCharType())
2452 return string_type_class; // gcc doesn't appear to use char_type_class
2453 else if (ArgTy->isIntegerType())
2454 return integer_type_class;
2455 else if (ArgTy->isPointerType())
2456 return pointer_type_class;
2457 else if (ArgTy->isReferenceType())
2458 return reference_type_class;
2459 else if (ArgTy->isRealType())
2460 return real_type_class;
2461 else if (ArgTy->isComplexType())
2462 return complex_type_class;
2463 else if (ArgTy->isFunctionType())
2464 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00002465 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00002466 return record_type_class;
2467 else if (ArgTy->isUnionType())
2468 return union_type_class;
2469 else if (ArgTy->isArrayType())
2470 return array_type_class;
2471 else if (ArgTy->isUnionType())
2472 return union_type_class;
2473 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00002474 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00002475 return -1;
2476}
2477
John McCall42c8f872010-05-10 23:27:23 +00002478/// Retrieves the "underlying object type" of the given expression,
2479/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002480QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
2481 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
2482 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00002483 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002484 } else if (const Expr *E = B.get<const Expr*>()) {
2485 if (isa<CompoundLiteralExpr>(E))
2486 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00002487 }
2488
2489 return QualType();
2490}
2491
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002492bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00002493 // TODO: Perhaps we should let LLVM lower this?
2494 LValue Base;
2495 if (!EvaluatePointer(E->getArg(0), Base, Info))
2496 return false;
2497
2498 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002499 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00002500
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002501 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00002502 if (T.isNull() ||
2503 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00002504 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00002505 T->isVariablyModifiedType() ||
2506 T->isDependentType())
2507 return false;
2508
2509 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
2510 CharUnits Offset = Base.getLValueOffset();
2511
2512 if (!Offset.isNegative() && Offset <= Size)
2513 Size -= Offset;
2514 else
2515 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002516 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00002517}
2518
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002519bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002520 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00002521 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002522 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00002523
2524 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00002525 if (TryEvaluateBuiltinObjectSize(E))
2526 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00002527
Eric Christopherb2aaf512010-01-19 22:58:35 +00002528 // If evaluating the argument has side-effects we can't determine
2529 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002530 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002531 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00002532 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00002533 return Success(0, E);
2534 }
Mike Stumpc4c90452009-10-27 22:09:17 +00002535
Mike Stump64eda9e2009-10-26 18:35:08 +00002536 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2537 }
2538
Chris Lattner019f4e82008-10-06 05:28:25 +00002539 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002540 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00002541
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002542 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00002543 // __builtin_constant_p always has one operand: it returns true if that
2544 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00002545 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002546
2547 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00002548 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002549 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00002550 return Success(Operand, E);
2551 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00002552
2553 case Builtin::BI__builtin_expect:
2554 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00002555
2556 case Builtin::BIstrlen:
2557 case Builtin::BI__builtin_strlen:
2558 // As an extension, we support strlen() and __builtin_strlen() as constant
2559 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002560 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00002561 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2562 // The string literal may have embedded null characters. Find the first
2563 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002564 StringRef Str = S->getString();
2565 StringRef::size_type Pos = Str.find(0);
2566 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00002567 Str = Str.substr(0, Pos);
2568
2569 return Success(Str.size(), E);
2570 }
2571
2572 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00002573
2574 case Builtin::BI__atomic_is_lock_free: {
2575 APSInt SizeVal;
2576 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2577 return false;
2578
2579 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2580 // of two less than the maximum inline atomic width, we know it is
2581 // lock-free. If the size isn't a power of two, or greater than the
2582 // maximum alignment where we promote atomics, we know it is not lock-free
2583 // (at least not in the sense of atomic_is_lock_free). Otherwise,
2584 // the answer can only be determined at runtime; for example, 16-byte
2585 // atomics have lock-free implementations on some, but not all,
2586 // x86-64 processors.
2587
2588 // Check power-of-two.
2589 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2590 if (!Size.isPowerOfTwo())
2591#if 0
2592 // FIXME: Suppress this folding until the ABI for the promotion width
2593 // settles.
2594 return Success(0, E);
2595#else
2596 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2597#endif
2598
2599#if 0
2600 // Check against promotion width.
2601 // FIXME: Suppress this folding until the ABI for the promotion width
2602 // settles.
2603 unsigned PromoteWidthBits =
2604 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2605 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2606 return Success(0, E);
2607#endif
2608
2609 // Check against inlining width.
2610 unsigned InlineWidthBits =
2611 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2612 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2613 return Success(1, E);
2614
2615 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2616 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002617 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00002618}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002619
Richard Smith625b8072011-10-31 01:37:14 +00002620static bool HasSameBase(const LValue &A, const LValue &B) {
2621 if (!A.getLValueBase())
2622 return !B.getLValueBase();
2623 if (!B.getLValueBase())
2624 return false;
2625
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002626 if (A.getLValueBase().getOpaqueValue() !=
2627 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00002628 const Decl *ADecl = GetLValueBaseDecl(A);
2629 if (!ADecl)
2630 return false;
2631 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00002632 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00002633 return false;
2634 }
2635
2636 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00002637 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00002638}
2639
Chris Lattnerb542afe2008-07-11 19:10:17 +00002640bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002641 if (E->isAssignmentOp())
2642 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2643
John McCall2de56d12010-08-25 11:45:40 +00002644 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00002645 VisitIgnoredValue(E->getLHS());
2646 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00002647 }
2648
2649 if (E->isLogicalOp()) {
2650 // These need to be handled specially because the operands aren't
2651 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002652 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00002653
Richard Smithc49bd112011-10-28 17:51:58 +00002654 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00002655 // We were able to evaluate the LHS, see if we can get away with not
2656 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00002657 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002658 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002659
Richard Smithc49bd112011-10-28 17:51:58 +00002660 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00002661 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002662 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002663 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00002664 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002665 }
2666 } else {
Richard Smithc49bd112011-10-28 17:51:58 +00002667 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002668 // We can't evaluate the LHS; however, sometimes the result
2669 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00002670 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2671 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002672 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00002673 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00002674 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00002675
2676 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00002677 }
2678 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00002679 }
Eli Friedmana6afa762008-11-13 06:09:17 +00002680
Eli Friedmana6afa762008-11-13 06:09:17 +00002681 return false;
2682 }
2683
Anders Carlsson286f85e2008-11-16 07:17:21 +00002684 QualType LHSTy = E->getLHS()->getType();
2685 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00002686
2687 if (LHSTy->isAnyComplexType()) {
2688 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00002689 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00002690
2691 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2692 return false;
2693
2694 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2695 return false;
2696
2697 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002698 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002699 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00002700 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00002701 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2702
John McCall2de56d12010-08-25 11:45:40 +00002703 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002704 return Success((CR_r == APFloat::cmpEqual &&
2705 CR_i == APFloat::cmpEqual), E);
2706 else {
John McCall2de56d12010-08-25 11:45:40 +00002707 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002708 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00002709 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002710 CR_r == APFloat::cmpLessThan ||
2711 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00002712 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00002713 CR_i == APFloat::cmpLessThan ||
2714 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00002715 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002716 } else {
John McCall2de56d12010-08-25 11:45:40 +00002717 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00002718 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2719 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2720 else {
John McCall2de56d12010-08-25 11:45:40 +00002721 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00002722 "Invalid compex comparison.");
2723 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2724 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2725 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00002726 }
2727 }
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Anders Carlsson286f85e2008-11-16 07:17:21 +00002729 if (LHSTy->isRealFloatingType() &&
2730 RHSTy->isRealFloatingType()) {
2731 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00002732
Anders Carlsson286f85e2008-11-16 07:17:21 +00002733 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2734 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002735
Anders Carlsson286f85e2008-11-16 07:17:21 +00002736 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2737 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Anders Carlsson286f85e2008-11-16 07:17:21 +00002739 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00002740
Anders Carlsson286f85e2008-11-16 07:17:21 +00002741 switch (E->getOpcode()) {
2742 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002743 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00002744 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002745 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002746 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002747 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00002748 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002749 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002750 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00002751 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00002752 E);
John McCall2de56d12010-08-25 11:45:40 +00002753 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00002754 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00002755 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00002756 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00002757 || CR == APFloat::cmpLessThan
2758 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00002759 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00002760 }
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002762 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00002763 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00002764 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002765 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2766 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002767
John McCallefdb83e2010-05-07 21:00:08 +00002768 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00002769 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2770 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002771
Richard Smith625b8072011-10-31 01:37:14 +00002772 // Reject differing bases from the normal codepath; we special-case
2773 // comparisons to null.
2774 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00002775 // Inequalities and subtractions between unrelated pointers have
2776 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00002777 if (!E->isEqualityOp())
2778 return false;
Eli Friedmanffbda402011-10-31 22:28:05 +00002779 // A constant address may compare equal to the address of a symbol.
2780 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00002781 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00002782 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2783 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2784 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002785 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00002786 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00002787 // distinct. However, we do know that the address of a literal will be
2788 // non-null.
2789 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2790 LHSValue.Base && RHSValue.Base)
Eli Friedman5bc86102009-06-14 02:17:33 +00002791 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002792 // We can't tell whether weak symbols will end up pointing to the same
2793 // object.
2794 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman5bc86102009-06-14 02:17:33 +00002795 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00002796 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00002797 // (Note that clang defaults to -fmerge-all-constants, which can
2798 // lead to inconsistent results for comparisons involving the address
2799 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00002800 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00002801 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002802
Richard Smithcc5d4f62011-11-07 09:22:26 +00002803 // FIXME: Implement the C++11 restrictions:
2804 // - Pointer subtractions must be on elements of the same array.
2805 // - Pointer comparisons must be between members with the same access.
2806
John McCall2de56d12010-08-25 11:45:40 +00002807 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00002808 QualType Type = E->getLHS()->getType();
2809 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00002810
Richard Smith180f4792011-11-10 06:34:14 +00002811 CharUnits ElementSize;
2812 if (!HandleSizeof(Info, ElementType, ElementSize))
2813 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00002814
Richard Smith180f4792011-11-10 06:34:14 +00002815 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00002816 RHSValue.getLValueOffset();
2817 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002818 }
Richard Smith625b8072011-10-31 01:37:14 +00002819
2820 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2821 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2822 switch (E->getOpcode()) {
2823 default: llvm_unreachable("missing comparison operator");
2824 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2825 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2826 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2827 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2828 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2829 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00002830 }
Anders Carlsson3068d112008-11-16 19:01:22 +00002831 }
2832 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002833 if (!LHSTy->isIntegralOrEnumerationType() ||
2834 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00002835 // We can't continue from here for non-integral types, and they
2836 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00002837 return false;
2838 }
2839
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002840 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00002841 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00002842 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner54176fd2008-07-12 00:14:42 +00002843 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00002844
Richard Smithc49bd112011-10-28 17:51:58 +00002845 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002846 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00002847 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002848
2849 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00002850 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00002851 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2852 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00002853 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00002854 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002855 else
Richard Smith47a1eed2011-10-29 20:57:55 +00002856 LHSVal.getLValueOffset() -= AdditionalOffset;
2857 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00002858 return true;
2859 }
2860
2861 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00002862 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00002863 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002864 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2865 LHSVal.getInt().getZExtValue());
2866 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00002867 return true;
2868 }
2869
2870 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00002871 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00002872 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00002873
Richard Smithc49bd112011-10-28 17:51:58 +00002874 APSInt &LHS = LHSVal.getInt();
2875 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00002876
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002877 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002878 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002879 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002880 case BO_Mul: return Success(LHS * RHS, E);
2881 case BO_Add: return Success(LHS + RHS, E);
2882 case BO_Sub: return Success(LHS - RHS, E);
2883 case BO_And: return Success(LHS & RHS, E);
2884 case BO_Xor: return Success(LHS ^ RHS, E);
2885 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002886 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00002887 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002888 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002889 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002890 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00002891 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002892 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002893 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00002894 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00002895 // During constant-folding, a negative shift is an opposite shift.
2896 if (RHS.isSigned() && RHS.isNegative()) {
2897 RHS = -RHS;
2898 goto shift_right;
2899 }
2900
2901 shift_left:
2902 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00002903 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2904 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002905 }
John McCall2de56d12010-08-25 11:45:40 +00002906 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00002907 // During constant-folding, a negative shift is an opposite shift.
2908 if (RHS.isSigned() && RHS.isNegative()) {
2909 RHS = -RHS;
2910 goto shift_left;
2911 }
2912
2913 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00002914 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00002915 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2916 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002917 }
Mike Stump1eb44332009-09-09 15:08:12 +00002918
Richard Smithc49bd112011-10-28 17:51:58 +00002919 case BO_LT: return Success(LHS < RHS, E);
2920 case BO_GT: return Success(LHS > RHS, E);
2921 case BO_LE: return Success(LHS <= RHS, E);
2922 case BO_GE: return Success(LHS >= RHS, E);
2923 case BO_EQ: return Success(LHS == RHS, E);
2924 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00002925 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002926}
2927
Ken Dyck8b752f12010-01-27 17:10:57 +00002928CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00002929 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2930 // the result is the size of the referenced type."
2931 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2932 // result shall be the alignment of the referenced type."
2933 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2934 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00002935
2936 // __alignof is defined to return the preferred alignment.
2937 return Info.Ctx.toCharUnitsFromBits(
2938 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00002939}
2940
Ken Dyck8b752f12010-01-27 17:10:57 +00002941CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00002942 E = E->IgnoreParens();
2943
2944 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00002945 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00002946 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002947 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2948 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00002949
Chris Lattneraf707ab2009-01-24 21:53:27 +00002950 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00002951 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2952 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00002953
Chris Lattnere9feb472009-01-24 21:09:06 +00002954 return GetAlignOfType(E->getType());
2955}
2956
2957
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002958/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2959/// a result as the expression's type.
2960bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2961 const UnaryExprOrTypeTraitExpr *E) {
2962 switch(E->getKind()) {
2963 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00002964 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002965 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002966 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002967 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00002968 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00002969
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002970 case UETT_VecStep: {
2971 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00002972
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002973 if (Ty->isVectorType()) {
2974 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00002975
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002976 // The vec_step built-in functions that take a 3-component
2977 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2978 if (n == 3)
2979 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00002980
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002981 return Success(n, E);
2982 } else
2983 return Success(1, E);
2984 }
2985
2986 case UETT_SizeOf: {
2987 QualType SrcTy = E->getTypeOfArgument();
2988 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2989 // the result is the size of the referenced type."
2990 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2991 // result shall be the alignment of the referenced type."
2992 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2993 SrcTy = Ref->getPointeeType();
2994
Richard Smith180f4792011-11-10 06:34:14 +00002995 CharUnits Sizeof;
2996 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002997 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002998 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002999 }
3000 }
3001
3002 llvm_unreachable("unknown expr/type trait");
3003 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00003004}
3005
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003006bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003007 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003008 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003009 if (n == 0)
3010 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003011 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003012 for (unsigned i = 0; i != n; ++i) {
3013 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3014 switch (ON.getKind()) {
3015 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003016 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003017 APSInt IdxResult;
3018 if (!EvaluateInteger(Idx, IdxResult, Info))
3019 return false;
3020 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3021 if (!AT)
3022 return false;
3023 CurrentType = AT->getElementType();
3024 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3025 Result += IdxResult.getSExtValue() * ElementSize;
3026 break;
3027 }
3028
3029 case OffsetOfExpr::OffsetOfNode::Field: {
3030 FieldDecl *MemberDecl = ON.getField();
3031 const RecordType *RT = CurrentType->getAs<RecordType>();
3032 if (!RT)
3033 return false;
3034 RecordDecl *RD = RT->getDecl();
3035 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003036 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003037 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003038 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003039 CurrentType = MemberDecl->getType().getNonReferenceType();
3040 break;
3041 }
3042
3043 case OffsetOfExpr::OffsetOfNode::Identifier:
3044 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003045 return false;
3046
3047 case OffsetOfExpr::OffsetOfNode::Base: {
3048 CXXBaseSpecifier *BaseSpec = ON.getBase();
3049 if (BaseSpec->isVirtual())
3050 return false;
3051
3052 // Find the layout of the class whose base we are looking into.
3053 const RecordType *RT = CurrentType->getAs<RecordType>();
3054 if (!RT)
3055 return false;
3056 RecordDecl *RD = RT->getDecl();
3057 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3058
3059 // Find the base class itself.
3060 CurrentType = BaseSpec->getType();
3061 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3062 if (!BaseRT)
3063 return false;
3064
3065 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003066 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003067 break;
3068 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003069 }
3070 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003071 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003072}
3073
Chris Lattnerb542afe2008-07-11 19:10:17 +00003074bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003075 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00003076 // LNot's operand isn't necessarily an integer, so we handle it specially.
3077 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003078 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003079 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003080 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003081 }
3082
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003083 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003084 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003085 return false;
3086
Richard Smithc49bd112011-10-28 17:51:58 +00003087 // Get the operand value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003088 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00003089 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00003090 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003091
Chris Lattner75a48812008-07-11 22:15:16 +00003092 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003093 default:
Chris Lattner75a48812008-07-11 22:15:16 +00003094 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3095 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003096 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00003097 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00003098 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3099 // If so, we could clear the diagnostic ID.
Richard Smithc49bd112011-10-28 17:51:58 +00003100 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003101 case UO_Plus:
Richard Smithc49bd112011-10-28 17:51:58 +00003102 // The result is just the value.
3103 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003104 case UO_Minus:
Richard Smithc49bd112011-10-28 17:51:58 +00003105 if (!Val.isInt()) return false;
3106 return Success(-Val.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00003107 case UO_Not:
Richard Smithc49bd112011-10-28 17:51:58 +00003108 if (!Val.isInt()) return false;
3109 return Success(~Val.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003110 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003111}
Mike Stump1eb44332009-09-09 15:08:12 +00003112
Chris Lattner732b2232008-07-12 01:15:53 +00003113/// HandleCast - This is used to evaluate implicit or explicit casts where the
3114/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003115bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3116 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003117 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003118 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003119
Eli Friedman46a52322011-03-25 00:43:55 +00003120 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003121 case CK_BaseToDerived:
3122 case CK_DerivedToBase:
3123 case CK_UncheckedDerivedToBase:
3124 case CK_Dynamic:
3125 case CK_ToUnion:
3126 case CK_ArrayToPointerDecay:
3127 case CK_FunctionToPointerDecay:
3128 case CK_NullToPointer:
3129 case CK_NullToMemberPointer:
3130 case CK_BaseToDerivedMemberPointer:
3131 case CK_DerivedToBaseMemberPointer:
3132 case CK_ConstructorConversion:
3133 case CK_IntegralToPointer:
3134 case CK_ToVoid:
3135 case CK_VectorSplat:
3136 case CK_IntegralToFloating:
3137 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003138 case CK_CPointerToObjCPointerCast:
3139 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003140 case CK_AnyPointerToBlockPointerCast:
3141 case CK_ObjCObjectLValueCast:
3142 case CK_FloatingRealToComplex:
3143 case CK_FloatingComplexToReal:
3144 case CK_FloatingComplexCast:
3145 case CK_FloatingComplexToIntegralComplex:
3146 case CK_IntegralRealToComplex:
3147 case CK_IntegralComplexCast:
3148 case CK_IntegralComplexToFloatingComplex:
3149 llvm_unreachable("invalid cast kind for integral value");
3150
Eli Friedmane50c2972011-03-25 19:07:11 +00003151 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003152 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003153 case CK_LValueBitCast:
3154 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00003155 case CK_ARCProduceObject:
3156 case CK_ARCConsumeObject:
3157 case CK_ARCReclaimReturnedObject:
3158 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00003159 return false;
3160
3161 case CK_LValueToRValue:
3162 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003164
3165 case CK_MemberPointerToBoolean:
3166 case CK_PointerToBoolean:
3167 case CK_IntegralToBoolean:
3168 case CK_FloatingToBoolean:
3169 case CK_FloatingComplexToBoolean:
3170 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003171 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00003172 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003173 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003174 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003175 }
3176
Eli Friedman46a52322011-03-25 00:43:55 +00003177 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00003178 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003179 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003180
Eli Friedmanbe265702009-02-20 01:15:07 +00003181 if (!Result.isInt()) {
3182 // Only allow casts of lvalues if they are lossless.
3183 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3184 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003185
Daniel Dunbardd211642009-02-19 22:24:01 +00003186 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003187 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00003188 }
Mike Stump1eb44332009-09-09 15:08:12 +00003189
Eli Friedman46a52322011-03-25 00:43:55 +00003190 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00003191 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00003192 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003193 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003194
Daniel Dunbardd211642009-02-19 22:24:01 +00003195 if (LV.getLValueBase()) {
3196 // Only allow based lvalue casts if they are lossless.
3197 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3198 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003199
Richard Smithb755a9d2011-11-16 07:18:12 +00003200 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003201 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00003202 return true;
3203 }
3204
Ken Dycka7305832010-01-15 12:37:54 +00003205 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3206 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00003207 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00003208 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003209
Eli Friedman46a52322011-03-25 00:43:55 +00003210 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00003211 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00003212 if (!EvaluateComplex(SubExpr, C, Info))
3213 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00003214 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00003215 }
Eli Friedman2217c872009-02-22 11:46:18 +00003216
Eli Friedman46a52322011-03-25 00:43:55 +00003217 case CK_FloatingToIntegral: {
3218 APFloat F(0.0);
3219 if (!EvaluateFloat(SubExpr, F, Info))
3220 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00003221
Eli Friedman46a52322011-03-25 00:43:55 +00003222 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3223 }
3224 }
Mike Stump1eb44332009-09-09 15:08:12 +00003225
Eli Friedman46a52322011-03-25 00:43:55 +00003226 llvm_unreachable("unknown cast resulting in integral value");
3227 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003228}
Anders Carlsson2bad1682008-07-08 14:30:00 +00003229
Eli Friedman722c7172009-02-28 03:59:05 +00003230bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3231 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003232 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003233 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3234 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3235 return Success(LV.getComplexIntReal(), E);
3236 }
3237
3238 return Visit(E->getSubExpr());
3239}
3240
Eli Friedman664a1042009-02-27 04:45:43 +00003241bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00003242 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003243 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003244 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3245 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3246 return Success(LV.getComplexIntImag(), E);
3247 }
3248
Richard Smith8327fad2011-10-24 18:44:57 +00003249 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00003250 return Success(0, E);
3251}
3252
Douglas Gregoree8aff02011-01-04 17:33:58 +00003253bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3254 return Success(E->getPackLength(), E);
3255}
3256
Sebastian Redl295995c2010-09-10 20:55:47 +00003257bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3258 return Success(E->getValue(), E);
3259}
3260
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003261//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003262// Float Evaluation
3263//===----------------------------------------------------------------------===//
3264
3265namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003266class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003267 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003268 APFloat &Result;
3269public:
3270 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003271 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003272
Richard Smith47a1eed2011-10-29 20:57:55 +00003273 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003274 Result = V.getFloat();
3275 return true;
3276 }
3277 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003278 return false;
3279 }
3280
Richard Smithf10d9172011-10-11 21:43:33 +00003281 bool ValueInitialization(const Expr *E) {
3282 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3283 return true;
3284 }
3285
Chris Lattner019f4e82008-10-06 05:28:25 +00003286 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003287
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003288 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003289 bool VisitBinaryOperator(const BinaryOperator *E);
3290 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003291 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00003292
John McCallabd3a852010-05-07 22:08:54 +00003293 bool VisitUnaryReal(const UnaryOperator *E);
3294 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003295
John McCallabd3a852010-05-07 22:08:54 +00003296 // FIXME: Missing: array subscript of vector, member of vector,
3297 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003298};
3299} // end anonymous namespace
3300
3301static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003302 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003303 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003304}
3305
Jay Foad4ba2a172011-01-12 09:06:06 +00003306static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00003307 QualType ResultTy,
3308 const Expr *Arg,
3309 bool SNaN,
3310 llvm::APFloat &Result) {
3311 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3312 if (!S) return false;
3313
3314 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3315
3316 llvm::APInt fill;
3317
3318 // Treat empty strings as if they were zero.
3319 if (S->getString().empty())
3320 fill = llvm::APInt(32, 0);
3321 else if (S->getString().getAsInteger(0, fill))
3322 return false;
3323
3324 if (SNaN)
3325 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3326 else
3327 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3328 return true;
3329}
3330
Chris Lattner019f4e82008-10-06 05:28:25 +00003331bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003332 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003333 default:
3334 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3335
Chris Lattner019f4e82008-10-06 05:28:25 +00003336 case Builtin::BI__builtin_huge_val:
3337 case Builtin::BI__builtin_huge_valf:
3338 case Builtin::BI__builtin_huge_vall:
3339 case Builtin::BI__builtin_inf:
3340 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003341 case Builtin::BI__builtin_infl: {
3342 const llvm::fltSemantics &Sem =
3343 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00003344 Result = llvm::APFloat::getInf(Sem);
3345 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003346 }
Mike Stump1eb44332009-09-09 15:08:12 +00003347
John McCalldb7b72a2010-02-28 13:00:19 +00003348 case Builtin::BI__builtin_nans:
3349 case Builtin::BI__builtin_nansf:
3350 case Builtin::BI__builtin_nansl:
3351 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3352 true, Result);
3353
Chris Lattner9e621712008-10-06 06:31:58 +00003354 case Builtin::BI__builtin_nan:
3355 case Builtin::BI__builtin_nanf:
3356 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00003357 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00003358 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00003359 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3360 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003361
3362 case Builtin::BI__builtin_fabs:
3363 case Builtin::BI__builtin_fabsf:
3364 case Builtin::BI__builtin_fabsl:
3365 if (!EvaluateFloat(E->getArg(0), Result, Info))
3366 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003367
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003368 if (Result.isNegative())
3369 Result.changeSign();
3370 return true;
3371
Mike Stump1eb44332009-09-09 15:08:12 +00003372 case Builtin::BI__builtin_copysign:
3373 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003374 case Builtin::BI__builtin_copysignl: {
3375 APFloat RHS(0.);
3376 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3377 !EvaluateFloat(E->getArg(1), RHS, Info))
3378 return false;
3379 Result.copySign(RHS);
3380 return true;
3381 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003382 }
3383}
3384
John McCallabd3a852010-05-07 22:08:54 +00003385bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003386 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3387 ComplexValue CV;
3388 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3389 return false;
3390 Result = CV.FloatReal;
3391 return true;
3392 }
3393
3394 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00003395}
3396
3397bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003398 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3399 ComplexValue CV;
3400 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3401 return false;
3402 Result = CV.FloatImag;
3403 return true;
3404 }
3405
Richard Smith8327fad2011-10-24 18:44:57 +00003406 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00003407 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3408 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00003409 return true;
3410}
3411
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003412bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003413 switch (E->getOpcode()) {
3414 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003415 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003416 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00003417 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003418 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3419 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003420 Result.changeSign();
3421 return true;
3422 }
3423}
Chris Lattner019f4e82008-10-06 05:28:25 +00003424
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003425bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003426 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003427 VisitIgnoredValue(E->getLHS());
3428 return Visit(E->getRHS());
Eli Friedman7f92f032009-11-16 04:25:37 +00003429 }
3430
Richard Smithee591a92011-10-28 23:26:52 +00003431 // We can't evaluate pointer-to-member operations or assignments.
3432 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlsson96e93662010-10-31 01:21:47 +00003433 return false;
3434
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003435 // FIXME: Diagnostics? I really don't understand how the warnings
3436 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003437 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003438 if (!EvaluateFloat(E->getLHS(), Result, Info))
3439 return false;
3440 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3441 return false;
3442
3443 switch (E->getOpcode()) {
3444 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003445 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003446 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3447 return true;
John McCall2de56d12010-08-25 11:45:40 +00003448 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003449 Result.add(RHS, APFloat::rmNearestTiesToEven);
3450 return true;
John McCall2de56d12010-08-25 11:45:40 +00003451 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003452 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3453 return true;
John McCall2de56d12010-08-25 11:45:40 +00003454 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003455 Result.divide(RHS, APFloat::rmNearestTiesToEven);
3456 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003457 }
3458}
3459
3460bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3461 Result = E->getValue();
3462 return true;
3463}
3464
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003465bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
3466 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Eli Friedman2a523ee2011-03-25 00:54:52 +00003468 switch (E->getCastKind()) {
3469 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003470 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00003471
3472 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003473 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003474 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003475 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003476 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003477 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00003478 return true;
3479 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00003480
3481 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003482 if (!Visit(SubExpr))
3483 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003484 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
3485 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00003486 return true;
3487 }
John McCallf3ea8cf2010-11-14 08:17:51 +00003488
Eli Friedman2a523ee2011-03-25 00:54:52 +00003489 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00003490 ComplexValue V;
3491 if (!EvaluateComplex(SubExpr, V, Info))
3492 return false;
3493 Result = V.getComplexFloatReal();
3494 return true;
3495 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00003496 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003497
3498 return false;
3499}
3500
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003501//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003502// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003503//===----------------------------------------------------------------------===//
3504
3505namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003506class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003507 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00003508 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003510public:
John McCallf4cf1a12010-05-07 17:22:02 +00003511 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003512 : ExprEvaluatorBaseTy(info), Result(Result) {}
3513
Richard Smith47a1eed2011-10-29 20:57:55 +00003514 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003515 Result.setFrom(V);
3516 return true;
3517 }
3518 bool Error(const Expr *E) {
3519 return false;
3520 }
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003522 //===--------------------------------------------------------------------===//
3523 // Visitor Methods
3524 //===--------------------------------------------------------------------===//
3525
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003526 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003527
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003528 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003529
John McCallf4cf1a12010-05-07 17:22:02 +00003530 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003531 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003532 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003533};
3534} // end anonymous namespace
3535
John McCallf4cf1a12010-05-07 17:22:02 +00003536static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3537 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003538 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003539 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003540}
3541
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003542bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3543 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003544
3545 if (SubExpr->getType()->isRealFloatingType()) {
3546 Result.makeComplexFloat();
3547 APFloat &Imag = Result.FloatImag;
3548 if (!EvaluateFloat(SubExpr, Imag, Info))
3549 return false;
3550
3551 Result.FloatReal = APFloat(Imag.getSemantics());
3552 return true;
3553 } else {
3554 assert(SubExpr->getType()->isIntegerType() &&
3555 "Unexpected imaginary literal.");
3556
3557 Result.makeComplexInt();
3558 APSInt &Imag = Result.IntImag;
3559 if (!EvaluateInteger(SubExpr, Imag, Info))
3560 return false;
3561
3562 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3563 return true;
3564 }
3565}
3566
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003567bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003568
John McCall8786da72010-12-14 17:51:41 +00003569 switch (E->getCastKind()) {
3570 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00003571 case CK_BaseToDerived:
3572 case CK_DerivedToBase:
3573 case CK_UncheckedDerivedToBase:
3574 case CK_Dynamic:
3575 case CK_ToUnion:
3576 case CK_ArrayToPointerDecay:
3577 case CK_FunctionToPointerDecay:
3578 case CK_NullToPointer:
3579 case CK_NullToMemberPointer:
3580 case CK_BaseToDerivedMemberPointer:
3581 case CK_DerivedToBaseMemberPointer:
3582 case CK_MemberPointerToBoolean:
3583 case CK_ConstructorConversion:
3584 case CK_IntegralToPointer:
3585 case CK_PointerToIntegral:
3586 case CK_PointerToBoolean:
3587 case CK_ToVoid:
3588 case CK_VectorSplat:
3589 case CK_IntegralCast:
3590 case CK_IntegralToBoolean:
3591 case CK_IntegralToFloating:
3592 case CK_FloatingToIntegral:
3593 case CK_FloatingToBoolean:
3594 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003595 case CK_CPointerToObjCPointerCast:
3596 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00003597 case CK_AnyPointerToBlockPointerCast:
3598 case CK_ObjCObjectLValueCast:
3599 case CK_FloatingComplexToReal:
3600 case CK_FloatingComplexToBoolean:
3601 case CK_IntegralComplexToReal:
3602 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00003603 case CK_ARCProduceObject:
3604 case CK_ARCConsumeObject:
3605 case CK_ARCReclaimReturnedObject:
3606 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00003607 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00003608
John McCall8786da72010-12-14 17:51:41 +00003609 case CK_LValueToRValue:
3610 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003611 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00003612
3613 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003614 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00003615 case CK_UserDefinedConversion:
3616 return false;
3617
3618 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003619 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00003620 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003621 return false;
3622
John McCall8786da72010-12-14 17:51:41 +00003623 Result.makeComplexFloat();
3624 Result.FloatImag = APFloat(Real.getSemantics());
3625 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003626 }
3627
John McCall8786da72010-12-14 17:51:41 +00003628 case CK_FloatingComplexCast: {
3629 if (!Visit(E->getSubExpr()))
3630 return false;
3631
3632 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3633 QualType From
3634 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3635
3636 Result.FloatReal
3637 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3638 Result.FloatImag
3639 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3640 return true;
3641 }
3642
3643 case CK_FloatingComplexToIntegralComplex: {
3644 if (!Visit(E->getSubExpr()))
3645 return false;
3646
3647 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3648 QualType From
3649 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3650 Result.makeComplexInt();
3651 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3652 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3653 return true;
3654 }
3655
3656 case CK_IntegralRealToComplex: {
3657 APSInt &Real = Result.IntReal;
3658 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3659 return false;
3660
3661 Result.makeComplexInt();
3662 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3663 return true;
3664 }
3665
3666 case CK_IntegralComplexCast: {
3667 if (!Visit(E->getSubExpr()))
3668 return false;
3669
3670 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3671 QualType From
3672 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3673
3674 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3675 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3676 return true;
3677 }
3678
3679 case CK_IntegralComplexToFloatingComplex: {
3680 if (!Visit(E->getSubExpr()))
3681 return false;
3682
3683 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3684 QualType From
3685 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3686 Result.makeComplexFloat();
3687 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3688 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3689 return true;
3690 }
3691 }
3692
3693 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00003694 return false;
3695}
3696
John McCallf4cf1a12010-05-07 17:22:02 +00003697bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith2ad226b2011-11-16 17:22:48 +00003698 if (E->isPtrMemOp() || E->isAssignmentOp())
3699 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
3700
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003701 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003702 VisitIgnoredValue(E->getLHS());
3703 return Visit(E->getRHS());
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003704 }
Richard Smith2ad226b2011-11-16 17:22:48 +00003705
John McCallf4cf1a12010-05-07 17:22:02 +00003706 if (!Visit(E->getLHS()))
3707 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003708
John McCallf4cf1a12010-05-07 17:22:02 +00003709 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003710 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00003711 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003712
Daniel Dunbar3f279872009-01-29 01:32:56 +00003713 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3714 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003715 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003716 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003717 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003718 if (Result.isComplexFloat()) {
3719 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3720 APFloat::rmNearestTiesToEven);
3721 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3722 APFloat::rmNearestTiesToEven);
3723 } else {
3724 Result.getComplexIntReal() += RHS.getComplexIntReal();
3725 Result.getComplexIntImag() += RHS.getComplexIntImag();
3726 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003727 break;
John McCall2de56d12010-08-25 11:45:40 +00003728 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003729 if (Result.isComplexFloat()) {
3730 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3731 APFloat::rmNearestTiesToEven);
3732 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3733 APFloat::rmNearestTiesToEven);
3734 } else {
3735 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3736 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3737 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00003738 break;
John McCall2de56d12010-08-25 11:45:40 +00003739 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00003740 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003741 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00003742 APFloat &LHS_r = LHS.getComplexFloatReal();
3743 APFloat &LHS_i = LHS.getComplexFloatImag();
3744 APFloat &RHS_r = RHS.getComplexFloatReal();
3745 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Daniel Dunbar3f279872009-01-29 01:32:56 +00003747 APFloat Tmp = LHS_r;
3748 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3749 Result.getComplexFloatReal() = Tmp;
3750 Tmp = LHS_i;
3751 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3752 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3753
3754 Tmp = LHS_r;
3755 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3756 Result.getComplexFloatImag() = Tmp;
3757 Tmp = LHS_i;
3758 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3759 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3760 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00003761 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00003762 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003763 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3764 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00003765 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00003766 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3767 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3768 }
3769 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003770 case BO_Div:
3771 if (Result.isComplexFloat()) {
3772 ComplexValue LHS = Result;
3773 APFloat &LHS_r = LHS.getComplexFloatReal();
3774 APFloat &LHS_i = LHS.getComplexFloatImag();
3775 APFloat &RHS_r = RHS.getComplexFloatReal();
3776 APFloat &RHS_i = RHS.getComplexFloatImag();
3777 APFloat &Res_r = Result.getComplexFloatReal();
3778 APFloat &Res_i = Result.getComplexFloatImag();
3779
3780 APFloat Den = RHS_r;
3781 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3782 APFloat Tmp = RHS_i;
3783 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3784 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3785
3786 Res_r = LHS_r;
3787 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3788 Tmp = LHS_i;
3789 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3790 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3791 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3792
3793 Res_i = LHS_i;
3794 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3795 Tmp = LHS_r;
3796 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3797 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3798 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3799 } else {
3800 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3801 // FIXME: what about diagnostics?
3802 return false;
3803 }
3804 ComplexValue LHS = Result;
3805 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3806 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3807 Result.getComplexIntReal() =
3808 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3809 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3810 Result.getComplexIntImag() =
3811 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3812 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3813 }
3814 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003815 }
3816
John McCallf4cf1a12010-05-07 17:22:02 +00003817 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00003818}
3819
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00003820bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3821 // Get the operand value into 'Result'.
3822 if (!Visit(E->getSubExpr()))
3823 return false;
3824
3825 switch (E->getOpcode()) {
3826 default:
3827 // FIXME: what about diagnostics?
3828 return false;
3829 case UO_Extension:
3830 return true;
3831 case UO_Plus:
3832 // The result is always just the subexpr.
3833 return true;
3834 case UO_Minus:
3835 if (Result.isComplexFloat()) {
3836 Result.getComplexFloatReal().changeSign();
3837 Result.getComplexFloatImag().changeSign();
3838 }
3839 else {
3840 Result.getComplexIntReal() = -Result.getComplexIntReal();
3841 Result.getComplexIntImag() = -Result.getComplexIntImag();
3842 }
3843 return true;
3844 case UO_Not:
3845 if (Result.isComplexFloat())
3846 Result.getComplexFloatImag().changeSign();
3847 else
3848 Result.getComplexIntImag() = -Result.getComplexIntImag();
3849 return true;
3850 }
3851}
3852
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00003853//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00003854// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003855//===----------------------------------------------------------------------===//
3856
Richard Smith47a1eed2011-10-29 20:57:55 +00003857static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003858 // In C, function designators are not lvalues, but we evaluate them as if they
3859 // are.
3860 if (E->isGLValue() || E->getType()->isFunctionType()) {
3861 LValue LV;
3862 if (!EvaluateLValue(E, LV, Info))
3863 return false;
3864 LV.moveInto(Result);
3865 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003866 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00003867 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00003868 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00003869 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003870 return false;
John McCallefdb83e2010-05-07 21:00:08 +00003871 } else if (E->getType()->hasPointerRepresentation()) {
3872 LValue LV;
3873 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003874 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003875 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00003876 } else if (E->getType()->isRealFloatingType()) {
3877 llvm::APFloat F(0.0);
3878 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003879 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003880 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00003881 } else if (E->getType()->isAnyComplexType()) {
3882 ComplexValue C;
3883 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003884 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00003885 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00003886 } else if (E->getType()->isMemberPointerType()) {
3887 // FIXME: Implement evaluation of pointer-to-member types.
3888 return false;
3889 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00003890 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003891 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00003892 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00003893 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003894 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00003895 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00003896 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003897 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00003898 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
3899 return false;
3900 Result = Info.CurrentCall->Temporaries[E];
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00003901 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00003902 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00003903
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00003904 return true;
3905}
3906
Richard Smith69c2c502011-11-04 05:33:44 +00003907/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3908/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3909/// since later initializers for an object can indirectly refer to subobjects
3910/// which were initialized earlier.
3911static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00003912 const LValue &This, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003913 if (E->isRValue() && E->getType()->isLiteralType()) {
3914 // Evaluate arrays and record types in-place, so that later initializers can
3915 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00003916 if (E->getType()->isArrayType())
3917 return EvaluateArray(E, This, Result, Info);
3918 else if (E->getType()->isRecordType())
3919 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00003920 }
3921
3922 // For any other type, in-place evaluation is unimportant.
3923 CCValue CoreConstResult;
3924 return Evaluate(CoreConstResult, Info, E) &&
3925 CheckConstantExpression(CoreConstResult, Result);
3926}
3927
Richard Smithc49bd112011-10-28 17:51:58 +00003928
Richard Smith51f47082011-10-29 00:50:52 +00003929/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00003930/// any crazy technique (that has nothing to do with language standards) that
3931/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00003932/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3933/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00003934bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith1445bba2011-11-10 03:30:42 +00003935 // FIXME: Evaluating initializers for large arrays can cause performance
3936 // problems, and we don't use such values yet. Once we have a more efficient
3937 // array representation, this should be reinstated, and used by CodeGen.
3938 if (isRValue() && getType()->isArrayType())
3939 return false;
3940
John McCall56ca35d2011-02-17 10:25:35 +00003941 EvalInfo Info(Ctx, Result);
Richard Smithc49bd112011-10-28 17:51:58 +00003942
Richard Smith180f4792011-11-10 06:34:14 +00003943 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smith47a1eed2011-10-29 20:57:55 +00003944 CCValue Value;
3945 if (!::Evaluate(Value, Info, this))
Richard Smithc49bd112011-10-28 17:51:58 +00003946 return false;
3947
3948 if (isGLValue()) {
3949 LValue LV;
Richard Smith47a1eed2011-10-29 20:57:55 +00003950 LV.setFrom(Value);
3951 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3952 return false;
Richard Smithc49bd112011-10-28 17:51:58 +00003953 }
3954
Richard Smith47a1eed2011-10-29 20:57:55 +00003955 // Check this core constant expression is a constant expression, and if so,
Richard Smith69c2c502011-11-04 05:33:44 +00003956 // convert it to one.
3957 return CheckConstantExpression(Value, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00003958}
3959
Jay Foad4ba2a172011-01-12 09:06:06 +00003960bool Expr::EvaluateAsBooleanCondition(bool &Result,
3961 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003962 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00003963 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00003964 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00003965 Result);
John McCallcd7a4452010-01-05 23:42:56 +00003966}
3967
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003968bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00003969 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00003970 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithc49bd112011-10-28 17:51:58 +00003971 !ExprResult.Val.isInt()) {
3972 return false;
3973 }
3974 Result = ExprResult.Val.getInt();
3975 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003976}
3977
Jay Foad4ba2a172011-01-12 09:06:06 +00003978bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00003979 EvalInfo Info(Ctx, Result);
3980
John McCallefdb83e2010-05-07 21:00:08 +00003981 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00003982 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3983 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00003984}
3985
Richard Smith51f47082011-10-29 00:50:52 +00003986/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3987/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00003988bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00003989 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00003990 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00003991}
Anders Carlsson51fe9962008-11-22 21:04:56 +00003992
Jay Foad4ba2a172011-01-12 09:06:06 +00003993bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00003994 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003995}
3996
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003997APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003998 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00003999 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004000 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004001 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004002 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004003
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004004 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004005}
John McCalld905f5a2010-05-07 05:32:02 +00004006
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004007 bool Expr::EvalResult::isGlobalLValue() const {
4008 assert(Val.isLValue());
4009 return IsGlobalLValue(Val.getLValueBase());
4010 }
4011
4012
John McCalld905f5a2010-05-07 05:32:02 +00004013/// isIntegerConstantExpr - this recursive routine will test if an expression is
4014/// an integer constant expression.
4015
4016/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4017/// comma, etc
4018///
4019/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4020/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4021/// cast+dereference.
4022
4023// CheckICE - This function does the fundamental ICE checking: the returned
4024// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4025// Note that to reduce code duplication, this helper does no evaluation
4026// itself; the caller checks whether the expression is evaluatable, and
4027// in the rare cases where CheckICE actually cares about the evaluated
4028// value, it calls into Evalute.
4029//
4030// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004031// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004032// 1: This expression is not an ICE, but if it isn't evaluated, it's
4033// a legal subexpression for an ICE. This return value is used to handle
4034// the comma operator in C99 mode.
4035// 2: This expression is not an ICE, and is not a legal subexpression for one.
4036
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004037namespace {
4038
John McCalld905f5a2010-05-07 05:32:02 +00004039struct ICEDiag {
4040 unsigned Val;
4041 SourceLocation Loc;
4042
4043 public:
4044 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4045 ICEDiag() : Val(0) {}
4046};
4047
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004048}
4049
4050static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004051
4052static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4053 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004054 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004055 !EVResult.Val.isInt()) {
4056 return ICEDiag(2, E->getLocStart());
4057 }
4058 return NoDiag();
4059}
4060
4061static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4062 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004063 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004064 return ICEDiag(2, E->getLocStart());
4065 }
4066
4067 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004068#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004069#define STMT(Node, Base) case Expr::Node##Class:
4070#define EXPR(Node, Base)
4071#include "clang/AST/StmtNodes.inc"
4072 case Expr::PredefinedExprClass:
4073 case Expr::FloatingLiteralClass:
4074 case Expr::ImaginaryLiteralClass:
4075 case Expr::StringLiteralClass:
4076 case Expr::ArraySubscriptExprClass:
4077 case Expr::MemberExprClass:
4078 case Expr::CompoundAssignOperatorClass:
4079 case Expr::CompoundLiteralExprClass:
4080 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004081 case Expr::DesignatedInitExprClass:
4082 case Expr::ImplicitValueInitExprClass:
4083 case Expr::ParenListExprClass:
4084 case Expr::VAArgExprClass:
4085 case Expr::AddrLabelExprClass:
4086 case Expr::StmtExprClass:
4087 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004088 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004089 case Expr::CXXDynamicCastExprClass:
4090 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004091 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004092 case Expr::CXXNullPtrLiteralExprClass:
4093 case Expr::CXXThisExprClass:
4094 case Expr::CXXThrowExprClass:
4095 case Expr::CXXNewExprClass:
4096 case Expr::CXXDeleteExprClass:
4097 case Expr::CXXPseudoDestructorExprClass:
4098 case Expr::UnresolvedLookupExprClass:
4099 case Expr::DependentScopeDeclRefExprClass:
4100 case Expr::CXXConstructExprClass:
4101 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00004102 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00004103 case Expr::CXXTemporaryObjectExprClass:
4104 case Expr::CXXUnresolvedConstructExprClass:
4105 case Expr::CXXDependentScopeMemberExprClass:
4106 case Expr::UnresolvedMemberExprClass:
4107 case Expr::ObjCStringLiteralClass:
4108 case Expr::ObjCEncodeExprClass:
4109 case Expr::ObjCMessageExprClass:
4110 case Expr::ObjCSelectorExprClass:
4111 case Expr::ObjCProtocolExprClass:
4112 case Expr::ObjCIvarRefExprClass:
4113 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004114 case Expr::ObjCIsaExprClass:
4115 case Expr::ShuffleVectorExprClass:
4116 case Expr::BlockExprClass:
4117 case Expr::BlockDeclRefExprClass:
4118 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00004119 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00004120 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00004121 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004122 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004123 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00004124 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00004125 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00004126 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004127 return ICEDiag(2, E->getLocStart());
4128
Sebastian Redlcea8d962011-09-24 17:48:14 +00004129 case Expr::InitListExprClass:
4130 if (Ctx.getLangOptions().CPlusPlus0x) {
4131 const InitListExpr *ILE = cast<InitListExpr>(E);
4132 if (ILE->getNumInits() == 0)
4133 return NoDiag();
4134 if (ILE->getNumInits() == 1)
4135 return CheckICE(ILE->getInit(0), Ctx);
4136 // Fall through for more than 1 expression.
4137 }
4138 return ICEDiag(2, E->getLocStart());
4139
Douglas Gregoree8aff02011-01-04 17:33:58 +00004140 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004141 case Expr::GNUNullExprClass:
4142 // GCC considers the GNU __null value to be an integral constant expression.
4143 return NoDiag();
4144
John McCall91a57552011-07-15 05:09:51 +00004145 case Expr::SubstNonTypeTemplateParmExprClass:
4146 return
4147 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4148
John McCalld905f5a2010-05-07 05:32:02 +00004149 case Expr::ParenExprClass:
4150 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00004151 case Expr::GenericSelectionExprClass:
4152 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004153 case Expr::IntegerLiteralClass:
4154 case Expr::CharacterLiteralClass:
4155 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00004156 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004157 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00004158 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00004159 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00004160 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00004161 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004162 return NoDiag();
4163 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00004164 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00004165 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4166 // constant expressions, but they can never be ICEs because an ICE cannot
4167 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00004168 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00004169 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00004170 return CheckEvalInICE(E, Ctx);
4171 return ICEDiag(2, E->getLocStart());
4172 }
4173 case Expr::DeclRefExprClass:
4174 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4175 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00004176 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00004177 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4178
4179 // Parameter variables are never constants. Without this check,
4180 // getAnyInitializer() can find a default argument, which leads
4181 // to chaos.
4182 if (isa<ParmVarDecl>(D))
4183 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4184
4185 // C++ 7.1.5.1p2
4186 // A variable of non-volatile const-qualified integral or enumeration
4187 // type initialized by an ICE can be used in ICEs.
4188 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00004189 if (!Dcl->getType()->isIntegralOrEnumerationType())
4190 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4191
John McCalld905f5a2010-05-07 05:32:02 +00004192 // Look for a declaration of this variable that has an initializer.
4193 const VarDecl *ID = 0;
4194 const Expr *Init = Dcl->getAnyInitializer(ID);
4195 if (Init) {
4196 if (ID->isInitKnownICE()) {
4197 // We have already checked whether this subexpression is an
4198 // integral constant expression.
4199 if (ID->isInitICE())
4200 return NoDiag();
4201 else
4202 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4203 }
4204
4205 // It's an ICE whether or not the definition we found is
4206 // out-of-line. See DR 721 and the discussion in Clang PR
4207 // 6206 for details.
4208
4209 if (Dcl->isCheckingICE()) {
4210 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4211 }
4212
4213 Dcl->setCheckingICE();
4214 ICEDiag Result = CheckICE(Init, Ctx);
4215 // Cache the result of the ICE test.
4216 Dcl->setInitKnownICE(Result.Val == 0);
4217 return Result;
4218 }
4219 }
4220 }
4221 return ICEDiag(2, E->getLocStart());
4222 case Expr::UnaryOperatorClass: {
4223 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4224 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004225 case UO_PostInc:
4226 case UO_PostDec:
4227 case UO_PreInc:
4228 case UO_PreDec:
4229 case UO_AddrOf:
4230 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00004231 // C99 6.6/3 allows increment and decrement within unevaluated
4232 // subexpressions of constant expressions, but they can never be ICEs
4233 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004234 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00004235 case UO_Extension:
4236 case UO_LNot:
4237 case UO_Plus:
4238 case UO_Minus:
4239 case UO_Not:
4240 case UO_Real:
4241 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00004242 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004243 }
4244
4245 // OffsetOf falls through here.
4246 }
4247 case Expr::OffsetOfExprClass: {
4248 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00004249 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00004250 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00004251 // compliance: we should warn earlier for offsetof expressions with
4252 // array subscripts that aren't ICEs, and if the array subscripts
4253 // are ICEs, the value of the offsetof must be an integer constant.
4254 return CheckEvalInICE(E, Ctx);
4255 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004256 case Expr::UnaryExprOrTypeTraitExprClass: {
4257 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4258 if ((Exp->getKind() == UETT_SizeOf) &&
4259 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00004260 return ICEDiag(2, E->getLocStart());
4261 return NoDiag();
4262 }
4263 case Expr::BinaryOperatorClass: {
4264 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4265 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004266 case BO_PtrMemD:
4267 case BO_PtrMemI:
4268 case BO_Assign:
4269 case BO_MulAssign:
4270 case BO_DivAssign:
4271 case BO_RemAssign:
4272 case BO_AddAssign:
4273 case BO_SubAssign:
4274 case BO_ShlAssign:
4275 case BO_ShrAssign:
4276 case BO_AndAssign:
4277 case BO_XorAssign:
4278 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00004279 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4280 // constant expressions, but they can never be ICEs because an ICE cannot
4281 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004282 return ICEDiag(2, E->getLocStart());
4283
John McCall2de56d12010-08-25 11:45:40 +00004284 case BO_Mul:
4285 case BO_Div:
4286 case BO_Rem:
4287 case BO_Add:
4288 case BO_Sub:
4289 case BO_Shl:
4290 case BO_Shr:
4291 case BO_LT:
4292 case BO_GT:
4293 case BO_LE:
4294 case BO_GE:
4295 case BO_EQ:
4296 case BO_NE:
4297 case BO_And:
4298 case BO_Xor:
4299 case BO_Or:
4300 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00004301 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4302 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00004303 if (Exp->getOpcode() == BO_Div ||
4304 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00004305 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00004306 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00004307 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004308 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004309 if (REval == 0)
4310 return ICEDiag(1, E->getLocStart());
4311 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004312 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004313 if (LEval.isMinSignedValue())
4314 return ICEDiag(1, E->getLocStart());
4315 }
4316 }
4317 }
John McCall2de56d12010-08-25 11:45:40 +00004318 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00004319 if (Ctx.getLangOptions().C99) {
4320 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4321 // if it isn't evaluated.
4322 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4323 return ICEDiag(1, E->getLocStart());
4324 } else {
4325 // In both C89 and C++, commas in ICEs are illegal.
4326 return ICEDiag(2, E->getLocStart());
4327 }
4328 }
4329 if (LHSResult.Val >= RHSResult.Val)
4330 return LHSResult;
4331 return RHSResult;
4332 }
John McCall2de56d12010-08-25 11:45:40 +00004333 case BO_LAnd:
4334 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00004335 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00004336
4337 // C++0x [expr.const]p2:
4338 // [...] subexpressions of logical AND (5.14), logical OR
4339 // (5.15), and condi- tional (5.16) operations that are not
4340 // evaluated are not considered.
4341 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4342 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004343 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004344 return LHSResult;
4345
4346 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004347 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004348 return LHSResult;
4349 }
4350
John McCalld905f5a2010-05-07 05:32:02 +00004351 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4352 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4353 // Rare case where the RHS has a comma "side-effect"; we need
4354 // to actually check the condition to see whether the side
4355 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00004356 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004357 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00004358 return RHSResult;
4359 return NoDiag();
4360 }
4361
4362 if (LHSResult.Val >= RHSResult.Val)
4363 return LHSResult;
4364 return RHSResult;
4365 }
4366 }
4367 }
4368 case Expr::ImplicitCastExprClass:
4369 case Expr::CStyleCastExprClass:
4370 case Expr::CXXFunctionalCastExprClass:
4371 case Expr::CXXStaticCastExprClass:
4372 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00004373 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004374 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00004375 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00004376 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00004377 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4378 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00004379 switch (cast<CastExpr>(E)->getCastKind()) {
4380 case CK_LValueToRValue:
4381 case CK_NoOp:
4382 case CK_IntegralToBoolean:
4383 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00004384 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00004385 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00004386 return ICEDiag(2, E->getLocStart());
4387 }
John McCalld905f5a2010-05-07 05:32:02 +00004388 }
John McCall56ca35d2011-02-17 10:25:35 +00004389 case Expr::BinaryConditionalOperatorClass: {
4390 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4391 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4392 if (CommonResult.Val == 2) return CommonResult;
4393 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4394 if (FalseResult.Val == 2) return FalseResult;
4395 if (CommonResult.Val == 1) return CommonResult;
4396 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004397 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00004398 return FalseResult;
4399 }
John McCalld905f5a2010-05-07 05:32:02 +00004400 case Expr::ConditionalOperatorClass: {
4401 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4402 // If the condition (ignoring parens) is a __builtin_constant_p call,
4403 // then only the true side is actually considered in an integer constant
4404 // expression, and it is fully evaluated. This is an important GNU
4405 // extension. See GCC PR38377 for discussion.
4406 if (const CallExpr *CallCE
4407 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00004408 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00004409 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004410 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004411 !EVResult.Val.isInt()) {
4412 return ICEDiag(2, E->getLocStart());
4413 }
4414 return NoDiag();
4415 }
4416 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004417 if (CondResult.Val == 2)
4418 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00004419
4420 // C++0x [expr.const]p2:
4421 // subexpressions of [...] conditional (5.16) operations that
4422 // are not evaluated are not considered
4423 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004424 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00004425 : false;
4426 ICEDiag TrueResult = NoDiag();
4427 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4428 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4429 ICEDiag FalseResult = NoDiag();
4430 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
4431 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4432
John McCalld905f5a2010-05-07 05:32:02 +00004433 if (TrueResult.Val == 2)
4434 return TrueResult;
4435 if (FalseResult.Val == 2)
4436 return FalseResult;
4437 if (CondResult.Val == 1)
4438 return CondResult;
4439 if (TrueResult.Val == 0 && FalseResult.Val == 0)
4440 return NoDiag();
4441 // Rare case where the diagnostics depend on which side is evaluated
4442 // Note that if we get here, CondResult is 0, and at least one of
4443 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004444 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00004445 return FalseResult;
4446 }
4447 return TrueResult;
4448 }
4449 case Expr::CXXDefaultArgExprClass:
4450 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
4451 case Expr::ChooseExprClass: {
4452 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
4453 }
4454 }
4455
4456 // Silence a GCC warning
4457 return ICEDiag(2, E->getLocStart());
4458}
4459
4460bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
4461 SourceLocation *Loc, bool isEvaluated) const {
4462 ICEDiag d = CheckICE(this, Ctx);
4463 if (d.Val != 0) {
4464 if (Loc) *Loc = d.Loc;
4465 return false;
4466 }
Richard Smithc49bd112011-10-28 17:51:58 +00004467 if (!EvaluateAsInt(Result, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00004468 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00004469 return true;
4470}