blob: 25c7a90caaa44ded7ed7f0a3955564e7a40a7c7b [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithd62306a2011-11-10 06:34:14 +000050 /// Get an LValue path entry, which is known to not be an array index, as a
51 /// field declaration.
52 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
53 APValue::BaseOrMemberType Value;
54 Value.setFromOpaqueValue(E.BaseOrMember);
55 return dyn_cast<FieldDecl>(Value.getPointer());
56 }
57 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// base class declaration.
59 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<CXXRecordDecl>(Value.getPointer());
63 }
64 /// Determine whether this LValue path entry for a base class names a virtual
65 /// base class.
66 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return Value.getInt();
70 }
71
Richard Smith80815602011-11-07 05:07:52 +000072 /// Determine whether the described subobject is an array element.
73 static bool SubobjectIsArrayElement(QualType Base,
74 ArrayRef<APValue::LValuePathEntry> Path) {
75 bool IsArrayElement = false;
76 const Type *T = Base.getTypePtr();
77 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
78 IsArrayElement = T && T->isArrayType();
79 if (IsArrayElement)
80 T = T->getBaseElementTypeUnsafe();
Richard Smithd62306a2011-11-10 06:34:14 +000081 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-11-07 05:07:52 +000082 T = FD->getType().getTypePtr();
83 else
84 // Path[I] describes a base class.
85 T = 0;
86 }
87 return IsArrayElement;
88 }
89
Richard Smith96e0c102011-11-04 02:25:55 +000090 /// A path from a glvalue to a subobject of that glvalue.
91 struct SubobjectDesignator {
92 /// True if the subobject was named in a manner not supported by C++11. Such
93 /// lvalues can still be folded, but they are not core constant expressions
94 /// and we cannot perform lvalue-to-rvalue conversions on them.
95 bool Invalid : 1;
96
97 /// Whether this designates an array element.
98 bool ArrayElement : 1;
99
100 /// Whether this designates 'one past the end' of the current subobject.
101 bool OnePastTheEnd : 1;
102
Richard Smith80815602011-11-07 05:07:52 +0000103 typedef APValue::LValuePathEntry PathEntry;
104
Richard Smith96e0c102011-11-04 02:25:55 +0000105 /// The entries on the path from the glvalue to the designated subobject.
106 SmallVector<PathEntry, 8> Entries;
107
108 SubobjectDesignator() :
109 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
110
Richard Smith80815602011-11-07 05:07:52 +0000111 SubobjectDesignator(const APValue &V) :
112 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
113 OnePastTheEnd(false) {
114 if (!Invalid) {
115 ArrayRef<PathEntry> VEntries = V.getLValuePath();
116 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
117 if (V.getLValueBase())
118 ArrayElement = SubobjectIsArrayElement(V.getLValueBase()->getType(),
119 V.getLValuePath());
120 else
121 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
122 }
123 }
124
Richard Smith96e0c102011-11-04 02:25:55 +0000125 void setInvalid() {
126 Invalid = true;
127 Entries.clear();
128 }
129 /// Update this designator to refer to the given element within this array.
130 void addIndex(uint64_t N) {
131 if (Invalid) return;
132 if (OnePastTheEnd) {
133 setInvalid();
134 return;
135 }
136 PathEntry Entry;
Richard Smith80815602011-11-07 05:07:52 +0000137 Entry.ArrayIndex = N;
Richard Smith96e0c102011-11-04 02:25:55 +0000138 Entries.push_back(Entry);
139 ArrayElement = true;
140 }
141 /// Update this designator to refer to the given base or member of this
142 /// object.
Richard Smithd62306a2011-11-10 06:34:14 +0000143 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000144 if (Invalid) return;
145 if (OnePastTheEnd) {
146 setInvalid();
147 return;
148 }
149 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000150 APValue::BaseOrMemberType Value(D, Virtual);
151 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000152 Entries.push_back(Entry);
153 ArrayElement = false;
154 }
155 /// Add N to the address of this subobject.
156 void adjustIndex(uint64_t N) {
157 if (Invalid) return;
158 if (ArrayElement) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000159 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000160 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-11-04 02:25:55 +0000161 return;
162 }
163 if (OnePastTheEnd && N == (uint64_t)-1)
164 OnePastTheEnd = false;
165 else if (!OnePastTheEnd && N == 1)
166 OnePastTheEnd = true;
167 else if (N != 0)
168 setInvalid();
169 }
170 };
171
Richard Smith0b0a0b62011-10-29 20:57:55 +0000172 /// A core constant value. This can be the value of any constant expression,
173 /// or a pointer or reference to a non-static object or function parameter.
174 class CCValue : public APValue {
175 typedef llvm::APSInt APSInt;
176 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-11-01 16:57:24 +0000177 /// If the value is a reference or pointer into a parameter or temporary,
178 /// this is the corresponding call stack frame.
179 CallStackFrame *CallFrame;
Richard Smith96e0c102011-11-04 02:25:55 +0000180 /// If the value is a reference or pointer, this is a description of how the
181 /// subobject was specified.
182 SubobjectDesignator Designator;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000183 public:
Richard Smithfec09922011-11-01 16:57:24 +0000184 struct GlobalValue {};
185
Richard Smith0b0a0b62011-10-29 20:57:55 +0000186 CCValue() {}
187 explicit CCValue(const APSInt &I) : APValue(I) {}
188 explicit CCValue(const APFloat &F) : APValue(F) {}
189 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
190 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
191 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smithfec09922011-11-01 16:57:24 +0000192 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000193 CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
194 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000195 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000196 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000197 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000198
Richard Smithfec09922011-11-01 16:57:24 +0000199 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000200 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000201 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000202 }
Richard Smith96e0c102011-11-04 02:25:55 +0000203 SubobjectDesignator &getLValueDesignator() {
204 assert(getKind() == LValue);
205 return Designator;
206 }
207 const SubobjectDesignator &getLValueDesignator() const {
208 return const_cast<CCValue*>(this)->getLValueDesignator();
209 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000210 };
211
Richard Smith254a73d2011-10-28 22:34:42 +0000212 /// A stack frame in the constexpr call stack.
213 struct CallStackFrame {
214 EvalInfo &Info;
215
216 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000217 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000218
Richard Smithd62306a2011-11-10 06:34:14 +0000219 /// This - The binding for the this pointer in this call, if any.
220 const LValue *This;
221
Richard Smith254a73d2011-10-28 22:34:42 +0000222 /// ParmBindings - Parameter bindings for this function call, indexed by
223 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000224 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000225
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000226 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
227 typedef MapTy::const_iterator temp_iterator;
228 /// Temporaries - Temporary lvalues materialized within this stack frame.
229 MapTy Temporaries;
230
Richard Smithd62306a2011-11-10 06:34:14 +0000231 CallStackFrame(EvalInfo &Info, const LValue *This,
232 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000233 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000234 };
235
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000236 struct EvalInfo {
237 const ASTContext &Ctx;
238
239 /// EvalStatus - Contains information about the evaluation.
240 Expr::EvalStatus &EvalStatus;
241
242 /// CurrentCall - The top of the constexpr call stack.
243 CallStackFrame *CurrentCall;
244
245 /// NumCalls - The number of calls we've evaluated so far.
246 unsigned NumCalls;
247
248 /// CallStackDepth - The number of calls in the call stack right now.
249 unsigned CallStackDepth;
250
251 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
252 /// OpaqueValues - Values used as the common expression in a
253 /// BinaryConditionalOperator.
254 MapTy OpaqueValues;
255
256 /// BottomFrame - The frame in which evaluation started. This must be
257 /// initialized last.
258 CallStackFrame BottomFrame;
259
Richard Smithd62306a2011-11-10 06:34:14 +0000260 /// EvaluatingDecl - This is the declaration whose initializer is being
261 /// evaluated, if any.
262 const VarDecl *EvaluatingDecl;
263
264 /// EvaluatingDeclValue - This is the value being constructed for the
265 /// declaration whose initializer is being evaluated, if any.
266 APValue *EvaluatingDeclValue;
267
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000268
269 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
270 : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
Richard Smithd62306a2011-11-10 06:34:14 +0000271 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000272
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000273 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
274 MapTy::const_iterator i = OpaqueValues.find(e);
275 if (i == OpaqueValues.end()) return 0;
276 return &i->second;
277 }
278
Richard Smithd62306a2011-11-10 06:34:14 +0000279 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
280 EvaluatingDecl = VD;
281 EvaluatingDeclValue = &Value;
282 }
283
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000284 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
285 };
286
Richard Smithd62306a2011-11-10 06:34:14 +0000287 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
288 const CCValue *Arguments)
289 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000290 Info.CurrentCall = this;
291 ++Info.CallStackDepth;
292 }
293
294 CallStackFrame::~CallStackFrame() {
295 assert(Info.CurrentCall == this && "calls retired out of order");
296 --Info.CallStackDepth;
297 Info.CurrentCall = Caller;
298 }
299
John McCall93d91dc2010-05-07 17:22:02 +0000300 struct ComplexValue {
301 private:
302 bool IsInt;
303
304 public:
305 APSInt IntReal, IntImag;
306 APFloat FloatReal, FloatImag;
307
308 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
309
310 void makeComplexFloat() { IsInt = false; }
311 bool isComplexFloat() const { return !IsInt; }
312 APFloat &getComplexFloatReal() { return FloatReal; }
313 APFloat &getComplexFloatImag() { return FloatImag; }
314
315 void makeComplexInt() { IsInt = true; }
316 bool isComplexInt() const { return IsInt; }
317 APSInt &getComplexIntReal() { return IntReal; }
318 APSInt &getComplexIntImag() { return IntImag; }
319
Richard Smith0b0a0b62011-10-29 20:57:55 +0000320 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000321 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000322 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000323 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000324 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000325 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000326 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000327 assert(v.isComplexFloat() || v.isComplexInt());
328 if (v.isComplexFloat()) {
329 makeComplexFloat();
330 FloatReal = v.getComplexFloatReal();
331 FloatImag = v.getComplexFloatImag();
332 } else {
333 makeComplexInt();
334 IntReal = v.getComplexIntReal();
335 IntImag = v.getComplexIntImag();
336 }
337 }
John McCall93d91dc2010-05-07 17:22:02 +0000338 };
John McCall45d55e42010-05-07 21:00:08 +0000339
340 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000341 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000342 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000343 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000344 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000345
Richard Smith8b3497e2011-10-31 01:37:14 +0000346 const Expr *getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000347 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000348 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000349 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000350 SubobjectDesignator &getLValueDesignator() { return Designator; }
351 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000352
Richard Smith0b0a0b62011-10-29 20:57:55 +0000353 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000354 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000355 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000356 void setFrom(const CCValue &V) {
357 assert(V.isLValue());
358 Base = V.getLValueBase();
359 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000360 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000361 Designator = V.getLValueDesignator();
362 }
363
364 void setExpr(const Expr *E, CallStackFrame *F = 0) {
365 Base = E;
366 Offset = CharUnits::Zero();
367 Frame = F;
368 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000369 }
John McCall45d55e42010-05-07 21:00:08 +0000370 };
John McCall93d91dc2010-05-07 17:22:02 +0000371}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000372
Richard Smith0b0a0b62011-10-29 20:57:55 +0000373static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000374static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +0000375 const LValue &This, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000376static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
377static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000378static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000379static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000380 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000381static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000382static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000383
384//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000385// Misc utilities
386//===----------------------------------------------------------------------===//
387
Richard Smithd62306a2011-11-10 06:34:14 +0000388/// Should this call expression be treated as a string literal?
389static bool IsStringLiteralCall(const CallExpr *E) {
390 unsigned Builtin = E->isBuiltinCall();
391 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
392 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
393}
394
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000395static bool IsGlobalLValue(const Expr* E) {
Richard Smithd62306a2011-11-10 06:34:14 +0000396 // C++11 [expr.const]p3 An address constant expression is a prvalue core
397 // constant expression of pointer type that evaluates to...
398
399 // ... a null pointer value, or a prvalue core constant expression of type
400 // std::nullptr_t.
John McCall95007602010-05-10 23:27:23 +0000401 if (!E) return true;
402
Richard Smithd62306a2011-11-10 06:34:14 +0000403 switch (E->getStmtClass()) {
404 default:
405 return false;
406 case Expr::DeclRefExprClass: {
407 const DeclRefExpr *DRE = cast<DeclRefExpr>(E);
408 // ... the address of an object with static storage duration,
John McCall95007602010-05-10 23:27:23 +0000409 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
410 return VD->hasGlobalStorage();
Richard Smithd62306a2011-11-10 06:34:14 +0000411 // ... to the address of a function,
412 if (isa<FunctionDecl>(DRE->getDecl()))
413 return true;
John McCall95007602010-05-10 23:27:23 +0000414 return false;
415 }
Richard Smithd62306a2011-11-10 06:34:14 +0000416 case Expr::CompoundLiteralExprClass:
417 return cast<CompoundLiteralExpr>(E)->isFileScope();
418 // A string literal has static storage duration.
419 case Expr::StringLiteralClass:
420 case Expr::PredefinedExprClass:
421 case Expr::ObjCStringLiteralClass:
422 case Expr::ObjCEncodeExprClass:
423 return true;
424 case Expr::CallExprClass:
425 return IsStringLiteralCall(cast<CallExpr>(E));
426 // For GCC compatibility, &&label has static storage duration.
427 case Expr::AddrLabelExprClass:
428 return true;
429 // A Block literal expression may be used as the initialization value for
430 // Block variables at global or local static scope.
431 case Expr::BlockExprClass:
432 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
433 }
John McCall95007602010-05-10 23:27:23 +0000434}
435
Richard Smith80815602011-11-07 05:07:52 +0000436/// Check that this reference or pointer core constant expression is a valid
437/// value for a constant expression. Type T should be either LValue or CCValue.
438template<typename T>
439static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
440 if (!IsGlobalLValue(LVal.getLValueBase()))
441 return false;
442
443 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
444 // A constant expression must refer to an object or be a null pointer.
445 if (Designator.Invalid || Designator.OnePastTheEnd ||
446 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
447 // FIXME: Check for out-of-bounds array indices.
448 // FIXME: This is not a constant expression.
449 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
450 APValue::NoLValuePath());
451 return true;
452 }
453
Richard Smithd62306a2011-11-10 06:34:14 +0000454 // FIXME: Null references are not constant expressions.
455
Richard Smith80815602011-11-07 05:07:52 +0000456 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
457 Designator.Entries);
458 return true;
459}
460
Richard Smith0b0a0b62011-10-29 20:57:55 +0000461/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000462/// constant expression, and if it is, produce the corresponding constant value.
463static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000464 if (!CCValue.isLValue()) {
465 Value = CCValue;
466 return true;
467 }
468 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000469}
470
Richard Smith83c68212011-10-31 05:11:32 +0000471const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
472 if (!LVal.Base)
473 return 0;
474
475 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
476 return DRE->getDecl();
477
478 // FIXME: Static data members accessed via a MemberExpr are represented as
479 // that MemberExpr. We should use the Decl directly instead.
480 if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
481 assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
482 return ME->getMemberDecl();
483 }
484
485 return 0;
486}
487
488static bool IsLiteralLValue(const LValue &Value) {
489 return Value.Base &&
490 !isa<DeclRefExpr>(Value.Base) &&
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000491 !isa<MemberExpr>(Value.Base) &&
492 !isa<MaterializeTemporaryExpr>(Value.Base);
Richard Smith83c68212011-10-31 05:11:32 +0000493}
494
Richard Smithcecf1842011-11-01 21:06:14 +0000495static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith83c68212011-10-31 05:11:32 +0000496 return Decl->hasAttr<WeakAttr>() ||
497 Decl->hasAttr<WeakRefAttr>() ||
498 Decl->isWeakImported();
499}
500
Richard Smithcecf1842011-11-01 21:06:14 +0000501static bool IsWeakLValue(const LValue &Value) {
502 const ValueDecl *Decl = GetLValueBaseDecl(Value);
503 return Decl && IsWeakDecl(Decl);
504}
505
Richard Smith11562c52011-10-28 17:51:58 +0000506static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000507 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000508
John McCalleb3e4f32010-05-07 21:34:32 +0000509 // A null base expression indicates a null pointer. These are always
510 // evaluatable, and they are false unless the offset is zero.
511 if (!Base) {
512 Result = !Value.Offset.isZero();
513 return true;
514 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000515
John McCall95007602010-05-10 23:27:23 +0000516 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000517 // FIXME: C++11 requires such conversions. Remove this check.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000518 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000519
John McCalleb3e4f32010-05-07 21:34:32 +0000520 // We have a non-null base expression. These are generally known to
521 // be true, but if it'a decl-ref to a weak symbol it can be null at
522 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000523 Result = true;
Richard Smith83c68212011-10-31 05:11:32 +0000524 return !IsWeakLValue(Value);
Eli Friedman334046a2009-06-14 02:17:33 +0000525}
526
Richard Smith0b0a0b62011-10-29 20:57:55 +0000527static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000528 switch (Val.getKind()) {
529 case APValue::Uninitialized:
530 return false;
531 case APValue::Int:
532 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000533 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000534 case APValue::Float:
535 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000536 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000537 case APValue::ComplexInt:
538 Result = Val.getComplexIntReal().getBoolValue() ||
539 Val.getComplexIntImag().getBoolValue();
540 return true;
541 case APValue::ComplexFloat:
542 Result = !Val.getComplexFloatReal().isZero() ||
543 !Val.getComplexFloatImag().isZero();
544 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000545 case APValue::LValue: {
546 LValue PointerResult;
547 PointerResult.setFrom(Val);
548 return EvalPointerValueAsBool(PointerResult, Result);
549 }
Richard Smith11562c52011-10-28 17:51:58 +0000550 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000551 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000552 case APValue::Struct:
553 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000554 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000555 }
556
Richard Smith11562c52011-10-28 17:51:58 +0000557 llvm_unreachable("unknown APValue kind");
558}
559
560static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
561 EvalInfo &Info) {
562 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000563 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000564 if (!Evaluate(Val, Info, E))
565 return false;
566 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000567}
568
Mike Stump11289f42009-09-09 15:08:12 +0000569static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000570 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000571 unsigned DestWidth = Ctx.getIntWidth(DestType);
572 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000573 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000574
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000575 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000576 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000577 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000578 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
579 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000580}
581
Mike Stump11289f42009-09-09 15:08:12 +0000582static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000583 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000584 bool ignored;
585 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000586 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000587 APFloat::rmNearestTiesToEven, &ignored);
588 return Result;
589}
590
Mike Stump11289f42009-09-09 15:08:12 +0000591static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000592 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000593 unsigned DestWidth = Ctx.getIntWidth(DestType);
594 APSInt Result = Value;
595 // Figure out if this is a truncate, extend or noop cast.
596 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000597 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000598 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000599 return Result;
600}
601
Mike Stump11289f42009-09-09 15:08:12 +0000602static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000603 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000604
605 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
606 Result.convertFromAPInt(Value, Value.isSigned(),
607 APFloat::rmNearestTiesToEven);
608 return Result;
609}
610
Richard Smithd62306a2011-11-10 06:34:14 +0000611/// If the given LValue refers to a base subobject of some object, find the most
612/// derived object and the corresponding complete record type. This is necessary
613/// in order to find the offset of a virtual base class.
614static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
615 const CXXRecordDecl *&MostDerivedType) {
616 SubobjectDesignator &D = Result.Designator;
617 if (D.Invalid || !Result.Base)
618 return false;
619
620 const Type *T = Result.Base->getType().getTypePtr();
621
622 // Find path prefix which leads to the most-derived subobject.
623 unsigned MostDerivedPathLength = 0;
624 MostDerivedType = T->getAsCXXRecordDecl();
625 bool MostDerivedIsArrayElement = false;
626
627 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
628 bool IsArray = T && T->isArrayType();
629 if (IsArray)
630 T = T->getBaseElementTypeUnsafe();
631 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
632 T = FD->getType().getTypePtr();
633 else
634 T = 0;
635
636 if (T) {
637 MostDerivedType = T->getAsCXXRecordDecl();
638 MostDerivedPathLength = I + 1;
639 MostDerivedIsArrayElement = IsArray;
640 }
641 }
642
643 if (!MostDerivedType)
644 return false;
645
646 // (B*)&d + 1 has no most-derived object.
647 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
648 return false;
649
650 // Remove the trailing base class path entries and their offsets.
651 const RecordDecl *RD = MostDerivedType;
652 for (unsigned I = MostDerivedPathLength, N = D.Entries.size(); I != N; ++I) {
653 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
654 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
655 if (isVirtualBaseClass(D.Entries[I])) {
656 assert(I == MostDerivedPathLength &&
657 "virtual base class must be immediately after most-derived class");
658 Result.Offset -= Layout.getVBaseClassOffset(Base);
659 } else
660 Result.Offset -= Layout.getBaseClassOffset(Base);
661 RD = Base;
662 }
663 D.Entries.resize(MostDerivedPathLength);
664 D.ArrayElement = MostDerivedIsArrayElement;
665 return true;
666}
667
668static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
669 const CXXRecordDecl *Derived,
670 const CXXRecordDecl *Base,
671 const ASTRecordLayout *RL = 0) {
672 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
673 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
674 Obj.Designator.addDecl(Base, /*Virtual*/ false);
675}
676
677static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
678 const CXXRecordDecl *DerivedDecl,
679 const CXXBaseSpecifier *Base) {
680 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
681
682 if (!Base->isVirtual()) {
683 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
684 return true;
685 }
686
687 // Extract most-derived object and corresponding type.
688 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
689 return false;
690
691 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
692 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
693 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
694 return true;
695}
696
697/// Update LVal to refer to the given field, which must be a member of the type
698/// currently described by LVal.
699static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
700 const FieldDecl *FD,
701 const ASTRecordLayout *RL = 0) {
702 if (!RL)
703 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
704
705 unsigned I = FD->getFieldIndex();
706 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
707 LVal.Designator.addDecl(FD);
708}
709
710/// Get the size of the given type in char units.
711static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
712 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
713 // extension.
714 if (Type->isVoidType() || Type->isFunctionType()) {
715 Size = CharUnits::One();
716 return true;
717 }
718
719 if (!Type->isConstantSizeType()) {
720 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
721 return false;
722 }
723
724 Size = Info.Ctx.getTypeSizeInChars(Type);
725 return true;
726}
727
728/// Update a pointer value to model pointer arithmetic.
729/// \param Info - Information about the ongoing evaluation.
730/// \param LVal - The pointer value to be updated.
731/// \param EltTy - The pointee type represented by LVal.
732/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
733static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
734 QualType EltTy, int64_t Adjustment) {
735 CharUnits SizeOfPointee;
736 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
737 return false;
738
739 // Compute the new offset in the appropriate width.
740 LVal.Offset += Adjustment * SizeOfPointee;
741 LVal.Designator.adjustIndex(Adjustment);
742 return true;
743}
744
Richard Smith27908702011-10-24 17:54:18 +0000745/// Try to evaluate the initializer for a variable declaration.
Richard Smithd62306a2011-11-10 06:34:14 +0000746static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000747 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000748 // If this is a parameter to an active constexpr function call, perform
749 // argument substitution.
750 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithfec09922011-11-01 16:57:24 +0000751 if (!Frame || !Frame->Arguments)
752 return false;
753 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
754 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000755 }
Richard Smith27908702011-10-24 17:54:18 +0000756
Richard Smithd62306a2011-11-10 06:34:14 +0000757 // If we're currently evaluating the initializer of this declaration, use that
758 // in-flight value.
759 if (Info.EvaluatingDecl == VD) {
760 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
761 return !Result.isUninit();
762 }
763
Richard Smithcecf1842011-11-01 21:06:14 +0000764 // Never evaluate the initializer of a weak variable. We can't be sure that
765 // this is the definition which will be used.
766 if (IsWeakDecl(VD))
767 return false;
768
Richard Smith27908702011-10-24 17:54:18 +0000769 const Expr *Init = VD->getAnyInitializer();
Richard Smithec8dcd22011-11-08 01:31:09 +0000770 if (!Init || Init->isValueDependent())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000771 return false;
Richard Smith27908702011-10-24 17:54:18 +0000772
Richard Smith0b0a0b62011-10-29 20:57:55 +0000773 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000774 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000775 return !Result.isUninit();
776 }
Richard Smith27908702011-10-24 17:54:18 +0000777
778 if (VD->isEvaluatingValue())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000779 return false;
Richard Smith27908702011-10-24 17:54:18 +0000780
781 VD->setEvaluatingValue();
782
Richard Smith0b0a0b62011-10-29 20:57:55 +0000783 Expr::EvalStatus EStatus;
784 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithd62306a2011-11-10 06:34:14 +0000785 APValue EvalResult;
786 InitInfo.setEvaluatingDecl(VD, EvalResult);
787 LValue LVal;
788 LVal.setExpr(E);
Richard Smith11562c52011-10-28 17:51:58 +0000789 // FIXME: The caller will need to know whether the value was a constant
790 // expression. If not, we should propagate up a diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +0000791 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000792 // FIXME: If the evaluation failure was not permanent (for instance, if we
793 // hit a variable with no declaration yet, or a constexpr function with no
794 // definition yet), the standard is unclear as to how we should behave.
795 //
796 // Either the initializer should be evaluated when the variable is defined,
797 // or a failed evaluation of the initializer should be reattempted each time
798 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000799 VD->setEvaluatedValue(APValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000800 return false;
801 }
Richard Smith27908702011-10-24 17:54:18 +0000802
Richard Smithed5165f2011-11-04 05:33:44 +0000803 VD->setEvaluatedValue(EvalResult);
804 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000805 return true;
Richard Smith27908702011-10-24 17:54:18 +0000806}
807
Richard Smith11562c52011-10-28 17:51:58 +0000808static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000809 Qualifiers Quals = T.getQualifiers();
810 return Quals.hasConst() && !Quals.hasVolatile();
811}
812
Richard Smithf3e9e432011-11-07 09:22:26 +0000813/// Extract the designated sub-object of an rvalue.
814static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
815 const SubobjectDesignator &Sub, QualType SubType) {
816 if (Sub.Invalid || Sub.OnePastTheEnd)
817 return false;
818 if (Sub.Entries.empty()) {
819 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
820 "Unexpected subobject type");
821 return true;
822 }
823
824 assert(!Obj.isLValue() && "extracting subobject of lvalue");
825 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +0000826 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +0000827 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000828 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +0000829 // Next subobject is an array element.
Richard Smithf3e9e432011-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 Smithd62306a2011-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 Smithf3e9e432011-11-07 09:22:26 +0000853 } else {
Richard Smithd62306a2011-11-10 06:34:14 +0000854 // Next subobject is a base class.
855 const CXXRecordDecl *RD =
856 cast<CXXRecordDecl>(ObjType->castAs<RecordType>()->getDecl());
857 const CXXRecordDecl *Base =
858 getAsBaseClass(Sub.Entries[I])->getCanonicalDecl();
859 unsigned Index = 0;
860 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
861 E = RD->bases_end(); I != E; ++I, ++Index) {
862 QualType BT = I->getType();
863 if (BT->castAs<RecordType>()->getDecl()->getCanonicalDecl() == Base) {
864 O = &O->getStructBase(Index);
865 ObjType = BT;
866 break;
867 }
868 }
869 if (Index == RD->getNumBases())
870 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +0000871 }
Richard Smithd62306a2011-11-10 06:34:14 +0000872
873 if (O->isUninit())
874 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +0000875 }
876
877 assert(Info.Ctx.hasSameUnqualifiedType(ObjType, SubType) &&
878 "Unexpected subobject type");
879 Obj = CCValue(*O, CCValue::GlobalValue());
880 return true;
881}
882
Richard Smithd62306a2011-11-10 06:34:14 +0000883/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
884/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
885/// for looking up the glvalue referred to by an entity of reference type.
886///
887/// \param Info - Information about the ongoing evaluation.
888/// \param Type - The type we expect this conversion to produce.
889/// \param LVal - The glvalue on which we are attempting to perform this action.
890/// \param RVal - The produced value will be placed here.
Richard Smithf3e9e432011-11-07 09:22:26 +0000891static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
892 const LValue &LVal, CCValue &RVal) {
Richard Smith11562c52011-10-28 17:51:58 +0000893 const Expr *Base = LVal.Base;
Richard Smithfec09922011-11-01 16:57:24 +0000894 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +0000895
896 // FIXME: Indirection through a null pointer deserves a diagnostic.
897 if (!Base)
898 return false;
899
Richard Smith8b3497e2011-10-31 01:37:14 +0000900 if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
Richard Smith11562c52011-10-28 17:51:58 +0000901 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
902 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +0000903 // expressions are constant expressions too. Inside constexpr functions,
904 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +0000905 // In C, such things can also be folded, although they are not ICEs.
906 //
Richard Smith254a73d2011-10-28 22:34:42 +0000907 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
908 // interpretation of C++11 suggests that volatile parameters are OK if
909 // they're never read (there's no prohibition against constructing volatile
910 // objects in constant expressions), but lvalue-to-rvalue conversions on
911 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +0000912 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smith96e0c102011-11-04 02:25:55 +0000913 QualType VT = VD->getType();
Richard Smitha08acd82011-11-07 03:22:51 +0000914 if (!VD || VD->isInvalidDecl())
Richard Smith96e0c102011-11-04 02:25:55 +0000915 return false;
916 if (!isa<ParmVarDecl>(VD)) {
917 if (!IsConstNonVolatile(VT))
918 return false;
Richard Smitha08acd82011-11-07 03:22:51 +0000919 // FIXME: Allow folding of values of any literal type in all languages.
920 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
921 !VD->isConstexpr())
Richard Smith96e0c102011-11-04 02:25:55 +0000922 return false;
923 }
Richard Smithd62306a2011-11-10 06:34:14 +0000924 if (!EvaluateVarDeclInit(Info, LVal.Base, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +0000925 return false;
926
Richard Smith0b0a0b62011-10-29 20:57:55 +0000927 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf3e9e432011-11-07 09:22:26 +0000928 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +0000929
930 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
931 // conversion. This happens when the declaration and the lvalue should be
932 // considered synonymous, for instance when initializing an array of char
933 // from a string literal. Continue as if the initializer lvalue was the
934 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +0000935 assert(RVal.getLValueOffset().isZero() &&
936 "offset for lvalue init of non-reference");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000937 Base = RVal.getLValueBase();
Richard Smithfec09922011-11-01 16:57:24 +0000938 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +0000939 }
940
Richard Smith96e0c102011-11-04 02:25:55 +0000941 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
942 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
943 const SubobjectDesignator &Designator = LVal.Designator;
944 if (Designator.Invalid || Designator.Entries.size() != 1)
945 return false;
946
947 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +0000948 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000949 if (Index > S->getLength())
950 return false;
951 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
952 Type->isUnsignedIntegerType());
953 if (Index < S->getLength())
954 Value = S->getCodeUnit(Index);
955 RVal = CCValue(Value);
956 return true;
957 }
958
Richard Smithf3e9e432011-11-07 09:22:26 +0000959 if (Frame) {
960 // If this is a temporary expression with a nontrivial initializer, grab the
961 // value from the relevant stack frame.
962 RVal = Frame->Temporaries[Base];
963 } else if (const CompoundLiteralExpr *CLE
964 = dyn_cast<CompoundLiteralExpr>(Base)) {
965 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
966 // initializer until now for such expressions. Such an expression can't be
967 // an ICE in C, so this only matters for fold.
968 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
969 if (!Evaluate(RVal, Info, CLE->getInitializer()))
970 return false;
971 } else
Richard Smith96e0c102011-11-04 02:25:55 +0000972 return false;
973
Richard Smithf3e9e432011-11-07 09:22:26 +0000974 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +0000975}
976
Mike Stump876387b2009-10-27 22:09:17 +0000977namespace {
Richard Smith254a73d2011-10-28 22:34:42 +0000978enum EvalStmtResult {
979 /// Evaluation failed.
980 ESR_Failed,
981 /// Hit a 'return' statement.
982 ESR_Returned,
983 /// Evaluation succeeded.
984 ESR_Succeeded
985};
986}
987
988// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000989static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +0000990 const Stmt *S) {
991 switch (S->getStmtClass()) {
992 default:
993 return ESR_Failed;
994
995 case Stmt::NullStmtClass:
996 case Stmt::DeclStmtClass:
997 return ESR_Succeeded;
998
999 case Stmt::ReturnStmtClass:
1000 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1001 return ESR_Returned;
1002 return ESR_Failed;
1003
1004 case Stmt::CompoundStmtClass: {
1005 const CompoundStmt *CS = cast<CompoundStmt>(S);
1006 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1007 BE = CS->body_end(); BI != BE; ++BI) {
1008 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1009 if (ESR != ESR_Succeeded)
1010 return ESR;
1011 }
1012 return ESR_Succeeded;
1013 }
1014 }
1015}
1016
Richard Smithd62306a2011-11-10 06:34:14 +00001017namespace {
1018typedef SmallVector<CCValue, 16> ArgVector;
1019}
1020
1021/// EvaluateArgs - Evaluate the arguments to a function call.
1022static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1023 EvalInfo &Info) {
1024 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1025 I != E; ++I)
1026 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1027 return false;
1028 return true;
1029}
1030
Richard Smith254a73d2011-10-28 22:34:42 +00001031/// Evaluate a function call.
Devang Patel63104ad2011-11-10 17:47:39 +00001032static bool HandleFunctionCall(ArrayRef<const Expr*> Args, const Stmt *Body,
1033 EvalInfo &Info, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001034 // FIXME: Implement a proper call limit, along with a command-line flag.
1035 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1036 return false;
1037
Richard Smithd62306a2011-11-10 06:34:14 +00001038 ArgVector ArgValues(Args.size());
1039 if (!EvaluateArgs(Args, ArgValues, Info))
1040 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001041
Devang Patel63104ad2011-11-10 17:47:39 +00001042 // FIXME: Pass in 'this' for member functions.
1043 const LValue *This = 0;
Richard Smithd62306a2011-11-10 06:34:14 +00001044 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001045 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1046}
1047
Richard Smithd62306a2011-11-10 06:34:14 +00001048/// Evaluate a constructor call.
Devang Patel63104ad2011-11-10 17:47:39 +00001049static bool HandleConstructorCall(ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001050 const CXXConstructorDecl *Definition,
Devang Patel63104ad2011-11-10 17:47:39 +00001051 EvalInfo &Info, const LValue &This,
Richard Smithd62306a2011-11-10 06:34:14 +00001052 APValue &Result) {
1053 if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1054 return false;
1055
1056 ArgVector ArgValues(Args.size());
1057 if (!EvaluateArgs(Args, ArgValues, Info))
1058 return false;
1059
1060 CallStackFrame Frame(Info, &This, ArgValues.data());
1061
1062 // If it's a delegating constructor, just delegate.
1063 if (Definition->isDelegatingConstructor()) {
1064 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1065 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1066 }
1067
1068 // Reserve space for the struct members.
1069 const CXXRecordDecl *RD = Definition->getParent();
1070 if (!RD->isUnion())
1071 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1072 std::distance(RD->field_begin(), RD->field_end()));
1073
1074 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1075
1076 unsigned BasesSeen = 0;
1077#ifndef NDEBUG
1078 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1079#endif
1080 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1081 E = Definition->init_end(); I != E; ++I) {
1082 if ((*I)->isBaseInitializer()) {
1083 QualType BaseType((*I)->getBaseClass(), 0);
1084#ifndef NDEBUG
1085 // Non-virtual base classes are initialized in the order in the class
1086 // definition. We cannot have a virtual base class for a literal type.
1087 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1088 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1089 "base class initializers not in expected order");
1090 ++BaseIt;
1091#endif
1092 LValue Subobject = This;
1093 HandleLValueDirectBase(Info, Subobject, RD,
1094 BaseType->getAsCXXRecordDecl(), &Layout);
1095 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1096 Subobject, (*I)->getInit()))
1097 return false;
1098 } else if (FieldDecl *FD = (*I)->getMember()) {
1099 LValue Subobject = This;
1100 HandleLValueMember(Info, Subobject, FD, &Layout);
1101 if (RD->isUnion()) {
1102 Result = APValue(FD);
1103 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1104 Subobject, (*I)->getInit()))
1105 return false;
1106 } else if (!EvaluateConstantExpression(
1107 Result.getStructField(FD->getFieldIndex()),
1108 Info, Subobject, (*I)->getInit()))
1109 return false;
1110 } else {
1111 // FIXME: handle indirect field initializers
1112 return false;
1113 }
1114 }
1115
1116 return true;
1117}
1118
Richard Smith254a73d2011-10-28 22:34:42 +00001119namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001120class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001121 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001122 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001123public:
1124
Richard Smith725810a2011-10-16 21:26:27 +00001125 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001126
1127 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001128 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001129 return true;
1130 }
1131
Peter Collingbournee9200682011-05-13 03:29:01 +00001132 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1133 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001134 return Visit(E->getResultExpr());
1135 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001136 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001137 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001138 return true;
1139 return false;
1140 }
John McCall31168b02011-06-15 23:02:42 +00001141 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001142 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001143 return true;
1144 return false;
1145 }
1146 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001147 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001148 return true;
1149 return false;
1150 }
1151
Mike Stump876387b2009-10-27 22:09:17 +00001152 // We don't want to evaluate BlockExprs multiple times, as they generate
1153 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001154 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1155 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1156 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001157 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001158 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1159 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1160 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1161 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1162 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1163 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001164 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001165 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001166 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001167 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001168 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001169 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1170 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1171 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1172 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001173 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001174 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1175 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1176 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1177 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1178 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001179 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001180 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001181 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001182 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001183 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001184
1185 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001186 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001187 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1188 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001189 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001190 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001191 return false;
1192 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001193
Peter Collingbournee9200682011-05-13 03:29:01 +00001194 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001195};
1196
John McCallc07a0c72011-02-17 10:25:35 +00001197class OpaqueValueEvaluation {
1198 EvalInfo &info;
1199 OpaqueValueExpr *opaqueValue;
1200
1201public:
1202 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1203 Expr *value)
1204 : info(info), opaqueValue(opaqueValue) {
1205
1206 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001207 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001208 this->opaqueValue = 0;
1209 return;
1210 }
John McCallc07a0c72011-02-17 10:25:35 +00001211 }
1212
1213 bool hasError() const { return opaqueValue == 0; }
1214
1215 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001216 // FIXME: This will not work for recursive constexpr functions using opaque
1217 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001218 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1219 }
1220};
1221
Mike Stump876387b2009-10-27 22:09:17 +00001222} // end anonymous namespace
1223
Eli Friedman9a156e52008-11-12 09:44:48 +00001224//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001225// Generic Evaluation
1226//===----------------------------------------------------------------------===//
1227namespace {
1228
1229template <class Derived, typename RetTy=void>
1230class ExprEvaluatorBase
1231 : public ConstStmtVisitor<Derived, RetTy> {
1232private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001233 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001234 return static_cast<Derived*>(this)->Success(V, E);
1235 }
1236 RetTy DerivedError(const Expr *E) {
1237 return static_cast<Derived*>(this)->Error(E);
1238 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001239 RetTy DerivedValueInitialization(const Expr *E) {
1240 return static_cast<Derived*>(this)->ValueInitialization(E);
1241 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001242
1243protected:
1244 EvalInfo &Info;
1245 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1246 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1247
Richard Smith4ce706a2011-10-11 21:43:33 +00001248 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1249
Peter Collingbournee9200682011-05-13 03:29:01 +00001250public:
1251 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1252
1253 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001254 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001255 }
1256 RetTy VisitExpr(const Expr *E) {
1257 return DerivedError(E);
1258 }
1259
1260 RetTy VisitParenExpr(const ParenExpr *E)
1261 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1262 RetTy VisitUnaryExtension(const UnaryOperator *E)
1263 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1264 RetTy VisitUnaryPlus(const UnaryOperator *E)
1265 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1266 RetTy VisitChooseExpr(const ChooseExpr *E)
1267 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1268 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1269 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001270 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1271 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001272 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1273 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001274
1275 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1276 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1277 if (opaque.hasError())
1278 return DerivedError(E);
1279
1280 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001281 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +00001282 return DerivedError(E);
1283
1284 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1285 }
1286
1287 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1288 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001289 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +00001290 return DerivedError(E);
1291
Richard Smith11562c52011-10-28 17:51:58 +00001292 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001293 return StmtVisitorTy::Visit(EvalExpr);
1294 }
1295
1296 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001297 const CCValue *Value = Info.getOpaqueValue(E);
1298 if (!Value)
Peter Collingbournee9200682011-05-13 03:29:01 +00001299 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
1300 : DerivedError(E));
Richard Smith0b0a0b62011-10-29 20:57:55 +00001301 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001302 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001303
Richard Smith254a73d2011-10-28 22:34:42 +00001304 RetTy VisitCallExpr(const CallExpr *E) {
1305 const Expr *Callee = E->getCallee();
1306 QualType CalleeType = Callee->getType();
1307
Devang Patel63104ad2011-11-10 17:47:39 +00001308 // FIXME: Handle the case where Callee is a (parenthesized) MemberExpr for a
1309 // non-static member function.
1310 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember))
1311 return DerivedError(E);
1312
1313 if (!CalleeType->isFunctionType() && !CalleeType->isFunctionPointerType())
1314 return DerivedError(E);
1315
1316 CCValue Call;
1317 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
1318 !Call.getLValueBase() || !Call.getLValueOffset().isZero())
1319 return DerivedError(Callee);
1320
Richard Smith254a73d2011-10-28 22:34:42 +00001321 const FunctionDecl *FD = 0;
Devang Patel63104ad2011-11-10 17:47:39 +00001322 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Call.getLValueBase()))
1323 FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1324 else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Call.getLValueBase()))
Richard Smith656d49d2011-11-10 09:31:24 +00001325 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
Devang Patel63104ad2011-11-10 17:47:39 +00001326 if (!FD)
1327 return DerivedError(Callee);
Richard Smith656d49d2011-11-10 09:31:24 +00001328
Devang Patel63104ad2011-11-10 17:47:39 +00001329 // Don't call function pointers which have been cast to some other type.
1330 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1331 return DerivedError(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001332
1333 const FunctionDecl *Definition;
1334 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001335 CCValue CCResult;
1336 APValue Result;
Devang Patel63104ad2011-11-10 17:47:39 +00001337 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith254a73d2011-10-28 22:34:42 +00001338
1339 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Devang Patel63104ad2011-11-10 17:47:39 +00001340 HandleFunctionCall(Args, Body, Info, CCResult) &&
Richard Smithed5165f2011-11-04 05:33:44 +00001341 CheckConstantExpression(CCResult, Result))
1342 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001343
1344 return DerivedError(E);
1345 }
1346
Richard Smith11562c52011-10-28 17:51:58 +00001347 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1348 return StmtVisitorTy::Visit(E->getInitializer());
1349 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001350 RetTy VisitInitListExpr(const InitListExpr *E) {
1351 if (Info.getLangOpts().CPlusPlus0x) {
1352 if (E->getNumInits() == 0)
1353 return DerivedValueInitialization(E);
1354 if (E->getNumInits() == 1)
1355 return StmtVisitorTy::Visit(E->getInit(0));
1356 }
1357 return DerivedError(E);
1358 }
1359 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1360 return DerivedValueInitialization(E);
1361 }
1362 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1363 return DerivedValueInitialization(E);
1364 }
1365
Richard Smithd62306a2011-11-10 06:34:14 +00001366 /// A member expression where the object is a prvalue is itself a prvalue.
1367 RetTy VisitMemberExpr(const MemberExpr *E) {
1368 assert(!E->isArrow() && "missing call to bound member function?");
1369
1370 CCValue Val;
1371 if (!Evaluate(Val, Info, E->getBase()))
1372 return false;
1373
1374 QualType BaseTy = E->getBase()->getType();
1375
1376 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1377 if (!FD) return false;
1378 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1379 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1380 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1381
1382 SubobjectDesignator Designator;
1383 Designator.addDecl(FD);
1384
1385 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1386 DerivedSuccess(Val, E);
1387 }
1388
Richard Smith11562c52011-10-28 17:51:58 +00001389 RetTy VisitCastExpr(const CastExpr *E) {
1390 switch (E->getCastKind()) {
1391 default:
1392 break;
1393
1394 case CK_NoOp:
1395 return StmtVisitorTy::Visit(E->getSubExpr());
1396
1397 case CK_LValueToRValue: {
1398 LValue LVal;
1399 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001400 CCValue RVal;
Richard Smith11562c52011-10-28 17:51:58 +00001401 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1402 return DerivedSuccess(RVal, E);
1403 }
1404 break;
1405 }
1406 }
1407
1408 return DerivedError(E);
1409 }
1410
Richard Smith4a678122011-10-24 18:44:57 +00001411 /// Visit a value which is evaluated, but whose value is ignored.
1412 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001413 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001414 if (!Evaluate(Scratch, Info, E))
1415 Info.EvalStatus.HasSideEffects = true;
1416 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001417};
1418
1419}
1420
1421//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001422// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001423//
1424// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1425// function designators (in C), decl references to void objects (in C), and
1426// temporaries (if building with -Wno-address-of-temporary).
1427//
1428// LValue evaluation produces values comprising a base expression of one of the
1429// following types:
1430// * DeclRefExpr
1431// * MemberExpr for a static member
1432// * CompoundLiteralExpr in C
1433// * StringLiteral
1434// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00001435// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00001436// * ObjCEncodeExpr
1437// * AddrLabelExpr
1438// * BlockExpr
1439// * CallExpr for a MakeStringConstant builtin
Richard Smithfec09922011-11-01 16:57:24 +00001440// plus an offset in bytes. It can also produce lvalues referring to locals. In
1441// that case, the Frame will point to a stack frame, and the Expr is used as a
1442// key to find the relevant temporary's value.
Eli Friedman9a156e52008-11-12 09:44:48 +00001443//===----------------------------------------------------------------------===//
1444namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001445class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001446 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001447 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001448 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +00001449
Peter Collingbournee9200682011-05-13 03:29:01 +00001450 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001451 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001452 return true;
1453 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001454public:
Mike Stump11289f42009-09-09 15:08:12 +00001455
John McCall45d55e42010-05-07 21:00:08 +00001456 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +00001457 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +00001458
Richard Smith0b0a0b62011-10-29 20:57:55 +00001459 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001460 Result.setFrom(V);
1461 return true;
1462 }
1463 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00001464 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001465 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001466
Richard Smith11562c52011-10-28 17:51:58 +00001467 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1468
Peter Collingbournee9200682011-05-13 03:29:01 +00001469 bool VisitDeclRefExpr(const DeclRefExpr *E);
1470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001471 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001472 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1473 bool VisitMemberExpr(const MemberExpr *E);
1474 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1475 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1476 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1477 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001478
Peter Collingbournee9200682011-05-13 03:29:01 +00001479 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001480 switch (E->getCastKind()) {
1481 default:
Richard Smith11562c52011-10-28 17:51:58 +00001482 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001483
Eli Friedmance3e02a2011-10-11 00:13:24 +00001484 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001485 if (!Visit(E->getSubExpr()))
1486 return false;
1487 Result.Designator.setInvalid();
1488 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001489
Richard Smithd62306a2011-11-10 06:34:14 +00001490 case CK_DerivedToBase:
1491 case CK_UncheckedDerivedToBase: {
1492 if (!Visit(E->getSubExpr()))
1493 return false;
1494
1495 // Now figure out the necessary offset to add to the base LV to get from
1496 // the derived class to the base class.
1497 QualType Type = E->getSubExpr()->getType();
1498
1499 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1500 PathE = E->path_end(); PathI != PathE; ++PathI) {
1501 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
1502 return false;
1503 Type = (*PathI)->getType();
1504 }
1505
1506 return true;
1507 }
Anders Carlssonde55f642009-10-03 16:30:22 +00001508 }
1509 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001510
Eli Friedman449fe542009-03-23 04:56:01 +00001511 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001512
Eli Friedman9a156e52008-11-12 09:44:48 +00001513};
1514} // end anonymous namespace
1515
Richard Smith11562c52011-10-28 17:51:58 +00001516/// Evaluate an expression as an lvalue. This can be legitimately called on
1517/// expressions which are not glvalues, in a few cases:
1518/// * function designators in C,
1519/// * "extern void" objects,
1520/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00001521static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001522 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1523 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1524 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00001525 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001526}
1527
Peter Collingbournee9200682011-05-13 03:29:01 +00001528bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001529 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +00001530 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +00001531 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1532 return VisitVarDecl(E, VD);
1533 return Error(E);
1534}
Richard Smith733237d2011-10-24 23:14:33 +00001535
Richard Smith11562c52011-10-28 17:51:58 +00001536bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00001537 if (!VD->getType()->isReferenceType()) {
1538 if (isa<ParmVarDecl>(VD)) {
Richard Smith96e0c102011-11-04 02:25:55 +00001539 Result.setExpr(E, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00001540 return true;
1541 }
Richard Smith11562c52011-10-28 17:51:58 +00001542 return Success(E);
Richard Smithfec09922011-11-01 16:57:24 +00001543 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00001544
Richard Smith0b0a0b62011-10-29 20:57:55 +00001545 CCValue V;
Richard Smithd62306a2011-11-10 06:34:14 +00001546 if (EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
Richard Smith0b0a0b62011-10-29 20:57:55 +00001547 return Success(V, E);
Richard Smith11562c52011-10-28 17:51:58 +00001548
1549 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +00001550}
1551
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001552bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1553 const MaterializeTemporaryExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00001554 Result.setExpr(E, Info.CurrentCall);
1555 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1556 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001557}
1558
Peter Collingbournee9200682011-05-13 03:29:01 +00001559bool
1560LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001561 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1562 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1563 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00001564 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001565}
1566
Peter Collingbournee9200682011-05-13 03:29:01 +00001567bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001568 // Handle static data members.
1569 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1570 VisitIgnoredValue(E->getBase());
1571 return VisitVarDecl(E, VD);
1572 }
1573
Richard Smith254a73d2011-10-28 22:34:42 +00001574 // Handle static member functions.
1575 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1576 if (MD->isStatic()) {
1577 VisitIgnoredValue(E->getBase());
1578 return Success(E);
1579 }
1580 }
1581
Richard Smithd62306a2011-11-10 06:34:14 +00001582 // Handle non-static data members.
1583 QualType BaseTy;
Eli Friedman9a156e52008-11-12 09:44:48 +00001584 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +00001585 if (!EvaluatePointer(E->getBase(), Result, Info))
1586 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001587 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001588 } else {
John McCall45d55e42010-05-07 21:00:08 +00001589 if (!Visit(E->getBase()))
1590 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001591 BaseTy = E->getBase()->getType();
Eli Friedman9a156e52008-11-12 09:44:48 +00001592 }
1593
Peter Collingbournee9200682011-05-13 03:29:01 +00001594 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithd62306a2011-11-10 06:34:14 +00001595 if (!FD) return false;
1596 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1597 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1598 (void)BaseTy;
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001599
Richard Smithd62306a2011-11-10 06:34:14 +00001600 HandleLValueMember(Info, Result, FD);
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001601
Richard Smithd62306a2011-11-10 06:34:14 +00001602 if (FD->getType()->isReferenceType()) {
1603 CCValue RefValue;
1604 if (!HandleLValueToRValueConversion(Info, FD->getType(), Result, RefValue))
1605 return false;
1606 return Success(RefValue, E);
1607 }
John McCall45d55e42010-05-07 21:00:08 +00001608 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +00001609}
1610
Peter Collingbournee9200682011-05-13 03:29:01 +00001611bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001612 // FIXME: Deal with vectors as array subscript bases.
1613 if (E->getBase()->getType()->isVectorType())
1614 return false;
1615
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001616 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00001617 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001618
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001619 APSInt Index;
1620 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00001621 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001622 int64_t IndexValue
1623 = Index.isSigned() ? Index.getSExtValue()
1624 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001625
Richard Smithd62306a2011-11-10 06:34:14 +00001626 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001627}
Eli Friedman9a156e52008-11-12 09:44:48 +00001628
Peter Collingbournee9200682011-05-13 03:29:01 +00001629bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00001630 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00001631}
1632
Eli Friedman9a156e52008-11-12 09:44:48 +00001633//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001634// Pointer Evaluation
1635//===----------------------------------------------------------------------===//
1636
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001637namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001638class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001639 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00001640 LValue &Result;
1641
Peter Collingbournee9200682011-05-13 03:29:01 +00001642 bool Success(const Expr *E) {
Richard Smith96e0c102011-11-04 02:25:55 +00001643 Result.setExpr(E);
John McCall45d55e42010-05-07 21:00:08 +00001644 return true;
1645 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001646public:
Mike Stump11289f42009-09-09 15:08:12 +00001647
John McCall45d55e42010-05-07 21:00:08 +00001648 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001649 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001650
Richard Smith0b0a0b62011-10-29 20:57:55 +00001651 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001652 Result.setFrom(V);
1653 return true;
1654 }
1655 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +00001656 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001657 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001658 bool ValueInitialization(const Expr *E) {
1659 return Success((Expr*)0);
1660 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001661
John McCall45d55e42010-05-07 21:00:08 +00001662 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001663 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00001664 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001665 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00001666 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001667 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00001668 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001669 bool VisitCallExpr(const CallExpr *E);
1670 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00001671 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00001672 return Success(E);
1673 return false;
Mike Stumpa6703322009-02-19 22:01:56 +00001674 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001675 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +00001676 { return ValueInitialization(E); }
Richard Smithd62306a2011-11-10 06:34:14 +00001677 bool VisitCXXThisExpr(const CXXThisExpr *E) {
1678 if (!Info.CurrentCall->This)
1679 return false;
1680 Result = *Info.CurrentCall->This;
1681 return true;
1682 }
John McCallc07a0c72011-02-17 10:25:35 +00001683
Eli Friedman449fe542009-03-23 04:56:01 +00001684 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001685};
Chris Lattner05706e882008-07-11 18:11:29 +00001686} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001687
John McCall45d55e42010-05-07 21:00:08 +00001688static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001689 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00001690 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00001691}
1692
John McCall45d55e42010-05-07 21:00:08 +00001693bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001694 if (E->getOpcode() != BO_Add &&
1695 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +00001696 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001697
Chris Lattner05706e882008-07-11 18:11:29 +00001698 const Expr *PExp = E->getLHS();
1699 const Expr *IExp = E->getRHS();
1700 if (IExp->getType()->isPointerType())
1701 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00001702
John McCall45d55e42010-05-07 21:00:08 +00001703 if (!EvaluatePointer(PExp, Result, Info))
1704 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001705
John McCall45d55e42010-05-07 21:00:08 +00001706 llvm::APSInt Offset;
1707 if (!EvaluateInteger(IExp, Offset, Info))
1708 return false;
1709 int64_t AdditionalOffset
1710 = Offset.isSigned() ? Offset.getSExtValue()
1711 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00001712 if (E->getOpcode() == BO_Sub)
1713 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00001714
Richard Smithd62306a2011-11-10 06:34:14 +00001715 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
1716 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00001717}
Eli Friedman9a156e52008-11-12 09:44:48 +00001718
John McCall45d55e42010-05-07 21:00:08 +00001719bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1720 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001721}
Mike Stump11289f42009-09-09 15:08:12 +00001722
Peter Collingbournee9200682011-05-13 03:29:01 +00001723bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1724 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00001725
Eli Friedman847a2bc2009-12-27 05:43:15 +00001726 switch (E->getCastKind()) {
1727 default:
1728 break;
1729
John McCalle3027922010-08-25 11:45:40 +00001730 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00001731 case CK_CPointerToObjCPointerCast:
1732 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001733 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001734 if (!Visit(SubExpr))
1735 return false;
1736 Result.Designator.setInvalid();
1737 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00001738
Anders Carlsson18275092010-10-31 20:41:46 +00001739 case CK_DerivedToBase:
1740 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001741 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00001742 return false;
1743
Richard Smithd62306a2011-11-10 06:34:14 +00001744 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00001745 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00001746 QualType Type =
1747 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00001748
Richard Smithd62306a2011-11-10 06:34:14 +00001749 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00001750 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00001751 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00001752 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001753 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00001754 }
1755
Anders Carlsson18275092010-10-31 20:41:46 +00001756 return true;
1757 }
1758
Richard Smith0b0a0b62011-10-29 20:57:55 +00001759 case CK_NullToPointer:
1760 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00001761
John McCalle3027922010-08-25 11:45:40 +00001762 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001763 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00001764 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00001765 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00001766
John McCall45d55e42010-05-07 21:00:08 +00001767 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001768 unsigned Size = Info.Ctx.getTypeSize(E->getType());
1769 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
John McCall45d55e42010-05-07 21:00:08 +00001770 Result.Base = 0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001771 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00001772 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00001773 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00001774 return true;
1775 } else {
1776 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001777 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00001778 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00001779 }
1780 }
John McCalle3027922010-08-25 11:45:40 +00001781 case CK_ArrayToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001782 // FIXME: Support array-to-pointer decay on array rvalues.
1783 if (!SubExpr->isGLValue())
1784 return Error(E);
Richard Smith96e0c102011-11-04 02:25:55 +00001785 if (!EvaluateLValue(SubExpr, Result, Info))
1786 return false;
1787 // The result is a pointer to the first element of the array.
1788 Result.Designator.addIndex(0);
1789 return true;
Richard Smithdd785442011-10-31 20:57:44 +00001790
John McCalle3027922010-08-25 11:45:40 +00001791 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00001792 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00001793 }
1794
Richard Smith11562c52011-10-28 17:51:58 +00001795 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00001796}
Chris Lattner05706e882008-07-11 18:11:29 +00001797
Peter Collingbournee9200682011-05-13 03:29:01 +00001798bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00001799 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00001800 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00001801
Peter Collingbournee9200682011-05-13 03:29:01 +00001802 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001803}
Chris Lattner05706e882008-07-11 18:11:29 +00001804
1805//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00001806// Record Evaluation
1807//===----------------------------------------------------------------------===//
1808
1809namespace {
1810 class RecordExprEvaluator
1811 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
1812 const LValue &This;
1813 APValue &Result;
1814 public:
1815
1816 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
1817 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
1818
1819 bool Success(const CCValue &V, const Expr *E) {
1820 return CheckConstantExpression(V, Result);
1821 }
1822 bool Error(const Expr *E) { return false; }
1823
1824 bool VisitInitListExpr(const InitListExpr *E);
1825 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
1826 };
1827}
1828
1829bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1830 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
1831 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1832
1833 if (RD->isUnion()) {
1834 Result = APValue(E->getInitializedFieldInUnion());
1835 if (!E->getNumInits())
1836 return true;
1837 LValue Subobject = This;
1838 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
1839 &Layout);
1840 return EvaluateConstantExpression(Result.getUnionValue(), Info,
1841 Subobject, E->getInit(0));
1842 }
1843
1844 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
1845 "initializer list for class with base classes");
1846 Result = APValue(APValue::UninitStruct(), 0,
1847 std::distance(RD->field_begin(), RD->field_end()));
1848 unsigned ElementNo = 0;
1849 for (RecordDecl::field_iterator Field = RD->field_begin(),
1850 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
1851 // Anonymous bit-fields are not considered members of the class for
1852 // purposes of aggregate initialization.
1853 if (Field->isUnnamedBitfield())
1854 continue;
1855
1856 LValue Subobject = This;
1857 HandleLValueMember(Info, Subobject, *Field, &Layout);
1858
1859 if (ElementNo < E->getNumInits()) {
1860 if (!EvaluateConstantExpression(
1861 Result.getStructField((*Field)->getFieldIndex()),
1862 Info, Subobject, E->getInit(ElementNo++)))
1863 return false;
1864 } else {
1865 // Perform an implicit value-initialization for members beyond the end of
1866 // the initializer list.
1867 ImplicitValueInitExpr VIE(Field->getType());
1868 if (!EvaluateConstantExpression(
1869 Result.getStructField((*Field)->getFieldIndex()),
1870 Info, Subobject, &VIE))
1871 return false;
1872 }
1873 }
1874
1875 return true;
1876}
1877
1878bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1879 const CXXConstructorDecl *FD = E->getConstructor();
1880 const FunctionDecl *Definition = 0;
1881 FD->getBody(Definition);
1882
1883 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
1884 return false;
1885
1886 // FIXME: Elide the copy/move construction wherever we can.
1887 if (E->isElidable())
1888 if (const MaterializeTemporaryExpr *ME
1889 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
1890 return Visit(ME->GetTemporaryExpr());
1891
1892 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Devang Patel63104ad2011-11-10 17:47:39 +00001893 return HandleConstructorCall(Args, cast<CXXConstructorDecl>(Definition),
1894 Info, This, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00001895}
1896
1897static bool EvaluateRecord(const Expr *E, const LValue &This,
1898 APValue &Result, EvalInfo &Info) {
1899 assert(E->isRValue() && E->getType()->isRecordType() &&
1900 E->getType()->isLiteralType() &&
1901 "can't evaluate expression as a record rvalue");
1902 return RecordExprEvaluator(Info, This, Result).Visit(E);
1903}
1904
1905//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001906// Vector Evaluation
1907//===----------------------------------------------------------------------===//
1908
1909namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001910 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00001911 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1912 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001913 public:
Mike Stump11289f42009-09-09 15:08:12 +00001914
Richard Smith2d406342011-10-22 21:10:00 +00001915 VectorExprEvaluator(EvalInfo &info, APValue &Result)
1916 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001917
Richard Smith2d406342011-10-22 21:10:00 +00001918 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1919 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1920 // FIXME: remove this APValue copy.
1921 Result = APValue(V.data(), V.size());
1922 return true;
1923 }
Richard Smithed5165f2011-11-04 05:33:44 +00001924 bool Success(const CCValue &V, const Expr *E) {
1925 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00001926 Result = V;
1927 return true;
1928 }
1929 bool Error(const Expr *E) { return false; }
1930 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001931
Richard Smith2d406342011-10-22 21:10:00 +00001932 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001933 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001934 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001935 bool VisitInitListExpr(const InitListExpr *E);
1936 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001937 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001938 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001939 // shufflevector, ExtVectorElementExpr
1940 // (Note that these require implementing conversions
1941 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001942 };
1943} // end anonymous namespace
1944
1945static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001946 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001947 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001948}
1949
Richard Smith2d406342011-10-22 21:10:00 +00001950bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1951 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001952 QualType EltTy = VTy->getElementType();
1953 unsigned NElts = VTy->getNumElements();
1954 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001955
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001956 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001957 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001958
Eli Friedmanc757de22011-03-25 00:43:55 +00001959 switch (E->getCastKind()) {
1960 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001961 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001962 if (SETy->isIntegerType()) {
1963 APSInt IntResult;
1964 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001965 return Error(E);
1966 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001967 } else if (SETy->isRealFloatingType()) {
1968 APFloat F(0.0);
1969 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001970 return Error(E);
1971 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001972 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001973 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001974 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001975
1976 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001977 SmallVector<APValue, 4> Elts(NElts, Val);
1978 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001979 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001980 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001981 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001982 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001983 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001984
Eli Friedmanc757de22011-03-25 00:43:55 +00001985 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001986 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001987
Eli Friedmanc757de22011-03-25 00:43:55 +00001988 APSInt Init;
1989 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001990 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001991
Eli Friedmanc757de22011-03-25 00:43:55 +00001992 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1993 "Vectors must be composed of ints or floats");
1994
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001995 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001996 for (unsigned i = 0; i != NElts; ++i) {
1997 APSInt Tmp = Init.extOrTrunc(EltWidth);
1998
1999 if (EltTy->isIntegerType())
2000 Elts.push_back(APValue(Tmp));
2001 else
2002 Elts.push_back(APValue(APFloat(Tmp)));
2003
2004 Init >>= EltWidth;
2005 }
Richard Smith2d406342011-10-22 21:10:00 +00002006 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002007 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002008 default:
Richard Smith11562c52011-10-28 17:51:58 +00002009 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002010 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002011}
2012
Richard Smith2d406342011-10-22 21:10:00 +00002013bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002014VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002015 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002016 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002017 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002018
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002019 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002020 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002021
John McCall875679e2010-06-11 17:54:15 +00002022 // If a vector is initialized with a single element, that value
2023 // becomes every element of the vector, not just the first.
2024 // This is the behavior described in the IBM AltiVec documentation.
2025 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002026
2027 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002028 // vector (OpenCL 6.1.6).
2029 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002030 return Visit(E->getInit(0));
2031
John McCall875679e2010-06-11 17:54:15 +00002032 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002033 if (EltTy->isIntegerType()) {
2034 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002035 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002036 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002037 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002038 } else {
2039 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002040 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002041 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002042 InitValue = APValue(f);
2043 }
2044 for (unsigned i = 0; i < NumElements; i++) {
2045 Elements.push_back(InitValue);
2046 }
2047 } else {
2048 for (unsigned i = 0; i < NumElements; i++) {
2049 if (EltTy->isIntegerType()) {
2050 llvm::APSInt sInt(32);
2051 if (i < NumInits) {
2052 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002053 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002054 } else {
2055 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2056 }
2057 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002058 } else {
John McCall875679e2010-06-11 17:54:15 +00002059 llvm::APFloat f(0.0);
2060 if (i < NumInits) {
2061 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00002062 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00002063 } else {
2064 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2065 }
2066 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002067 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002068 }
2069 }
Richard Smith2d406342011-10-22 21:10:00 +00002070 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002071}
2072
Richard Smith2d406342011-10-22 21:10:00 +00002073bool
2074VectorExprEvaluator::ValueInitialization(const Expr *E) {
2075 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002076 QualType EltTy = VT->getElementType();
2077 APValue ZeroElement;
2078 if (EltTy->isIntegerType())
2079 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2080 else
2081 ZeroElement =
2082 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2083
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002084 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002085 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002086}
2087
Richard Smith2d406342011-10-22 21:10:00 +00002088bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002089 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002090 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002091}
2092
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002093//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002094// Array Evaluation
2095//===----------------------------------------------------------------------===//
2096
2097namespace {
2098 class ArrayExprEvaluator
2099 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002100 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002101 APValue &Result;
2102 public:
2103
Richard Smithd62306a2011-11-10 06:34:14 +00002104 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2105 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002106
2107 bool Success(const APValue &V, const Expr *E) {
2108 assert(V.isArray() && "Expected array type");
2109 Result = V;
2110 return true;
2111 }
2112 bool Error(const Expr *E) { return false; }
2113
Richard Smithd62306a2011-11-10 06:34:14 +00002114 bool ValueInitialization(const Expr *E) {
2115 const ConstantArrayType *CAT =
2116 Info.Ctx.getAsConstantArrayType(E->getType());
2117 if (!CAT)
2118 return false;
2119
2120 Result = APValue(APValue::UninitArray(), 0,
2121 CAT->getSize().getZExtValue());
2122 if (!Result.hasArrayFiller()) return true;
2123
2124 // Value-initialize all elements.
2125 LValue Subobject = This;
2126 Subobject.Designator.addIndex(0);
2127 ImplicitValueInitExpr VIE(CAT->getElementType());
2128 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2129 Subobject, &VIE);
2130 }
2131
2132 // FIXME: We also get CXXConstructExpr, in cases like:
2133 // struct S { constexpr S(); }; constexpr S s[10];
Richard Smithf3e9e432011-11-07 09:22:26 +00002134 bool VisitInitListExpr(const InitListExpr *E);
2135 };
2136} // end anonymous namespace
2137
Richard Smithd62306a2011-11-10 06:34:14 +00002138static bool EvaluateArray(const Expr *E, const LValue &This,
2139 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002140 assert(E->isRValue() && E->getType()->isArrayType() &&
2141 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002142 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002143}
2144
2145bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2146 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2147 if (!CAT)
2148 return false;
2149
2150 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2151 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002152 LValue Subobject = This;
2153 Subobject.Designator.addIndex(0);
2154 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002155 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002156 I != End; ++I, ++Index) {
2157 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2158 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002159 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002160 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2161 return false;
2162 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002163
2164 if (!Result.hasArrayFiller()) return true;
2165 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00002166 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2167 // but sometimes does:
2168 // struct S { constexpr S() : p(&p) {} void *p; };
2169 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00002170 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00002171 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00002172}
2173
2174//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002175// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002176//
2177// As a GNU extension, we support casting pointers to sufficiently-wide integer
2178// types and back in constant folding. Integer values are thus represented
2179// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00002180//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002181
2182namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002183class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002184 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002185 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002186public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002187 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002188 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002189
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002190 bool Success(const llvm::APSInt &SI, const Expr *E) {
2191 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002192 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002193 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002194 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002195 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002196 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002197 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002198 return true;
2199 }
2200
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002201 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002202 assert(E->getType()->isIntegralOrEnumerationType() &&
2203 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002204 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002205 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002206 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002207 Result.getInt().setIsUnsigned(
2208 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002209 return true;
2210 }
2211
2212 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002213 assert(E->getType()->isIntegralOrEnumerationType() &&
2214 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002215 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002216 return true;
2217 }
2218
Ken Dyckdbc01912011-03-11 02:13:43 +00002219 bool Success(CharUnits Size, const Expr *E) {
2220 return Success(Size.getQuantity(), E);
2221 }
2222
2223
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002224 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002225 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00002226 if (Info.EvalStatus.Diag == 0) {
2227 Info.EvalStatus.DiagLoc = L;
2228 Info.EvalStatus.Diag = D;
2229 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002230 }
Chris Lattner99415702008-07-12 00:14:42 +00002231 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00002232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Richard Smith0b0a0b62011-10-29 20:57:55 +00002234 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00002235 if (V.isLValue()) {
2236 Result = V;
2237 return true;
2238 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002239 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002240 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002241 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002242 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002243 }
Mike Stump11289f42009-09-09 15:08:12 +00002244
Richard Smith4ce706a2011-10-11 21:43:33 +00002245 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2246
Peter Collingbournee9200682011-05-13 03:29:01 +00002247 //===--------------------------------------------------------------------===//
2248 // Visitor Methods
2249 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002250
Chris Lattner7174bf32008-07-12 00:38:25 +00002251 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002252 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002253 }
2254 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002255 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002256 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002257
2258 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2259 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002260 if (CheckReferencedDecl(E, E->getDecl()))
2261 return true;
2262
2263 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002264 }
2265 bool VisitMemberExpr(const MemberExpr *E) {
2266 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00002267 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002268 return true;
2269 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002270
2271 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002272 }
2273
Peter Collingbournee9200682011-05-13 03:29:01 +00002274 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002275 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00002276 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002277 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00002278
Peter Collingbournee9200682011-05-13 03:29:01 +00002279 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002280 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00002281
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002282 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002283 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002284 }
Mike Stump11289f42009-09-09 15:08:12 +00002285
Richard Smith4ce706a2011-10-11 21:43:33 +00002286 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00002287 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002288 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002289 }
2290
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002291 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002292 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002293 }
2294
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002295 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2296 return Success(E->getValue(), E);
2297 }
2298
John Wiegley6242b6a2011-04-28 00:16:57 +00002299 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2300 return Success(E->getValue(), E);
2301 }
2302
John Wiegleyf9f65842011-04-25 06:54:41 +00002303 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2304 return Success(E->getValue(), E);
2305 }
2306
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002307 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002308 bool VisitUnaryImag(const UnaryOperator *E);
2309
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002310 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002311 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002312
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002313private:
Ken Dyck160146e2010-01-27 17:10:57 +00002314 CharUnits GetAlignOfExpr(const Expr *E);
2315 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00002316 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002317 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002318 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00002319};
Chris Lattner05706e882008-07-11 18:11:29 +00002320} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002321
Richard Smith11562c52011-10-28 17:51:58 +00002322/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2323/// produce either the integer value or a pointer.
2324///
2325/// GCC has a heinous extension which folds casts between pointer types and
2326/// pointer-sized integral types. We support this by allowing the evaluation of
2327/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2328/// Some simple arithmetic on such values is supported (they are treated much
2329/// like char*).
Richard Smith0b0a0b62011-10-29 20:57:55 +00002330static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2331 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002332 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002333 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00002334}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002335
Daniel Dunbarce399542009-02-20 18:22:23 +00002336static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002337 CCValue Val;
Daniel Dunbarce399542009-02-20 18:22:23 +00002338 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2339 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002340 Result = Val.getInt();
2341 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002342}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002343
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002344bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002345 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00002346 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002347 // Check for signedness/width mismatches between E type and ECD value.
2348 bool SameSign = (ECD->getInitVal().isSigned()
2349 == E->getType()->isSignedIntegerOrEnumerationType());
2350 bool SameWidth = (ECD->getInitVal().getBitWidth()
2351 == Info.Ctx.getIntWidth(E->getType()));
2352 if (SameSign && SameWidth)
2353 return Success(ECD->getInitVal(), E);
2354 else {
2355 // Get rid of mismatch (otherwise Success assertions will fail)
2356 // by computing a new value matching the type of E.
2357 llvm::APSInt Val = ECD->getInitVal();
2358 if (!SameSign)
2359 Val.setIsSigned(!ECD->getInitVal().isSigned());
2360 if (!SameWidth)
2361 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2362 return Success(Val, E);
2363 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00002364 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002365 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00002366}
2367
Chris Lattner86ee2862008-10-06 06:40:35 +00002368/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2369/// as GCC.
2370static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2371 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002372 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00002373 enum gcc_type_class {
2374 no_type_class = -1,
2375 void_type_class, integer_type_class, char_type_class,
2376 enumeral_type_class, boolean_type_class,
2377 pointer_type_class, reference_type_class, offset_type_class,
2378 real_type_class, complex_type_class,
2379 function_type_class, method_type_class,
2380 record_type_class, union_type_class,
2381 array_type_class, string_type_class,
2382 lang_type_class
2383 };
Mike Stump11289f42009-09-09 15:08:12 +00002384
2385 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00002386 // ideal, however it is what gcc does.
2387 if (E->getNumArgs() == 0)
2388 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00002389
Chris Lattner86ee2862008-10-06 06:40:35 +00002390 QualType ArgTy = E->getArg(0)->getType();
2391 if (ArgTy->isVoidType())
2392 return void_type_class;
2393 else if (ArgTy->isEnumeralType())
2394 return enumeral_type_class;
2395 else if (ArgTy->isBooleanType())
2396 return boolean_type_class;
2397 else if (ArgTy->isCharType())
2398 return string_type_class; // gcc doesn't appear to use char_type_class
2399 else if (ArgTy->isIntegerType())
2400 return integer_type_class;
2401 else if (ArgTy->isPointerType())
2402 return pointer_type_class;
2403 else if (ArgTy->isReferenceType())
2404 return reference_type_class;
2405 else if (ArgTy->isRealType())
2406 return real_type_class;
2407 else if (ArgTy->isComplexType())
2408 return complex_type_class;
2409 else if (ArgTy->isFunctionType())
2410 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00002411 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00002412 return record_type_class;
2413 else if (ArgTy->isUnionType())
2414 return union_type_class;
2415 else if (ArgTy->isArrayType())
2416 return array_type_class;
2417 else if (ArgTy->isUnionType())
2418 return union_type_class;
2419 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00002420 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00002421 return -1;
2422}
2423
John McCall95007602010-05-10 23:27:23 +00002424/// Retrieves the "underlying object type" of the given expression,
2425/// as used by __builtin_object_size.
2426QualType IntExprEvaluator::GetObjectType(const Expr *E) {
2427 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2428 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2429 return VD->getType();
2430 } else if (isa<CompoundLiteralExpr>(E)) {
2431 return E->getType();
2432 }
2433
2434 return QualType();
2435}
2436
Peter Collingbournee9200682011-05-13 03:29:01 +00002437bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00002438 // TODO: Perhaps we should let LLVM lower this?
2439 LValue Base;
2440 if (!EvaluatePointer(E->getArg(0), Base, Info))
2441 return false;
2442
2443 // If we can prove the base is null, lower to zero now.
2444 const Expr *LVBase = Base.getLValueBase();
2445 if (!LVBase) return Success(0, E);
2446
2447 QualType T = GetObjectType(LVBase);
2448 if (T.isNull() ||
2449 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00002450 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00002451 T->isVariablyModifiedType() ||
2452 T->isDependentType())
2453 return false;
2454
2455 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
2456 CharUnits Offset = Base.getLValueOffset();
2457
2458 if (!Offset.isNegative() && Offset <= Size)
2459 Size -= Offset;
2460 else
2461 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00002462 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00002463}
2464
Peter Collingbournee9200682011-05-13 03:29:01 +00002465bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002466 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002467 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00002468 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00002469
2470 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00002471 if (TryEvaluateBuiltinObjectSize(E))
2472 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00002473
Eric Christopher99469702010-01-19 22:58:35 +00002474 // If evaluating the argument has side-effects we can't determine
2475 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002476 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00002477 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00002478 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00002479 return Success(0, E);
2480 }
Mike Stump876387b2009-10-27 22:09:17 +00002481
Mike Stump722cedf2009-10-26 18:35:08 +00002482 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2483 }
2484
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002485 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002486 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00002487
Anders Carlsson4c76e932008-11-24 04:21:33 +00002488 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002489 // __builtin_constant_p always has one operand: it returns true if that
2490 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002491 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00002492
2493 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00002494 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00002495 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00002496 return Success(Operand, E);
2497 }
Eli Friedmand5c93992010-02-13 00:10:10 +00002498
2499 case Builtin::BI__builtin_expect:
2500 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002501
2502 case Builtin::BIstrlen:
2503 case Builtin::BI__builtin_strlen:
2504 // As an extension, we support strlen() and __builtin_strlen() as constant
2505 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00002506 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002507 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2508 // The string literal may have embedded null characters. Find the first
2509 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002510 StringRef Str = S->getString();
2511 StringRef::size_type Pos = Str.find(0);
2512 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00002513 Str = Str.substr(0, Pos);
2514
2515 return Success(Str.size(), E);
2516 }
2517
2518 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00002519
2520 case Builtin::BI__atomic_is_lock_free: {
2521 APSInt SizeVal;
2522 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2523 return false;
2524
2525 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2526 // of two less than the maximum inline atomic width, we know it is
2527 // lock-free. If the size isn't a power of two, or greater than the
2528 // maximum alignment where we promote atomics, we know it is not lock-free
2529 // (at least not in the sense of atomic_is_lock_free). Otherwise,
2530 // the answer can only be determined at runtime; for example, 16-byte
2531 // atomics have lock-free implementations on some, but not all,
2532 // x86-64 processors.
2533
2534 // Check power-of-two.
2535 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2536 if (!Size.isPowerOfTwo())
2537#if 0
2538 // FIXME: Suppress this folding until the ABI for the promotion width
2539 // settles.
2540 return Success(0, E);
2541#else
2542 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2543#endif
2544
2545#if 0
2546 // Check against promotion width.
2547 // FIXME: Suppress this folding until the ABI for the promotion width
2548 // settles.
2549 unsigned PromoteWidthBits =
2550 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2551 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2552 return Success(0, E);
2553#endif
2554
2555 // Check against inlining width.
2556 unsigned InlineWidthBits =
2557 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2558 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2559 return Success(1, E);
2560
2561 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2562 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002563 }
Chris Lattner7174bf32008-07-12 00:38:25 +00002564}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002565
Richard Smith8b3497e2011-10-31 01:37:14 +00002566static bool HasSameBase(const LValue &A, const LValue &B) {
2567 if (!A.getLValueBase())
2568 return !B.getLValueBase();
2569 if (!B.getLValueBase())
2570 return false;
2571
2572 if (A.getLValueBase() != B.getLValueBase()) {
2573 const Decl *ADecl = GetLValueBaseDecl(A);
2574 if (!ADecl)
2575 return false;
2576 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00002577 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00002578 return false;
2579 }
2580
2581 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00002582 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00002583}
2584
Chris Lattnere13042c2008-07-11 19:10:17 +00002585bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002586 if (E->isAssignmentOp())
2587 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2588
John McCalle3027922010-08-25 11:45:40 +00002589 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002590 VisitIgnoredValue(E->getLHS());
2591 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00002592 }
2593
2594 if (E->isLogicalOp()) {
2595 // These need to be handled specially because the operands aren't
2596 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002597 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00002598
Richard Smith11562c52011-10-28 17:51:58 +00002599 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00002600 // We were able to evaluate the LHS, see if we can get away with not
2601 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00002602 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002603 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002604
Richard Smith11562c52011-10-28 17:51:58 +00002605 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00002606 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002607 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002608 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002609 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002610 }
2611 } else {
Richard Smith11562c52011-10-28 17:51:58 +00002612 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00002613 // We can't evaluate the LHS; however, sometimes the result
2614 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00002615 if (rhsResult == (E->getOpcode() == BO_LOr) ||
2616 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002617 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00002618 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00002619 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002620
2621 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00002622 }
2623 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00002624 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00002625
Eli Friedman5a332ea2008-11-13 06:09:17 +00002626 return false;
2627 }
2628
Anders Carlssonacc79812008-11-16 07:17:21 +00002629 QualType LHSTy = E->getLHS()->getType();
2630 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002631
2632 if (LHSTy->isAnyComplexType()) {
2633 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00002634 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002635
2636 if (!EvaluateComplex(E->getLHS(), LHS, Info))
2637 return false;
2638
2639 if (!EvaluateComplex(E->getRHS(), RHS, Info))
2640 return false;
2641
2642 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00002643 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002644 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00002645 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002646 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2647
John McCalle3027922010-08-25 11:45:40 +00002648 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002649 return Success((CR_r == APFloat::cmpEqual &&
2650 CR_i == APFloat::cmpEqual), E);
2651 else {
John McCalle3027922010-08-25 11:45:40 +00002652 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002653 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00002654 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002655 CR_r == APFloat::cmpLessThan ||
2656 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00002657 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00002658 CR_i == APFloat::cmpLessThan ||
2659 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002660 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002661 } else {
John McCalle3027922010-08-25 11:45:40 +00002662 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002663 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2664 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2665 else {
John McCalle3027922010-08-25 11:45:40 +00002666 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002667 "Invalid compex comparison.");
2668 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2669 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2670 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00002671 }
2672 }
Mike Stump11289f42009-09-09 15:08:12 +00002673
Anders Carlssonacc79812008-11-16 07:17:21 +00002674 if (LHSTy->isRealFloatingType() &&
2675 RHSTy->isRealFloatingType()) {
2676 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00002677
Anders Carlssonacc79812008-11-16 07:17:21 +00002678 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2679 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002680
Anders Carlssonacc79812008-11-16 07:17:21 +00002681 if (!EvaluateFloat(E->getLHS(), LHS, Info))
2682 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002683
Anders Carlssonacc79812008-11-16 07:17:21 +00002684 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00002685
Anders Carlssonacc79812008-11-16 07:17:21 +00002686 switch (E->getOpcode()) {
2687 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002688 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00002689 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002690 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00002691 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002692 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00002693 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002694 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002695 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00002696 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002697 E);
John McCalle3027922010-08-25 11:45:40 +00002698 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002699 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00002700 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00002701 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00002702 || CR == APFloat::cmpLessThan
2703 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00002704 }
Anders Carlssonacc79812008-11-16 07:17:21 +00002705 }
Mike Stump11289f42009-09-09 15:08:12 +00002706
Eli Friedmana38da572009-04-28 19:17:36 +00002707 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00002708 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00002709 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002710 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2711 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002712
John McCall45d55e42010-05-07 21:00:08 +00002713 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002714 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2715 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002716
Richard Smith8b3497e2011-10-31 01:37:14 +00002717 // Reject differing bases from the normal codepath; we special-case
2718 // comparisons to null.
2719 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00002720 // Inequalities and subtractions between unrelated pointers have
2721 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00002722 if (!E->isEqualityOp())
2723 return false;
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002724 // A constant address may compare equal to the address of a symbol.
2725 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00002726 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00002727 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2728 (!RHSValue.Base && !RHSValue.Offset.isZero()))
2729 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002730 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00002731 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00002732 // distinct. However, we do know that the address of a literal will be
2733 // non-null.
2734 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2735 LHSValue.Base && RHSValue.Base)
Eli Friedman334046a2009-06-14 02:17:33 +00002736 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002737 // We can't tell whether weak symbols will end up pointing to the same
2738 // object.
2739 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman334046a2009-06-14 02:17:33 +00002740 return false;
Richard Smith83c68212011-10-31 05:11:32 +00002741 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00002742 // (Note that clang defaults to -fmerge-all-constants, which can
2743 // lead to inconsistent results for comparisons involving the address
2744 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00002745 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00002746 }
Eli Friedman64004332009-03-23 04:38:34 +00002747
Richard Smithf3e9e432011-11-07 09:22:26 +00002748 // FIXME: Implement the C++11 restrictions:
2749 // - Pointer subtractions must be on elements of the same array.
2750 // - Pointer comparisons must be between members with the same access.
2751
John McCalle3027922010-08-25 11:45:40 +00002752 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00002753 QualType Type = E->getLHS()->getType();
2754 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002755
Richard Smithd62306a2011-11-10 06:34:14 +00002756 CharUnits ElementSize;
2757 if (!HandleSizeof(Info, ElementType, ElementSize))
2758 return false;
Eli Friedman64004332009-03-23 04:38:34 +00002759
Richard Smithd62306a2011-11-10 06:34:14 +00002760 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00002761 RHSValue.getLValueOffset();
2762 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002763 }
Richard Smith8b3497e2011-10-31 01:37:14 +00002764
2765 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2766 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2767 switch (E->getOpcode()) {
2768 default: llvm_unreachable("missing comparison operator");
2769 case BO_LT: return Success(LHSOffset < RHSOffset, E);
2770 case BO_GT: return Success(LHSOffset > RHSOffset, E);
2771 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2772 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2773 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2774 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00002775 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002776 }
2777 }
Douglas Gregorb90df602010-06-16 00:17:44 +00002778 if (!LHSTy->isIntegralOrEnumerationType() ||
2779 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00002780 // We can't continue from here for non-integral types, and they
2781 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00002782 return false;
2783 }
2784
Anders Carlsson9c181652008-07-08 14:35:21 +00002785 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002786 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00002787 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00002788 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00002789
Richard Smith11562c52011-10-28 17:51:58 +00002790 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002791 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002792 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00002793
2794 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00002795 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00002796 CharUnits AdditionalOffset = CharUnits::fromQuantity(
2797 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00002798 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00002799 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00002800 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00002801 LHSVal.getLValueOffset() -= AdditionalOffset;
2802 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00002803 return true;
2804 }
2805
2806 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00002807 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00002808 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002809 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2810 LHSVal.getInt().getZExtValue());
2811 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00002812 return true;
2813 }
2814
2815 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00002816 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00002817 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00002818
Richard Smith11562c52011-10-28 17:51:58 +00002819 APSInt &LHS = LHSVal.getInt();
2820 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00002821
Anders Carlsson9c181652008-07-08 14:35:21 +00002822 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002823 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002824 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00002825 case BO_Mul: return Success(LHS * RHS, E);
2826 case BO_Add: return Success(LHS + RHS, E);
2827 case BO_Sub: return Success(LHS - RHS, E);
2828 case BO_And: return Success(LHS & RHS, E);
2829 case BO_Xor: return Success(LHS ^ RHS, E);
2830 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002831 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00002832 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002833 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002834 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002835 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00002836 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00002837 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00002838 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00002839 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00002840 // During constant-folding, a negative shift is an opposite shift.
2841 if (RHS.isSigned() && RHS.isNegative()) {
2842 RHS = -RHS;
2843 goto shift_right;
2844 }
2845
2846 shift_left:
2847 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00002848 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2849 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002850 }
John McCalle3027922010-08-25 11:45:40 +00002851 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00002852 // During constant-folding, a negative shift is an opposite shift.
2853 if (RHS.isSigned() && RHS.isNegative()) {
2854 RHS = -RHS;
2855 goto shift_left;
2856 }
2857
2858 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00002859 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00002860 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2861 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002862 }
Mike Stump11289f42009-09-09 15:08:12 +00002863
Richard Smith11562c52011-10-28 17:51:58 +00002864 case BO_LT: return Success(LHS < RHS, E);
2865 case BO_GT: return Success(LHS > RHS, E);
2866 case BO_LE: return Success(LHS <= RHS, E);
2867 case BO_GE: return Success(LHS >= RHS, E);
2868 case BO_EQ: return Success(LHS == RHS, E);
2869 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00002870 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002871}
2872
Ken Dyck160146e2010-01-27 17:10:57 +00002873CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002874 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2875 // the result is the size of the referenced type."
2876 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2877 // result shall be the alignment of the referenced type."
2878 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2879 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00002880
2881 // __alignof is defined to return the preferred alignment.
2882 return Info.Ctx.toCharUnitsFromBits(
2883 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00002884}
2885
Ken Dyck160146e2010-01-27 17:10:57 +00002886CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00002887 E = E->IgnoreParens();
2888
2889 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00002890 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00002891 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002892 return Info.Ctx.getDeclAlign(DRE->getDecl(),
2893 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00002894
Chris Lattner68061312009-01-24 21:53:27 +00002895 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00002896 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2897 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00002898
Chris Lattner24aeeab2009-01-24 21:09:06 +00002899 return GetAlignOfType(E->getType());
2900}
2901
2902
Peter Collingbournee190dee2011-03-11 19:24:49 +00002903/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2904/// a result as the expression's type.
2905bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2906 const UnaryExprOrTypeTraitExpr *E) {
2907 switch(E->getKind()) {
2908 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00002909 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00002910 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002911 else
Ken Dyckdbc01912011-03-11 02:13:43 +00002912 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00002913 }
Eli Friedman64004332009-03-23 04:38:34 +00002914
Peter Collingbournee190dee2011-03-11 19:24:49 +00002915 case UETT_VecStep: {
2916 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00002917
Peter Collingbournee190dee2011-03-11 19:24:49 +00002918 if (Ty->isVectorType()) {
2919 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00002920
Peter Collingbournee190dee2011-03-11 19:24:49 +00002921 // The vec_step built-in functions that take a 3-component
2922 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2923 if (n == 3)
2924 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002925
Peter Collingbournee190dee2011-03-11 19:24:49 +00002926 return Success(n, E);
2927 } else
2928 return Success(1, E);
2929 }
2930
2931 case UETT_SizeOf: {
2932 QualType SrcTy = E->getTypeOfArgument();
2933 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2934 // the result is the size of the referenced type."
2935 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2936 // result shall be the alignment of the referenced type."
2937 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
2938 SrcTy = Ref->getPointeeType();
2939
Richard Smithd62306a2011-11-10 06:34:14 +00002940 CharUnits Sizeof;
2941 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00002942 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002943 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002944 }
2945 }
2946
2947 llvm_unreachable("unknown expr/type trait");
2948 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002949}
2950
Peter Collingbournee9200682011-05-13 03:29:01 +00002951bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00002952 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00002953 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00002954 if (n == 0)
2955 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002956 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00002957 for (unsigned i = 0; i != n; ++i) {
2958 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
2959 switch (ON.getKind()) {
2960 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00002961 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00002962 APSInt IdxResult;
2963 if (!EvaluateInteger(Idx, IdxResult, Info))
2964 return false;
2965 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
2966 if (!AT)
2967 return false;
2968 CurrentType = AT->getElementType();
2969 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
2970 Result += IdxResult.getSExtValue() * ElementSize;
2971 break;
2972 }
2973
2974 case OffsetOfExpr::OffsetOfNode::Field: {
2975 FieldDecl *MemberDecl = ON.getField();
2976 const RecordType *RT = CurrentType->getAs<RecordType>();
2977 if (!RT)
2978 return false;
2979 RecordDecl *RD = RT->getDecl();
2980 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00002981 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00002982 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002983 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00002984 CurrentType = MemberDecl->getType().getNonReferenceType();
2985 break;
2986 }
2987
2988 case OffsetOfExpr::OffsetOfNode::Identifier:
2989 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00002990 return false;
2991
2992 case OffsetOfExpr::OffsetOfNode::Base: {
2993 CXXBaseSpecifier *BaseSpec = ON.getBase();
2994 if (BaseSpec->isVirtual())
2995 return false;
2996
2997 // Find the layout of the class whose base we are looking into.
2998 const RecordType *RT = CurrentType->getAs<RecordType>();
2999 if (!RT)
3000 return false;
3001 RecordDecl *RD = RT->getDecl();
3002 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3003
3004 // Find the base class itself.
3005 CurrentType = BaseSpec->getType();
3006 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3007 if (!BaseRT)
3008 return false;
3009
3010 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003011 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003012 break;
3013 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003014 }
3015 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003016 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003017}
3018
Chris Lattnere13042c2008-07-11 19:10:17 +00003019bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003020 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003021 // LNot's operand isn't necessarily an integer, so we handle it specially.
3022 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003023 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003024 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003025 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003026 }
3027
Daniel Dunbar79e042a2009-02-21 18:14:20 +00003028 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00003029 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00003030 return false;
3031
Richard Smith11562c52011-10-28 17:51:58 +00003032 // Get the operand value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003033 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +00003034 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00003035 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00003036
Chris Lattnerf09ad162008-07-11 22:15:16 +00003037 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00003038 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00003039 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3040 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00003041 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00003042 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00003043 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3044 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00003045 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00003046 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00003047 // The result is just the value.
3048 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00003049 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00003050 if (!Val.isInt()) return false;
3051 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00003052 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00003053 if (!Val.isInt()) return false;
3054 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00003055 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003056}
Mike Stump11289f42009-09-09 15:08:12 +00003057
Chris Lattner477c4be2008-07-12 01:15:53 +00003058/// HandleCast - This is used to evaluate implicit or explicit casts where the
3059/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003060bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3061 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003062 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003063 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003064
Eli Friedmanc757de22011-03-25 00:43:55 +00003065 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003066 case CK_BaseToDerived:
3067 case CK_DerivedToBase:
3068 case CK_UncheckedDerivedToBase:
3069 case CK_Dynamic:
3070 case CK_ToUnion:
3071 case CK_ArrayToPointerDecay:
3072 case CK_FunctionToPointerDecay:
3073 case CK_NullToPointer:
3074 case CK_NullToMemberPointer:
3075 case CK_BaseToDerivedMemberPointer:
3076 case CK_DerivedToBaseMemberPointer:
3077 case CK_ConstructorConversion:
3078 case CK_IntegralToPointer:
3079 case CK_ToVoid:
3080 case CK_VectorSplat:
3081 case CK_IntegralToFloating:
3082 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003083 case CK_CPointerToObjCPointerCast:
3084 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003085 case CK_AnyPointerToBlockPointerCast:
3086 case CK_ObjCObjectLValueCast:
3087 case CK_FloatingRealToComplex:
3088 case CK_FloatingComplexToReal:
3089 case CK_FloatingComplexCast:
3090 case CK_FloatingComplexToIntegralComplex:
3091 case CK_IntegralRealToComplex:
3092 case CK_IntegralComplexCast:
3093 case CK_IntegralComplexToFloatingComplex:
3094 llvm_unreachable("invalid cast kind for integral value");
3095
Eli Friedman9faf2f92011-03-25 19:07:11 +00003096 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003097 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003098 case CK_LValueBitCast:
3099 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00003100 case CK_ARCProduceObject:
3101 case CK_ARCConsumeObject:
3102 case CK_ARCReclaimReturnedObject:
3103 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00003104 return false;
3105
3106 case CK_LValueToRValue:
3107 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003108 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003109
3110 case CK_MemberPointerToBoolean:
3111 case CK_PointerToBoolean:
3112 case CK_IntegralToBoolean:
3113 case CK_FloatingToBoolean:
3114 case CK_FloatingComplexToBoolean:
3115 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003116 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00003117 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003118 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003119 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003120 }
3121
Eli Friedmanc757de22011-03-25 00:43:55 +00003122 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00003123 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00003124 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003125
Eli Friedman742421e2009-02-20 01:15:07 +00003126 if (!Result.isInt()) {
3127 // Only allow casts of lvalues if they are lossless.
3128 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3129 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003130
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003131 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003132 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00003133 }
Mike Stump11289f42009-09-09 15:08:12 +00003134
Eli Friedmanc757de22011-03-25 00:43:55 +00003135 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00003136 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00003137 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00003138 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003139
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003140 if (LV.getLValueBase()) {
3141 // Only allow based lvalue casts if they are lossless.
3142 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3143 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003144
John McCall45d55e42010-05-07 21:00:08 +00003145 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003146 return true;
3147 }
3148
Ken Dyck02990832010-01-15 12:37:54 +00003149 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3150 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003151 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003152 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003153
Eli Friedmanc757de22011-03-25 00:43:55 +00003154 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00003155 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003156 if (!EvaluateComplex(SubExpr, C, Info))
3157 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00003158 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003159 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00003160
Eli Friedmanc757de22011-03-25 00:43:55 +00003161 case CK_FloatingToIntegral: {
3162 APFloat F(0.0);
3163 if (!EvaluateFloat(SubExpr, F, Info))
3164 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00003165
Eli Friedmanc757de22011-03-25 00:43:55 +00003166 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3167 }
3168 }
Mike Stump11289f42009-09-09 15:08:12 +00003169
Eli Friedmanc757de22011-03-25 00:43:55 +00003170 llvm_unreachable("unknown cast resulting in integral value");
3171 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00003172}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003173
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003174bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3175 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003176 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003177 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3178 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3179 return Success(LV.getComplexIntReal(), E);
3180 }
3181
3182 return Visit(E->getSubExpr());
3183}
3184
Eli Friedman4e7a2412009-02-27 04:45:43 +00003185bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003186 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003187 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003188 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3189 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3190 return Success(LV.getComplexIntImag(), E);
3191 }
3192
Richard Smith4a678122011-10-24 18:44:57 +00003193 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00003194 return Success(0, E);
3195}
3196
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003197bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3198 return Success(E->getPackLength(), E);
3199}
3200
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003201bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3202 return Success(E->getValue(), E);
3203}
3204
Chris Lattner05706e882008-07-11 18:11:29 +00003205//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00003206// Float Evaluation
3207//===----------------------------------------------------------------------===//
3208
3209namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003210class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003211 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00003212 APFloat &Result;
3213public:
3214 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003215 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00003216
Richard Smith0b0a0b62011-10-29 20:57:55 +00003217 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003218 Result = V.getFloat();
3219 return true;
3220 }
3221 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00003222 return false;
3223 }
3224
Richard Smith4ce706a2011-10-11 21:43:33 +00003225 bool ValueInitialization(const Expr *E) {
3226 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3227 return true;
3228 }
3229
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003230 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003231
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003232 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003233 bool VisitBinaryOperator(const BinaryOperator *E);
3234 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003235 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00003236
John McCallb1fb0d32010-05-07 22:08:54 +00003237 bool VisitUnaryReal(const UnaryOperator *E);
3238 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00003239
John McCallb1fb0d32010-05-07 22:08:54 +00003240 // FIXME: Missing: array subscript of vector, member of vector,
3241 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00003242};
3243} // end anonymous namespace
3244
3245static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003246 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003247 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00003248}
3249
Jay Foad39c79802011-01-12 09:06:06 +00003250static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00003251 QualType ResultTy,
3252 const Expr *Arg,
3253 bool SNaN,
3254 llvm::APFloat &Result) {
3255 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3256 if (!S) return false;
3257
3258 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3259
3260 llvm::APInt fill;
3261
3262 // Treat empty strings as if they were zero.
3263 if (S->getString().empty())
3264 fill = llvm::APInt(32, 0);
3265 else if (S->getString().getAsInteger(0, fill))
3266 return false;
3267
3268 if (SNaN)
3269 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3270 else
3271 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3272 return true;
3273}
3274
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003275bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003276 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003277 default:
3278 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3279
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003280 case Builtin::BI__builtin_huge_val:
3281 case Builtin::BI__builtin_huge_valf:
3282 case Builtin::BI__builtin_huge_vall:
3283 case Builtin::BI__builtin_inf:
3284 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003285 case Builtin::BI__builtin_infl: {
3286 const llvm::fltSemantics &Sem =
3287 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00003288 Result = llvm::APFloat::getInf(Sem);
3289 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003290 }
Mike Stump11289f42009-09-09 15:08:12 +00003291
John McCall16291492010-02-28 13:00:19 +00003292 case Builtin::BI__builtin_nans:
3293 case Builtin::BI__builtin_nansf:
3294 case Builtin::BI__builtin_nansl:
3295 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3296 true, Result);
3297
Chris Lattner0b7282e2008-10-06 06:31:58 +00003298 case Builtin::BI__builtin_nan:
3299 case Builtin::BI__builtin_nanf:
3300 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00003301 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00003302 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00003303 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3304 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003305
3306 case Builtin::BI__builtin_fabs:
3307 case Builtin::BI__builtin_fabsf:
3308 case Builtin::BI__builtin_fabsl:
3309 if (!EvaluateFloat(E->getArg(0), Result, Info))
3310 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003311
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003312 if (Result.isNegative())
3313 Result.changeSign();
3314 return true;
3315
Mike Stump11289f42009-09-09 15:08:12 +00003316 case Builtin::BI__builtin_copysign:
3317 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003318 case Builtin::BI__builtin_copysignl: {
3319 APFloat RHS(0.);
3320 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3321 !EvaluateFloat(E->getArg(1), RHS, Info))
3322 return false;
3323 Result.copySign(RHS);
3324 return true;
3325 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003326 }
3327}
3328
John McCallb1fb0d32010-05-07 22:08:54 +00003329bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00003330 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3331 ComplexValue CV;
3332 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3333 return false;
3334 Result = CV.FloatReal;
3335 return true;
3336 }
3337
3338 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00003339}
3340
3341bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00003342 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3343 ComplexValue CV;
3344 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3345 return false;
3346 Result = CV.FloatImag;
3347 return true;
3348 }
3349
Richard Smith4a678122011-10-24 18:44:57 +00003350 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00003351 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3352 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00003353 return true;
3354}
3355
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003356bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003357 switch (E->getOpcode()) {
3358 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003359 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00003360 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00003361 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00003362 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3363 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003364 Result.changeSign();
3365 return true;
3366 }
3367}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003368
Eli Friedman24c01542008-08-22 00:06:13 +00003369bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003370 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003371 VisitIgnoredValue(E->getLHS());
3372 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00003373 }
3374
Richard Smith472d4952011-10-28 23:26:52 +00003375 // We can't evaluate pointer-to-member operations or assignments.
3376 if (E->isPtrMemOp() || E->isAssignmentOp())
Anders Carlssona5df61a2010-10-31 01:21:47 +00003377 return false;
3378
Eli Friedman24c01542008-08-22 00:06:13 +00003379 // FIXME: Diagnostics? I really don't understand how the warnings
3380 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003381 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00003382 if (!EvaluateFloat(E->getLHS(), Result, Info))
3383 return false;
3384 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3385 return false;
3386
3387 switch (E->getOpcode()) {
3388 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003389 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00003390 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3391 return true;
John McCalle3027922010-08-25 11:45:40 +00003392 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00003393 Result.add(RHS, APFloat::rmNearestTiesToEven);
3394 return true;
John McCalle3027922010-08-25 11:45:40 +00003395 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00003396 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3397 return true;
John McCalle3027922010-08-25 11:45:40 +00003398 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00003399 Result.divide(RHS, APFloat::rmNearestTiesToEven);
3400 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00003401 }
3402}
3403
3404bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3405 Result = E->getValue();
3406 return true;
3407}
3408
Peter Collingbournee9200682011-05-13 03:29:01 +00003409bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
3410 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00003411
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00003412 switch (E->getCastKind()) {
3413 default:
Richard Smith11562c52011-10-28 17:51:58 +00003414 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00003415
3416 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003417 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003418 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003419 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003420 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003421 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00003422 return true;
3423 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00003424
3425 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003426 if (!Visit(SubExpr))
3427 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003428 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
3429 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00003430 return true;
3431 }
John McCalld7646252010-11-14 08:17:51 +00003432
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00003433 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00003434 ComplexValue V;
3435 if (!EvaluateComplex(SubExpr, V, Info))
3436 return false;
3437 Result = V.getComplexFloatReal();
3438 return true;
3439 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00003440 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003441
3442 return false;
3443}
3444
Eli Friedman24c01542008-08-22 00:06:13 +00003445//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003446// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00003447//===----------------------------------------------------------------------===//
3448
3449namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003450class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003451 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00003452 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00003453
Anders Carlsson537969c2008-11-16 20:27:53 +00003454public:
John McCall93d91dc2010-05-07 17:22:02 +00003455 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003456 : ExprEvaluatorBaseTy(info), Result(Result) {}
3457
Richard Smith0b0a0b62011-10-29 20:57:55 +00003458 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003459 Result.setFrom(V);
3460 return true;
3461 }
3462 bool Error(const Expr *E) {
3463 return false;
3464 }
Mike Stump11289f42009-09-09 15:08:12 +00003465
Anders Carlsson537969c2008-11-16 20:27:53 +00003466 //===--------------------------------------------------------------------===//
3467 // Visitor Methods
3468 //===--------------------------------------------------------------------===//
3469
Peter Collingbournee9200682011-05-13 03:29:01 +00003470 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00003471
Peter Collingbournee9200682011-05-13 03:29:01 +00003472 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003473
John McCall93d91dc2010-05-07 17:22:02 +00003474 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003475 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00003476 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00003477};
3478} // end anonymous namespace
3479
John McCall93d91dc2010-05-07 17:22:02 +00003480static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3481 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003482 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003483 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00003484}
3485
Peter Collingbournee9200682011-05-13 03:29:01 +00003486bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3487 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003488
3489 if (SubExpr->getType()->isRealFloatingType()) {
3490 Result.makeComplexFloat();
3491 APFloat &Imag = Result.FloatImag;
3492 if (!EvaluateFloat(SubExpr, Imag, Info))
3493 return false;
3494
3495 Result.FloatReal = APFloat(Imag.getSemantics());
3496 return true;
3497 } else {
3498 assert(SubExpr->getType()->isIntegerType() &&
3499 "Unexpected imaginary literal.");
3500
3501 Result.makeComplexInt();
3502 APSInt &Imag = Result.IntImag;
3503 if (!EvaluateInteger(SubExpr, Imag, Info))
3504 return false;
3505
3506 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3507 return true;
3508 }
3509}
3510
Peter Collingbournee9200682011-05-13 03:29:01 +00003511bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003512
John McCallfcef3cf2010-12-14 17:51:41 +00003513 switch (E->getCastKind()) {
3514 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003515 case CK_BaseToDerived:
3516 case CK_DerivedToBase:
3517 case CK_UncheckedDerivedToBase:
3518 case CK_Dynamic:
3519 case CK_ToUnion:
3520 case CK_ArrayToPointerDecay:
3521 case CK_FunctionToPointerDecay:
3522 case CK_NullToPointer:
3523 case CK_NullToMemberPointer:
3524 case CK_BaseToDerivedMemberPointer:
3525 case CK_DerivedToBaseMemberPointer:
3526 case CK_MemberPointerToBoolean:
3527 case CK_ConstructorConversion:
3528 case CK_IntegralToPointer:
3529 case CK_PointerToIntegral:
3530 case CK_PointerToBoolean:
3531 case CK_ToVoid:
3532 case CK_VectorSplat:
3533 case CK_IntegralCast:
3534 case CK_IntegralToBoolean:
3535 case CK_IntegralToFloating:
3536 case CK_FloatingToIntegral:
3537 case CK_FloatingToBoolean:
3538 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003539 case CK_CPointerToObjCPointerCast:
3540 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003541 case CK_AnyPointerToBlockPointerCast:
3542 case CK_ObjCObjectLValueCast:
3543 case CK_FloatingComplexToReal:
3544 case CK_FloatingComplexToBoolean:
3545 case CK_IntegralComplexToReal:
3546 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00003547 case CK_ARCProduceObject:
3548 case CK_ARCConsumeObject:
3549 case CK_ARCReclaimReturnedObject:
3550 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00003551 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00003552
John McCallfcef3cf2010-12-14 17:51:41 +00003553 case CK_LValueToRValue:
3554 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003555 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00003556
3557 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003558 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00003559 case CK_UserDefinedConversion:
3560 return false;
3561
3562 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003563 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00003564 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003565 return false;
3566
John McCallfcef3cf2010-12-14 17:51:41 +00003567 Result.makeComplexFloat();
3568 Result.FloatImag = APFloat(Real.getSemantics());
3569 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003570 }
3571
John McCallfcef3cf2010-12-14 17:51:41 +00003572 case CK_FloatingComplexCast: {
3573 if (!Visit(E->getSubExpr()))
3574 return false;
3575
3576 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3577 QualType From
3578 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3579
3580 Result.FloatReal
3581 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3582 Result.FloatImag
3583 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3584 return true;
3585 }
3586
3587 case CK_FloatingComplexToIntegralComplex: {
3588 if (!Visit(E->getSubExpr()))
3589 return false;
3590
3591 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3592 QualType From
3593 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3594 Result.makeComplexInt();
3595 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3596 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3597 return true;
3598 }
3599
3600 case CK_IntegralRealToComplex: {
3601 APSInt &Real = Result.IntReal;
3602 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3603 return false;
3604
3605 Result.makeComplexInt();
3606 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3607 return true;
3608 }
3609
3610 case CK_IntegralComplexCast: {
3611 if (!Visit(E->getSubExpr()))
3612 return false;
3613
3614 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3615 QualType From
3616 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3617
3618 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3619 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3620 return true;
3621 }
3622
3623 case CK_IntegralComplexToFloatingComplex: {
3624 if (!Visit(E->getSubExpr()))
3625 return false;
3626
3627 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3628 QualType From
3629 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3630 Result.makeComplexFloat();
3631 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3632 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3633 return true;
3634 }
3635 }
3636
3637 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00003638 return false;
3639}
3640
John McCall93d91dc2010-05-07 17:22:02 +00003641bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003642 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003643 VisitIgnoredValue(E->getLHS());
3644 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003645 }
John McCall93d91dc2010-05-07 17:22:02 +00003646 if (!Visit(E->getLHS()))
3647 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003648
John McCall93d91dc2010-05-07 17:22:02 +00003649 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003650 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00003651 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003652
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003653 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3654 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003655 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00003656 default: return false;
John McCalle3027922010-08-25 11:45:40 +00003657 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003658 if (Result.isComplexFloat()) {
3659 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3660 APFloat::rmNearestTiesToEven);
3661 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3662 APFloat::rmNearestTiesToEven);
3663 } else {
3664 Result.getComplexIntReal() += RHS.getComplexIntReal();
3665 Result.getComplexIntImag() += RHS.getComplexIntImag();
3666 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003667 break;
John McCalle3027922010-08-25 11:45:40 +00003668 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003669 if (Result.isComplexFloat()) {
3670 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3671 APFloat::rmNearestTiesToEven);
3672 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3673 APFloat::rmNearestTiesToEven);
3674 } else {
3675 Result.getComplexIntReal() -= RHS.getComplexIntReal();
3676 Result.getComplexIntImag() -= RHS.getComplexIntImag();
3677 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003678 break;
John McCalle3027922010-08-25 11:45:40 +00003679 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003680 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00003681 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003682 APFloat &LHS_r = LHS.getComplexFloatReal();
3683 APFloat &LHS_i = LHS.getComplexFloatImag();
3684 APFloat &RHS_r = RHS.getComplexFloatReal();
3685 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00003686
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003687 APFloat Tmp = LHS_r;
3688 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3689 Result.getComplexFloatReal() = Tmp;
3690 Tmp = LHS_i;
3691 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3692 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3693
3694 Tmp = LHS_r;
3695 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3696 Result.getComplexFloatImag() = Tmp;
3697 Tmp = LHS_i;
3698 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3699 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3700 } else {
John McCall93d91dc2010-05-07 17:22:02 +00003701 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00003702 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003703 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3704 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00003705 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00003706 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3707 LHS.getComplexIntImag() * RHS.getComplexIntReal());
3708 }
3709 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003710 case BO_Div:
3711 if (Result.isComplexFloat()) {
3712 ComplexValue LHS = Result;
3713 APFloat &LHS_r = LHS.getComplexFloatReal();
3714 APFloat &LHS_i = LHS.getComplexFloatImag();
3715 APFloat &RHS_r = RHS.getComplexFloatReal();
3716 APFloat &RHS_i = RHS.getComplexFloatImag();
3717 APFloat &Res_r = Result.getComplexFloatReal();
3718 APFloat &Res_i = Result.getComplexFloatImag();
3719
3720 APFloat Den = RHS_r;
3721 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3722 APFloat Tmp = RHS_i;
3723 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3724 Den.add(Tmp, APFloat::rmNearestTiesToEven);
3725
3726 Res_r = LHS_r;
3727 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3728 Tmp = LHS_i;
3729 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3730 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3731 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3732
3733 Res_i = LHS_i;
3734 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3735 Tmp = LHS_r;
3736 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3737 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3738 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3739 } else {
3740 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3741 // FIXME: what about diagnostics?
3742 return false;
3743 }
3744 ComplexValue LHS = Result;
3745 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3746 RHS.getComplexIntImag() * RHS.getComplexIntImag();
3747 Result.getComplexIntReal() =
3748 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3749 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3750 Result.getComplexIntImag() =
3751 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3752 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3753 }
3754 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003755 }
3756
John McCall93d91dc2010-05-07 17:22:02 +00003757 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00003758}
3759
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00003760bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3761 // Get the operand value into 'Result'.
3762 if (!Visit(E->getSubExpr()))
3763 return false;
3764
3765 switch (E->getOpcode()) {
3766 default:
3767 // FIXME: what about diagnostics?
3768 return false;
3769 case UO_Extension:
3770 return true;
3771 case UO_Plus:
3772 // The result is always just the subexpr.
3773 return true;
3774 case UO_Minus:
3775 if (Result.isComplexFloat()) {
3776 Result.getComplexFloatReal().changeSign();
3777 Result.getComplexFloatImag().changeSign();
3778 }
3779 else {
3780 Result.getComplexIntReal() = -Result.getComplexIntReal();
3781 Result.getComplexIntImag() = -Result.getComplexIntImag();
3782 }
3783 return true;
3784 case UO_Not:
3785 if (Result.isComplexFloat())
3786 Result.getComplexFloatImag().changeSign();
3787 else
3788 Result.getComplexIntImag() = -Result.getComplexIntImag();
3789 return true;
3790 }
3791}
3792
Anders Carlsson537969c2008-11-16 20:27:53 +00003793//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00003794// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00003795//===----------------------------------------------------------------------===//
3796
Richard Smith0b0a0b62011-10-29 20:57:55 +00003797static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003798 // In C, function designators are not lvalues, but we evaluate them as if they
3799 // are.
3800 if (E->isGLValue() || E->getType()->isFunctionType()) {
3801 LValue LV;
3802 if (!EvaluateLValue(E, LV, Info))
3803 return false;
3804 LV.moveInto(Result);
3805 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003806 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003807 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003808 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00003809 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003810 return false;
John McCall45d55e42010-05-07 21:00:08 +00003811 } else if (E->getType()->hasPointerRepresentation()) {
3812 LValue LV;
3813 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003814 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003815 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00003816 } else if (E->getType()->isRealFloatingType()) {
3817 llvm::APFloat F(0.0);
3818 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003819 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003820 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00003821 } else if (E->getType()->isAnyComplexType()) {
3822 ComplexValue C;
3823 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003824 return false;
Richard Smith725810a2011-10-16 21:26:27 +00003825 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00003826 } else if (E->getType()->isMemberPointerType()) {
3827 // FIXME: Implement evaluation of pointer-to-member types.
3828 return false;
3829 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003830 LValue LV;
3831 LV.setExpr(E, Info.CurrentCall);
3832 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00003833 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003834 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00003835 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00003836 LValue LV;
3837 LV.setExpr(E, Info.CurrentCall);
3838 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
3839 return false;
3840 Result = Info.CurrentCall->Temporaries[E];
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00003841 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00003842 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00003843
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00003844 return true;
3845}
3846
Richard Smithed5165f2011-11-04 05:33:44 +00003847/// EvaluateConstantExpression - Evaluate an expression as a constant expression
3848/// in-place in an APValue. In some cases, the in-place evaluation is essential,
3849/// since later initializers for an object can indirectly refer to subobjects
3850/// which were initialized earlier.
3851static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00003852 const LValue &This, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003853 if (E->isRValue() && E->getType()->isLiteralType()) {
3854 // Evaluate arrays and record types in-place, so that later initializers can
3855 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00003856 if (E->getType()->isArrayType())
3857 return EvaluateArray(E, This, Result, Info);
3858 else if (E->getType()->isRecordType())
3859 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00003860 }
3861
3862 // For any other type, in-place evaluation is unimportant.
3863 CCValue CoreConstResult;
3864 return Evaluate(CoreConstResult, Info, E) &&
3865 CheckConstantExpression(CoreConstResult, Result);
3866}
3867
Richard Smith11562c52011-10-28 17:51:58 +00003868
Richard Smith7b553f12011-10-29 00:50:52 +00003869/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00003870/// any crazy technique (that has nothing to do with language standards) that
3871/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00003872/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3873/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00003874bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith5686e752011-11-10 03:30:42 +00003875 // FIXME: Evaluating initializers for large arrays can cause performance
3876 // problems, and we don't use such values yet. Once we have a more efficient
3877 // array representation, this should be reinstated, and used by CodeGen.
3878 if (isRValue() && getType()->isArrayType())
3879 return false;
3880
John McCallc07a0c72011-02-17 10:25:35 +00003881 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00003882
Richard Smithd62306a2011-11-10 06:34:14 +00003883 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003884 CCValue Value;
3885 if (!::Evaluate(Value, Info, this))
Richard Smith11562c52011-10-28 17:51:58 +00003886 return false;
3887
3888 if (isGLValue()) {
3889 LValue LV;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003890 LV.setFrom(Value);
3891 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3892 return false;
Richard Smith11562c52011-10-28 17:51:58 +00003893 }
3894
Richard Smith0b0a0b62011-10-29 20:57:55 +00003895 // Check this core constant expression is a constant expression, and if so,
Richard Smithed5165f2011-11-04 05:33:44 +00003896 // convert it to one.
3897 return CheckConstantExpression(Value, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00003898}
3899
Jay Foad39c79802011-01-12 09:06:06 +00003900bool Expr::EvaluateAsBooleanCondition(bool &Result,
3901 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003902 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00003903 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00003904 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00003905 Result);
John McCall1be1c632010-01-05 23:42:56 +00003906}
3907
Richard Smithcaf33902011-10-10 18:28:20 +00003908bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00003909 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003910 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smith11562c52011-10-28 17:51:58 +00003911 !ExprResult.Val.isInt()) {
3912 return false;
3913 }
3914 Result = ExprResult.Val.getInt();
3915 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00003916}
3917
Jay Foad39c79802011-01-12 09:06:06 +00003918bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00003919 EvalInfo Info(Ctx, Result);
3920
John McCall45d55e42010-05-07 21:00:08 +00003921 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00003922 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3923 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00003924}
3925
Richard Smith7b553f12011-10-29 00:50:52 +00003926/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3927/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00003928bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00003929 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00003930 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00003931}
Anders Carlsson59689ed2008-11-22 21:04:56 +00003932
Jay Foad39c79802011-01-12 09:06:06 +00003933bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00003934 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003935}
3936
Richard Smithcaf33902011-10-10 18:28:20 +00003937APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003938 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003939 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00003940 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00003941 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003942 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00003943
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003944 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00003945}
John McCall864e3962010-05-07 05:32:02 +00003946
Abramo Bagnaraf8199452010-05-14 17:07:14 +00003947 bool Expr::EvalResult::isGlobalLValue() const {
3948 assert(Val.isLValue());
3949 return IsGlobalLValue(Val.getLValueBase());
3950 }
3951
3952
John McCall864e3962010-05-07 05:32:02 +00003953/// isIntegerConstantExpr - this recursive routine will test if an expression is
3954/// an integer constant expression.
3955
3956/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
3957/// comma, etc
3958///
3959/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
3960/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
3961/// cast+dereference.
3962
3963// CheckICE - This function does the fundamental ICE checking: the returned
3964// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
3965// Note that to reduce code duplication, this helper does no evaluation
3966// itself; the caller checks whether the expression is evaluatable, and
3967// in the rare cases where CheckICE actually cares about the evaluated
3968// value, it calls into Evalute.
3969//
3970// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00003971// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00003972// 1: This expression is not an ICE, but if it isn't evaluated, it's
3973// a legal subexpression for an ICE. This return value is used to handle
3974// the comma operator in C99 mode.
3975// 2: This expression is not an ICE, and is not a legal subexpression for one.
3976
Dan Gohman28ade552010-07-26 21:25:24 +00003977namespace {
3978
John McCall864e3962010-05-07 05:32:02 +00003979struct ICEDiag {
3980 unsigned Val;
3981 SourceLocation Loc;
3982
3983 public:
3984 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
3985 ICEDiag() : Val(0) {}
3986};
3987
Dan Gohman28ade552010-07-26 21:25:24 +00003988}
3989
3990static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00003991
3992static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
3993 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00003994 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00003995 !EVResult.Val.isInt()) {
3996 return ICEDiag(2, E->getLocStart());
3997 }
3998 return NoDiag();
3999}
4000
4001static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4002 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004003 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004004 return ICEDiag(2, E->getLocStart());
4005 }
4006
4007 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004008#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004009#define STMT(Node, Base) case Expr::Node##Class:
4010#define EXPR(Node, Base)
4011#include "clang/AST/StmtNodes.inc"
4012 case Expr::PredefinedExprClass:
4013 case Expr::FloatingLiteralClass:
4014 case Expr::ImaginaryLiteralClass:
4015 case Expr::StringLiteralClass:
4016 case Expr::ArraySubscriptExprClass:
4017 case Expr::MemberExprClass:
4018 case Expr::CompoundAssignOperatorClass:
4019 case Expr::CompoundLiteralExprClass:
4020 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004021 case Expr::DesignatedInitExprClass:
4022 case Expr::ImplicitValueInitExprClass:
4023 case Expr::ParenListExprClass:
4024 case Expr::VAArgExprClass:
4025 case Expr::AddrLabelExprClass:
4026 case Expr::StmtExprClass:
4027 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00004028 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00004029 case Expr::CXXDynamicCastExprClass:
4030 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00004031 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00004032 case Expr::CXXNullPtrLiteralExprClass:
4033 case Expr::CXXThisExprClass:
4034 case Expr::CXXThrowExprClass:
4035 case Expr::CXXNewExprClass:
4036 case Expr::CXXDeleteExprClass:
4037 case Expr::CXXPseudoDestructorExprClass:
4038 case Expr::UnresolvedLookupExprClass:
4039 case Expr::DependentScopeDeclRefExprClass:
4040 case Expr::CXXConstructExprClass:
4041 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00004042 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00004043 case Expr::CXXTemporaryObjectExprClass:
4044 case Expr::CXXUnresolvedConstructExprClass:
4045 case Expr::CXXDependentScopeMemberExprClass:
4046 case Expr::UnresolvedMemberExprClass:
4047 case Expr::ObjCStringLiteralClass:
4048 case Expr::ObjCEncodeExprClass:
4049 case Expr::ObjCMessageExprClass:
4050 case Expr::ObjCSelectorExprClass:
4051 case Expr::ObjCProtocolExprClass:
4052 case Expr::ObjCIvarRefExprClass:
4053 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00004054 case Expr::ObjCIsaExprClass:
4055 case Expr::ShuffleVectorExprClass:
4056 case Expr::BlockExprClass:
4057 case Expr::BlockDeclRefExprClass:
4058 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00004059 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004060 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00004061 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00004062 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00004063 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00004064 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00004065 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004066 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00004067 return ICEDiag(2, E->getLocStart());
4068
Sebastian Redl12757ab2011-09-24 17:48:14 +00004069 case Expr::InitListExprClass:
4070 if (Ctx.getLangOptions().CPlusPlus0x) {
4071 const InitListExpr *ILE = cast<InitListExpr>(E);
4072 if (ILE->getNumInits() == 0)
4073 return NoDiag();
4074 if (ILE->getNumInits() == 1)
4075 return CheckICE(ILE->getInit(0), Ctx);
4076 // Fall through for more than 1 expression.
4077 }
4078 return ICEDiag(2, E->getLocStart());
4079
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004080 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00004081 case Expr::GNUNullExprClass:
4082 // GCC considers the GNU __null value to be an integral constant expression.
4083 return NoDiag();
4084
John McCall7c454bb2011-07-15 05:09:51 +00004085 case Expr::SubstNonTypeTemplateParmExprClass:
4086 return
4087 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4088
John McCall864e3962010-05-07 05:32:02 +00004089 case Expr::ParenExprClass:
4090 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00004091 case Expr::GenericSelectionExprClass:
4092 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004093 case Expr::IntegerLiteralClass:
4094 case Expr::CharacterLiteralClass:
4095 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00004096 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00004097 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004098 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00004099 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00004100 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004101 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00004102 return NoDiag();
4103 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00004104 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00004105 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4106 // constant expressions, but they can never be ICEs because an ICE cannot
4107 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00004108 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004109 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00004110 return CheckEvalInICE(E, Ctx);
4111 return ICEDiag(2, E->getLocStart());
4112 }
4113 case Expr::DeclRefExprClass:
4114 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4115 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00004116 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00004117 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4118
4119 // Parameter variables are never constants. Without this check,
4120 // getAnyInitializer() can find a default argument, which leads
4121 // to chaos.
4122 if (isa<ParmVarDecl>(D))
4123 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4124
4125 // C++ 7.1.5.1p2
4126 // A variable of non-volatile const-qualified integral or enumeration
4127 // type initialized by an ICE can be used in ICEs.
4128 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00004129 if (!Dcl->getType()->isIntegralOrEnumerationType())
4130 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4131
John McCall864e3962010-05-07 05:32:02 +00004132 // Look for a declaration of this variable that has an initializer.
4133 const VarDecl *ID = 0;
4134 const Expr *Init = Dcl->getAnyInitializer(ID);
4135 if (Init) {
4136 if (ID->isInitKnownICE()) {
4137 // We have already checked whether this subexpression is an
4138 // integral constant expression.
4139 if (ID->isInitICE())
4140 return NoDiag();
4141 else
4142 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4143 }
4144
4145 // It's an ICE whether or not the definition we found is
4146 // out-of-line. See DR 721 and the discussion in Clang PR
4147 // 6206 for details.
4148
4149 if (Dcl->isCheckingICE()) {
4150 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4151 }
4152
4153 Dcl->setCheckingICE();
4154 ICEDiag Result = CheckICE(Init, Ctx);
4155 // Cache the result of the ICE test.
4156 Dcl->setInitKnownICE(Result.Val == 0);
4157 return Result;
4158 }
4159 }
4160 }
4161 return ICEDiag(2, E->getLocStart());
4162 case Expr::UnaryOperatorClass: {
4163 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4164 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004165 case UO_PostInc:
4166 case UO_PostDec:
4167 case UO_PreInc:
4168 case UO_PreDec:
4169 case UO_AddrOf:
4170 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00004171 // C99 6.6/3 allows increment and decrement within unevaluated
4172 // subexpressions of constant expressions, but they can never be ICEs
4173 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004174 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00004175 case UO_Extension:
4176 case UO_LNot:
4177 case UO_Plus:
4178 case UO_Minus:
4179 case UO_Not:
4180 case UO_Real:
4181 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00004182 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004183 }
4184
4185 // OffsetOf falls through here.
4186 }
4187 case Expr::OffsetOfExprClass: {
4188 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00004189 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00004190 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00004191 // compliance: we should warn earlier for offsetof expressions with
4192 // array subscripts that aren't ICEs, and if the array subscripts
4193 // are ICEs, the value of the offsetof must be an integer constant.
4194 return CheckEvalInICE(E, Ctx);
4195 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00004196 case Expr::UnaryExprOrTypeTraitExprClass: {
4197 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4198 if ((Exp->getKind() == UETT_SizeOf) &&
4199 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00004200 return ICEDiag(2, E->getLocStart());
4201 return NoDiag();
4202 }
4203 case Expr::BinaryOperatorClass: {
4204 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4205 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004206 case BO_PtrMemD:
4207 case BO_PtrMemI:
4208 case BO_Assign:
4209 case BO_MulAssign:
4210 case BO_DivAssign:
4211 case BO_RemAssign:
4212 case BO_AddAssign:
4213 case BO_SubAssign:
4214 case BO_ShlAssign:
4215 case BO_ShrAssign:
4216 case BO_AndAssign:
4217 case BO_XorAssign:
4218 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00004219 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4220 // constant expressions, but they can never be ICEs because an ICE cannot
4221 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004222 return ICEDiag(2, E->getLocStart());
4223
John McCalle3027922010-08-25 11:45:40 +00004224 case BO_Mul:
4225 case BO_Div:
4226 case BO_Rem:
4227 case BO_Add:
4228 case BO_Sub:
4229 case BO_Shl:
4230 case BO_Shr:
4231 case BO_LT:
4232 case BO_GT:
4233 case BO_LE:
4234 case BO_GE:
4235 case BO_EQ:
4236 case BO_NE:
4237 case BO_And:
4238 case BO_Xor:
4239 case BO_Or:
4240 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00004241 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4242 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00004243 if (Exp->getOpcode() == BO_Div ||
4244 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00004245 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00004246 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00004247 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00004248 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004249 if (REval == 0)
4250 return ICEDiag(1, E->getLocStart());
4251 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00004252 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004253 if (LEval.isMinSignedValue())
4254 return ICEDiag(1, E->getLocStart());
4255 }
4256 }
4257 }
John McCalle3027922010-08-25 11:45:40 +00004258 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00004259 if (Ctx.getLangOptions().C99) {
4260 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4261 // if it isn't evaluated.
4262 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4263 return ICEDiag(1, E->getLocStart());
4264 } else {
4265 // In both C89 and C++, commas in ICEs are illegal.
4266 return ICEDiag(2, E->getLocStart());
4267 }
4268 }
4269 if (LHSResult.Val >= RHSResult.Val)
4270 return LHSResult;
4271 return RHSResult;
4272 }
John McCalle3027922010-08-25 11:45:40 +00004273 case BO_LAnd:
4274 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00004275 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004276
4277 // C++0x [expr.const]p2:
4278 // [...] subexpressions of logical AND (5.14), logical OR
4279 // (5.15), and condi- tional (5.16) operations that are not
4280 // evaluated are not considered.
4281 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4282 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00004283 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004284 return LHSResult;
4285
4286 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00004287 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004288 return LHSResult;
4289 }
4290
John McCall864e3962010-05-07 05:32:02 +00004291 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4292 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4293 // Rare case where the RHS has a comma "side-effect"; we need
4294 // to actually check the condition to see whether the side
4295 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00004296 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00004297 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00004298 return RHSResult;
4299 return NoDiag();
4300 }
4301
4302 if (LHSResult.Val >= RHSResult.Val)
4303 return LHSResult;
4304 return RHSResult;
4305 }
4306 }
4307 }
4308 case Expr::ImplicitCastExprClass:
4309 case Expr::CStyleCastExprClass:
4310 case Expr::CXXFunctionalCastExprClass:
4311 case Expr::CXXStaticCastExprClass:
4312 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00004313 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004314 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00004315 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00004316 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00004317 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4318 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00004319 switch (cast<CastExpr>(E)->getCastKind()) {
4320 case CK_LValueToRValue:
4321 case CK_NoOp:
4322 case CK_IntegralToBoolean:
4323 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00004324 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00004325 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00004326 return ICEDiag(2, E->getLocStart());
4327 }
John McCall864e3962010-05-07 05:32:02 +00004328 }
John McCallc07a0c72011-02-17 10:25:35 +00004329 case Expr::BinaryConditionalOperatorClass: {
4330 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4331 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4332 if (CommonResult.Val == 2) return CommonResult;
4333 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4334 if (FalseResult.Val == 2) return FalseResult;
4335 if (CommonResult.Val == 1) return CommonResult;
4336 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00004337 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00004338 return FalseResult;
4339 }
John McCall864e3962010-05-07 05:32:02 +00004340 case Expr::ConditionalOperatorClass: {
4341 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4342 // If the condition (ignoring parens) is a __builtin_constant_p call,
4343 // then only the true side is actually considered in an integer constant
4344 // expression, and it is fully evaluated. This is an important GNU
4345 // extension. See GCC PR38377 for discussion.
4346 if (const CallExpr *CallCE
4347 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00004348 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00004349 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004350 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004351 !EVResult.Val.isInt()) {
4352 return ICEDiag(2, E->getLocStart());
4353 }
4354 return NoDiag();
4355 }
4356 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004357 if (CondResult.Val == 2)
4358 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004359
4360 // C++0x [expr.const]p2:
4361 // subexpressions of [...] conditional (5.16) operations that
4362 // are not evaluated are not considered
4363 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00004364 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00004365 : false;
4366 ICEDiag TrueResult = NoDiag();
4367 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4368 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4369 ICEDiag FalseResult = NoDiag();
4370 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
4371 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4372
John McCall864e3962010-05-07 05:32:02 +00004373 if (TrueResult.Val == 2)
4374 return TrueResult;
4375 if (FalseResult.Val == 2)
4376 return FalseResult;
4377 if (CondResult.Val == 1)
4378 return CondResult;
4379 if (TrueResult.Val == 0 && FalseResult.Val == 0)
4380 return NoDiag();
4381 // Rare case where the diagnostics depend on which side is evaluated
4382 // Note that if we get here, CondResult is 0, and at least one of
4383 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00004384 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00004385 return FalseResult;
4386 }
4387 return TrueResult;
4388 }
4389 case Expr::CXXDefaultArgExprClass:
4390 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
4391 case Expr::ChooseExprClass: {
4392 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
4393 }
4394 }
4395
4396 // Silence a GCC warning
4397 return ICEDiag(2, E->getLocStart());
4398}
4399
4400bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
4401 SourceLocation *Loc, bool isEvaluated) const {
4402 ICEDiag d = CheckICE(this, Ctx);
4403 if (d.Val != 0) {
4404 if (Loc) *Loc = d.Loc;
4405 return false;
4406 }
Richard Smith11562c52011-10-28 17:51:58 +00004407 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00004408 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00004409 return true;
4410}