blob: 81fe7e3a4e1b10350968f9225bcf3698b3f40dad [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith9a17a682011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith0a3bdb62011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith9a17a682011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith47a1eed2011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith180f4792011-11-10 06:34:14 +0000234 /// This - The binding for the this pointer in this call, if any.
235 const LValue *This;
236
Richard Smithd0dccea2011-10-28 22:34:42 +0000237 /// ParmBindings - Parameter bindings for this function call, indexed by
238 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000239 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000240
Richard Smithbd552ef2011-10-31 05:52:43 +0000241 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
242 typedef MapTy::const_iterator temp_iterator;
243 /// Temporaries - Temporary lvalues materialized within this stack frame.
244 MapTy Temporaries;
245
Richard Smith180f4792011-11-10 06:34:14 +0000246 CallStackFrame(EvalInfo &Info, const LValue *This,
247 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000248 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000249 };
250
Richard Smithbd552ef2011-10-31 05:52:43 +0000251 struct EvalInfo {
252 const ASTContext &Ctx;
253
254 /// EvalStatus - Contains information about the evaluation.
255 Expr::EvalStatus &EvalStatus;
256
257 /// CurrentCall - The top of the constexpr call stack.
258 CallStackFrame *CurrentCall;
259
Richard Smithbd552ef2011-10-31 05:52:43 +0000260 /// CallStackDepth - The number of calls in the call stack right now.
261 unsigned CallStackDepth;
262
263 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
264 /// OpaqueValues - Values used as the common expression in a
265 /// BinaryConditionalOperator.
266 MapTy OpaqueValues;
267
268 /// BottomFrame - The frame in which evaluation started. This must be
269 /// initialized last.
270 CallStackFrame BottomFrame;
271
Richard Smith180f4792011-11-10 06:34:14 +0000272 /// EvaluatingDecl - This is the declaration whose initializer is being
273 /// evaluated, if any.
274 const VarDecl *EvaluatingDecl;
275
276 /// EvaluatingDeclValue - This is the value being constructed for the
277 /// declaration whose initializer is being evaluated, if any.
278 APValue *EvaluatingDeclValue;
279
Richard Smithbd552ef2011-10-31 05:52:43 +0000280
281 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithc18c4232011-11-21 19:36:32 +0000282 : Ctx(C), EvalStatus(S), CurrentCall(0), CallStackDepth(0),
Richard Smith180f4792011-11-10 06:34:14 +0000283 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000284
Richard Smithbd552ef2011-10-31 05:52:43 +0000285 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
286 MapTy::const_iterator i = OpaqueValues.find(e);
287 if (i == OpaqueValues.end()) return 0;
288 return &i->second;
289 }
290
Richard Smith180f4792011-11-10 06:34:14 +0000291 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
292 EvaluatingDecl = VD;
293 EvaluatingDeclValue = &Value;
294 }
295
Richard Smithc18c4232011-11-21 19:36:32 +0000296 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
297
298 bool atCallLimit() const {
299 return CallStackDepth > getLangOpts().ConstexprCallDepth;
300 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000301 };
302
Richard Smith180f4792011-11-10 06:34:14 +0000303 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
304 const CCValue *Arguments)
305 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smithbd552ef2011-10-31 05:52:43 +0000306 Info.CurrentCall = this;
307 ++Info.CallStackDepth;
308 }
309
310 CallStackFrame::~CallStackFrame() {
311 assert(Info.CurrentCall == this && "calls retired out of order");
312 --Info.CallStackDepth;
313 Info.CurrentCall = Caller;
314 }
315
John McCallf4cf1a12010-05-07 17:22:02 +0000316 struct ComplexValue {
317 private:
318 bool IsInt;
319
320 public:
321 APSInt IntReal, IntImag;
322 APFloat FloatReal, FloatImag;
323
324 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
325
326 void makeComplexFloat() { IsInt = false; }
327 bool isComplexFloat() const { return !IsInt; }
328 APFloat &getComplexFloatReal() { return FloatReal; }
329 APFloat &getComplexFloatImag() { return FloatImag; }
330
331 void makeComplexInt() { IsInt = true; }
332 bool isComplexInt() const { return IsInt; }
333 APSInt &getComplexIntReal() { return IntReal; }
334 APSInt &getComplexIntImag() { return IntImag; }
335
Richard Smith47a1eed2011-10-29 20:57:55 +0000336 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000337 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000338 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000339 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000340 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000341 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000342 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000343 assert(v.isComplexFloat() || v.isComplexInt());
344 if (v.isComplexFloat()) {
345 makeComplexFloat();
346 FloatReal = v.getComplexFloatReal();
347 FloatImag = v.getComplexFloatImag();
348 } else {
349 makeComplexInt();
350 IntReal = v.getComplexIntReal();
351 IntImag = v.getComplexIntImag();
352 }
353 }
John McCallf4cf1a12010-05-07 17:22:02 +0000354 };
John McCallefdb83e2010-05-07 21:00:08 +0000355
356 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000357 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000358 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000359 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000360 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000361
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000362 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000363 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000364 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000365 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000366 SubobjectDesignator &getLValueDesignator() { return Designator; }
367 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000368
Richard Smith47a1eed2011-10-29 20:57:55 +0000369 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000370 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000371 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000372 void setFrom(const CCValue &V) {
373 assert(V.isLValue());
374 Base = V.getLValueBase();
375 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000376 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000377 Designator = V.getLValueDesignator();
378 }
379
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000380 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
381 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000382 Offset = CharUnits::Zero();
383 Frame = F;
384 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000385 }
John McCallefdb83e2010-05-07 21:00:08 +0000386 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000387
388 struct MemberPtr {
389 MemberPtr() {}
390 explicit MemberPtr(const ValueDecl *Decl) :
391 DeclAndIsDerivedMember(Decl, false), Path() {}
392
393 /// The member or (direct or indirect) field referred to by this member
394 /// pointer, or 0 if this is a null member pointer.
395 const ValueDecl *getDecl() const {
396 return DeclAndIsDerivedMember.getPointer();
397 }
398 /// Is this actually a member of some type derived from the relevant class?
399 bool isDerivedMember() const {
400 return DeclAndIsDerivedMember.getInt();
401 }
402 /// Get the class which the declaration actually lives in.
403 const CXXRecordDecl *getContainingRecord() const {
404 return cast<CXXRecordDecl>(
405 DeclAndIsDerivedMember.getPointer()->getDeclContext());
406 }
407
408 void moveInto(CCValue &V) const {
409 V = CCValue(getDecl(), isDerivedMember(), Path);
410 }
411 void setFrom(const CCValue &V) {
412 assert(V.isMemberPointer());
413 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
414 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
415 Path.clear();
416 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
417 Path.insert(Path.end(), P.begin(), P.end());
418 }
419
420 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
421 /// whether the member is a member of some class derived from the class type
422 /// of the member pointer.
423 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
424 /// Path - The path of base/derived classes from the member declaration's
425 /// class (exclusive) to the class type of the member pointer (inclusive).
426 SmallVector<const CXXRecordDecl*, 4> Path;
427
428 /// Perform a cast towards the class of the Decl (either up or down the
429 /// hierarchy).
430 bool castBack(const CXXRecordDecl *Class) {
431 assert(!Path.empty());
432 const CXXRecordDecl *Expected;
433 if (Path.size() >= 2)
434 Expected = Path[Path.size() - 2];
435 else
436 Expected = getContainingRecord();
437 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
438 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
439 // if B does not contain the original member and is not a base or
440 // derived class of the class containing the original member, the result
441 // of the cast is undefined.
442 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
443 // (D::*). We consider that to be a language defect.
444 return false;
445 }
446 Path.pop_back();
447 return true;
448 }
449 /// Perform a base-to-derived member pointer cast.
450 bool castToDerived(const CXXRecordDecl *Derived) {
451 if (!getDecl())
452 return true;
453 if (!isDerivedMember()) {
454 Path.push_back(Derived);
455 return true;
456 }
457 if (!castBack(Derived))
458 return false;
459 if (Path.empty())
460 DeclAndIsDerivedMember.setInt(false);
461 return true;
462 }
463 /// Perform a derived-to-base member pointer cast.
464 bool castToBase(const CXXRecordDecl *Base) {
465 if (!getDecl())
466 return true;
467 if (Path.empty())
468 DeclAndIsDerivedMember.setInt(true);
469 if (isDerivedMember()) {
470 Path.push_back(Base);
471 return true;
472 }
473 return castBack(Base);
474 }
475 };
John McCallf4cf1a12010-05-07 17:22:02 +0000476}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000477
Richard Smith47a1eed2011-10-29 20:57:55 +0000478static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000479static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +0000480 const LValue &This, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000481static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
482static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000483static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
484 EvalInfo &Info);
485static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000486static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000487static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000488 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000489static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000490static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000491
492//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000493// Misc utilities
494//===----------------------------------------------------------------------===//
495
Richard Smith180f4792011-11-10 06:34:14 +0000496/// Should this call expression be treated as a string literal?
497static bool IsStringLiteralCall(const CallExpr *E) {
498 unsigned Builtin = E->isBuiltinCall();
499 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
500 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
501}
502
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000503static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000504 // C++11 [expr.const]p3 An address constant expression is a prvalue core
505 // constant expression of pointer type that evaluates to...
506
507 // ... a null pointer value, or a prvalue core constant expression of type
508 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000509 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000510
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000511 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
512 // ... the address of an object with static storage duration,
513 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
514 return VD->hasGlobalStorage();
515 // ... the address of a function,
516 return isa<FunctionDecl>(D);
517 }
518
519 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000520 switch (E->getStmtClass()) {
521 default:
522 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000523 case Expr::CompoundLiteralExprClass:
524 return cast<CompoundLiteralExpr>(E)->isFileScope();
525 // A string literal has static storage duration.
526 case Expr::StringLiteralClass:
527 case Expr::PredefinedExprClass:
528 case Expr::ObjCStringLiteralClass:
529 case Expr::ObjCEncodeExprClass:
530 return true;
531 case Expr::CallExprClass:
532 return IsStringLiteralCall(cast<CallExpr>(E));
533 // For GCC compatibility, &&label has static storage duration.
534 case Expr::AddrLabelExprClass:
535 return true;
536 // A Block literal expression may be used as the initialization value for
537 // Block variables at global or local static scope.
538 case Expr::BlockExprClass:
539 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
540 }
John McCall42c8f872010-05-10 23:27:23 +0000541}
542
Richard Smith9a17a682011-11-07 05:07:52 +0000543/// Check that this reference or pointer core constant expression is a valid
544/// value for a constant expression. Type T should be either LValue or CCValue.
545template<typename T>
546static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
547 if (!IsGlobalLValue(LVal.getLValueBase()))
548 return false;
549
550 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
551 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000552 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000553 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith9a17a682011-11-07 05:07:52 +0000554 // FIXME: This is not a constant expression.
555 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
556 APValue::NoLValuePath());
557 return true;
558 }
559
560 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000561 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000562 return true;
563}
564
Richard Smith47a1eed2011-10-29 20:57:55 +0000565/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000566/// constant expression, and if it is, produce the corresponding constant value.
567static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
Richard Smith9a17a682011-11-07 05:07:52 +0000568 if (!CCValue.isLValue()) {
569 Value = CCValue;
570 return true;
571 }
572 return CheckLValueConstantExpression(CCValue, Value);
Richard Smith47a1eed2011-10-29 20:57:55 +0000573}
574
Richard Smith9e36b532011-10-31 05:11:32 +0000575const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000576 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000577}
578
579static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000580 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000581}
582
Richard Smith65ac5982011-11-01 21:06:14 +0000583static bool IsWeakDecl(const ValueDecl *Decl) {
Richard Smith9e36b532011-10-31 05:11:32 +0000584 return Decl->hasAttr<WeakAttr>() ||
585 Decl->hasAttr<WeakRefAttr>() ||
586 Decl->isWeakImported();
587}
588
Richard Smith65ac5982011-11-01 21:06:14 +0000589static bool IsWeakLValue(const LValue &Value) {
590 const ValueDecl *Decl = GetLValueBaseDecl(Value);
591 return Decl && IsWeakDecl(Decl);
592}
593
Richard Smithe24f5fc2011-11-17 22:56:20 +0000594static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000595 // A null base expression indicates a null pointer. These are always
596 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000597 if (!Value.getLValueBase()) {
598 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000599 return true;
600 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000601
John McCall42c8f872010-05-10 23:27:23 +0000602 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000603 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000604 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000605
Richard Smithe24f5fc2011-11-17 22:56:20 +0000606 // We have a non-null base. These are generally known to be true, but if it's
607 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000608 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000609 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
610 return !Decl || !IsWeakDecl(Decl);
Eli Friedman5bc86102009-06-14 02:17:33 +0000611}
612
Richard Smith47a1eed2011-10-29 20:57:55 +0000613static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000614 switch (Val.getKind()) {
615 case APValue::Uninitialized:
616 return false;
617 case APValue::Int:
618 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000619 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000620 case APValue::Float:
621 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000622 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000623 case APValue::ComplexInt:
624 Result = Val.getComplexIntReal().getBoolValue() ||
625 Val.getComplexIntImag().getBoolValue();
626 return true;
627 case APValue::ComplexFloat:
628 Result = !Val.getComplexFloatReal().isZero() ||
629 !Val.getComplexFloatImag().isZero();
630 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000631 case APValue::LValue:
632 return EvalPointerValueAsBool(Val, Result);
633 case APValue::MemberPointer:
634 Result = Val.getMemberPointerDecl();
635 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000636 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000637 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000638 case APValue::Struct:
639 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000640 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000641 }
642
Richard Smithc49bd112011-10-28 17:51:58 +0000643 llvm_unreachable("unknown APValue kind");
644}
645
646static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
647 EvalInfo &Info) {
648 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000649 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000650 if (!Evaluate(Val, Info, E))
651 return false;
652 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000653}
654
Mike Stump1eb44332009-09-09 15:08:12 +0000655static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000656 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000657 unsigned DestWidth = Ctx.getIntWidth(DestType);
658 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000659 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000660
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000661 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000662 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000663 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000664 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
665 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000666}
667
Mike Stump1eb44332009-09-09 15:08:12 +0000668static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000669 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000670 bool ignored;
671 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000672 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000673 APFloat::rmNearestTiesToEven, &ignored);
674 return Result;
675}
676
Mike Stump1eb44332009-09-09 15:08:12 +0000677static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000678 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000679 unsigned DestWidth = Ctx.getIntWidth(DestType);
680 APSInt Result = Value;
681 // Figure out if this is a truncate, extend or noop cast.
682 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000683 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000684 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000685 return Result;
686}
687
Mike Stump1eb44332009-09-09 15:08:12 +0000688static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000689 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000690
691 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
692 Result.convertFromAPInt(Value, Value.isSigned(),
693 APFloat::rmNearestTiesToEven);
694 return Result;
695}
696
Richard Smithe24f5fc2011-11-17 22:56:20 +0000697static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
698 const CXXRecordDecl *&MostDerivedType,
699 unsigned &MostDerivedPathLength,
700 bool &MostDerivedIsArrayElement) {
701 const SubobjectDesignator &D = LVal.Designator;
702 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000703 return false;
704
Richard Smithe24f5fc2011-11-17 22:56:20 +0000705 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000706
707 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000708 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000709 MostDerivedPathLength = 0;
710 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000711
712 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
713 bool IsArray = T && T->isArrayType();
714 if (IsArray)
715 T = T->getBaseElementTypeUnsafe();
716 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
717 T = FD->getType().getTypePtr();
718 else
719 T = 0;
720
721 if (T) {
722 MostDerivedType = T->getAsCXXRecordDecl();
723 MostDerivedPathLength = I + 1;
724 MostDerivedIsArrayElement = IsArray;
725 }
726 }
727
Richard Smith180f4792011-11-10 06:34:14 +0000728 // (B*)&d + 1 has no most-derived object.
729 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
730 return false;
731
Richard Smithe24f5fc2011-11-17 22:56:20 +0000732 return MostDerivedType != 0;
733}
734
735static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
736 const RecordDecl *TruncatedType,
737 unsigned TruncatedElements,
738 bool IsArrayElement) {
739 SubobjectDesignator &D = Result.Designator;
740 const RecordDecl *RD = TruncatedType;
741 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +0000742 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
743 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000744 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +0000745 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000746 else
Richard Smith180f4792011-11-10 06:34:14 +0000747 Result.Offset -= Layout.getBaseClassOffset(Base);
748 RD = Base;
749 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000750 D.Entries.resize(TruncatedElements);
751 D.ArrayElement = IsArrayElement;
752}
753
754/// If the given LValue refers to a base subobject of some object, find the most
755/// derived object and the corresponding complete record type. This is necessary
756/// in order to find the offset of a virtual base class.
757static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
758 const CXXRecordDecl *&MostDerivedType) {
759 unsigned MostDerivedPathLength;
760 bool MostDerivedIsArrayElement;
761 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
762 MostDerivedPathLength, MostDerivedIsArrayElement))
763 return false;
764
765 // Remove the trailing base class path entries and their offsets.
766 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
767 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +0000768 return true;
769}
770
771static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
772 const CXXRecordDecl *Derived,
773 const CXXRecordDecl *Base,
774 const ASTRecordLayout *RL = 0) {
775 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
776 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
777 Obj.Designator.addDecl(Base, /*Virtual*/ false);
778}
779
780static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
781 const CXXRecordDecl *DerivedDecl,
782 const CXXBaseSpecifier *Base) {
783 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
784
785 if (!Base->isVirtual()) {
786 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
787 return true;
788 }
789
790 // Extract most-derived object and corresponding type.
791 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
792 return false;
793
794 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
795 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
796 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
797 return true;
798}
799
800/// Update LVal to refer to the given field, which must be a member of the type
801/// currently described by LVal.
802static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
803 const FieldDecl *FD,
804 const ASTRecordLayout *RL = 0) {
805 if (!RL)
806 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
807
808 unsigned I = FD->getFieldIndex();
809 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
810 LVal.Designator.addDecl(FD);
811}
812
813/// Get the size of the given type in char units.
814static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
815 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
816 // extension.
817 if (Type->isVoidType() || Type->isFunctionType()) {
818 Size = CharUnits::One();
819 return true;
820 }
821
822 if (!Type->isConstantSizeType()) {
823 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
824 return false;
825 }
826
827 Size = Info.Ctx.getTypeSizeInChars(Type);
828 return true;
829}
830
831/// Update a pointer value to model pointer arithmetic.
832/// \param Info - Information about the ongoing evaluation.
833/// \param LVal - The pointer value to be updated.
834/// \param EltTy - The pointee type represented by LVal.
835/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
836static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
837 QualType EltTy, int64_t Adjustment) {
838 CharUnits SizeOfPointee;
839 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
840 return false;
841
842 // Compute the new offset in the appropriate width.
843 LVal.Offset += Adjustment * SizeOfPointee;
844 LVal.Designator.adjustIndex(Adjustment);
845 return true;
846}
847
Richard Smith03f96112011-10-24 17:54:18 +0000848/// Try to evaluate the initializer for a variable declaration.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000849static bool EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +0000850 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000851 // If this is a parameter to an active constexpr function call, perform
852 // argument substitution.
853 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith177dce72011-11-01 16:57:24 +0000854 if (!Frame || !Frame->Arguments)
855 return false;
856 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
857 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +0000858 }
Richard Smith03f96112011-10-24 17:54:18 +0000859
Richard Smith180f4792011-11-10 06:34:14 +0000860 // If we're currently evaluating the initializer of this declaration, use that
861 // in-flight value.
862 if (Info.EvaluatingDecl == VD) {
863 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
864 return !Result.isUninit();
865 }
866
Richard Smith65ac5982011-11-01 21:06:14 +0000867 // Never evaluate the initializer of a weak variable. We can't be sure that
868 // this is the definition which will be used.
869 if (IsWeakDecl(VD))
870 return false;
871
Richard Smith03f96112011-10-24 17:54:18 +0000872 const Expr *Init = VD->getAnyInitializer();
Richard Smithdb1822c2011-11-08 01:31:09 +0000873 if (!Init || Init->isValueDependent())
Richard Smith47a1eed2011-10-29 20:57:55 +0000874 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000875
Richard Smith47a1eed2011-10-29 20:57:55 +0000876 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +0000877 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000878 return !Result.isUninit();
879 }
Richard Smith03f96112011-10-24 17:54:18 +0000880
881 if (VD->isEvaluatingValue())
Richard Smith47a1eed2011-10-29 20:57:55 +0000882 return false;
Richard Smith03f96112011-10-24 17:54:18 +0000883
884 VD->setEvaluatingValue();
885
Richard Smith47a1eed2011-10-29 20:57:55 +0000886 Expr::EvalStatus EStatus;
887 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +0000888 APValue EvalResult;
889 InitInfo.setEvaluatingDecl(VD, EvalResult);
890 LValue LVal;
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000891 LVal.set(VD);
Richard Smithc49bd112011-10-28 17:51:58 +0000892 // FIXME: The caller will need to know whether the value was a constant
893 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +0000894 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000895 // FIXME: If the evaluation failure was not permanent (for instance, if we
896 // hit a variable with no declaration yet, or a constexpr function with no
897 // definition yet), the standard is unclear as to how we should behave.
898 //
899 // Either the initializer should be evaluated when the variable is defined,
900 // or a failed evaluation of the initializer should be reattempted each time
901 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +0000902 VD->setEvaluatedValue(APValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000903 return false;
904 }
Richard Smith03f96112011-10-24 17:54:18 +0000905
Richard Smith69c2c502011-11-04 05:33:44 +0000906 VD->setEvaluatedValue(EvalResult);
907 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +0000908 return true;
Richard Smith03f96112011-10-24 17:54:18 +0000909}
910
Richard Smithc49bd112011-10-28 17:51:58 +0000911static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +0000912 Qualifiers Quals = T.getQualifiers();
913 return Quals.hasConst() && !Quals.hasVolatile();
914}
915
Richard Smith59efe262011-11-11 04:05:33 +0000916/// Get the base index of the given base class within an APValue representing
917/// the given derived class.
918static unsigned getBaseIndex(const CXXRecordDecl *Derived,
919 const CXXRecordDecl *Base) {
920 Base = Base->getCanonicalDecl();
921 unsigned Index = 0;
922 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
923 E = Derived->bases_end(); I != E; ++I, ++Index) {
924 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
925 return Index;
926 }
927
928 llvm_unreachable("base class missing from derived class's bases list");
929}
930
Richard Smithcc5d4f62011-11-07 09:22:26 +0000931/// Extract the designated sub-object of an rvalue.
932static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
933 const SubobjectDesignator &Sub, QualType SubType) {
934 if (Sub.Invalid || Sub.OnePastTheEnd)
935 return false;
Richard Smithf64699e2011-11-11 08:28:03 +0000936 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +0000937 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +0000938
939 assert(!Obj.isLValue() && "extracting subobject of lvalue");
940 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +0000941 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000942 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000943 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +0000944 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000945 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
946 if (!CAT)
947 return false;
948 uint64_t Index = Sub.Entries[I].ArrayIndex;
949 if (CAT->getSize().ule(Index))
950 return false;
951 if (O->getArrayInitializedElts() > Index)
952 O = &O->getArrayInitializedElt(Index);
953 else
954 O = &O->getArrayFiller();
955 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +0000956 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
957 // Next subobject is a class, struct or union field.
958 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
959 if (RD->isUnion()) {
960 const FieldDecl *UnionField = O->getUnionField();
961 if (!UnionField ||
962 UnionField->getCanonicalDecl() != Field->getCanonicalDecl())
963 return false;
964 O = &O->getUnionValue();
965 } else
966 O = &O->getStructField(Field->getFieldIndex());
967 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +0000968 } else {
Richard Smith180f4792011-11-10 06:34:14 +0000969 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +0000970 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
971 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
972 O = &O->getStructBase(getBaseIndex(Derived, Base));
973 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +0000974 }
Richard Smith180f4792011-11-10 06:34:14 +0000975
976 if (O->isUninit())
977 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +0000978 }
979
Richard Smithcc5d4f62011-11-07 09:22:26 +0000980 Obj = CCValue(*O, CCValue::GlobalValue());
981 return true;
982}
983
Richard Smith180f4792011-11-10 06:34:14 +0000984/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
985/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
986/// for looking up the glvalue referred to by an entity of reference type.
987///
988/// \param Info - Information about the ongoing evaluation.
989/// \param Type - The type we expect this conversion to produce.
990/// \param LVal - The glvalue on which we are attempting to perform this action.
991/// \param RVal - The produced value will be placed here.
Richard Smithcc5d4f62011-11-07 09:22:26 +0000992static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
993 const LValue &LVal, CCValue &RVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000994 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +0000995 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +0000996
997 // FIXME: Indirection through a null pointer deserves a diagnostic.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000998 if (!LVal.Base)
Richard Smithc49bd112011-10-28 17:51:58 +0000999 return false;
1000
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001001 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001002 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1003 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001004 // expressions are constant expressions too. Inside constexpr functions,
1005 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001006 // In C, such things can also be folded, although they are not ICEs.
1007 //
Richard Smithd0dccea2011-10-28 22:34:42 +00001008 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1009 // interpretation of C++11 suggests that volatile parameters are OK if
1010 // they're never read (there's no prohibition against constructing volatile
1011 // objects in constant expressions), but lvalue-to-rvalue conversions on
1012 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +00001013 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithcd689922011-11-07 03:22:51 +00001014 if (!VD || VD->isInvalidDecl())
Richard Smith0a3bdb62011-11-04 02:25:55 +00001015 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001016 QualType VT = VD->getType();
Richard Smith0a3bdb62011-11-04 02:25:55 +00001017 if (!isa<ParmVarDecl>(VD)) {
1018 if (!IsConstNonVolatile(VT))
1019 return false;
Richard Smithcd689922011-11-07 03:22:51 +00001020 // FIXME: Allow folding of values of any literal type in all languages.
1021 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
1022 !VD->isConstexpr())
Richard Smith0a3bdb62011-11-04 02:25:55 +00001023 return false;
1024 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001025 if (!EvaluateVarDeclInit(Info, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001026 return false;
1027
Richard Smith47a1eed2011-10-29 20:57:55 +00001028 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001029 return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001030
1031 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1032 // conversion. This happens when the declaration and the lvalue should be
1033 // considered synonymous, for instance when initializing an array of char
1034 // from a string literal. Continue as if the initializer lvalue was the
1035 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001036 assert(RVal.getLValueOffset().isZero() &&
1037 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001038 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001039 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001040 }
1041
Richard Smith0a3bdb62011-11-04 02:25:55 +00001042 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1043 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1044 const SubobjectDesignator &Designator = LVal.Designator;
1045 if (Designator.Invalid || Designator.Entries.size() != 1)
1046 return false;
1047
1048 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001049 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +00001050 if (Index > S->getLength())
1051 return false;
1052 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1053 Type->isUnsignedIntegerType());
1054 if (Index < S->getLength())
1055 Value = S->getCodeUnit(Index);
1056 RVal = CCValue(Value);
1057 return true;
1058 }
1059
Richard Smithcc5d4f62011-11-07 09:22:26 +00001060 if (Frame) {
1061 // If this is a temporary expression with a nontrivial initializer, grab the
1062 // value from the relevant stack frame.
1063 RVal = Frame->Temporaries[Base];
1064 } else if (const CompoundLiteralExpr *CLE
1065 = dyn_cast<CompoundLiteralExpr>(Base)) {
1066 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1067 // initializer until now for such expressions. Such an expression can't be
1068 // an ICE in C, so this only matters for fold.
1069 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1070 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1071 return false;
1072 } else
Richard Smith0a3bdb62011-11-04 02:25:55 +00001073 return false;
1074
Richard Smithcc5d4f62011-11-07 09:22:26 +00001075 return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001076}
1077
Richard Smith59efe262011-11-11 04:05:33 +00001078/// Build an lvalue for the object argument of a member function call.
1079static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1080 LValue &This) {
1081 if (Object->getType()->isPointerType())
1082 return EvaluatePointer(Object, This, Info);
1083
1084 if (Object->isGLValue())
1085 return EvaluateLValue(Object, This, Info);
1086
Richard Smithe24f5fc2011-11-17 22:56:20 +00001087 if (Object->getType()->isLiteralType())
1088 return EvaluateTemporary(Object, This, Info);
1089
1090 return false;
1091}
1092
1093/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1094/// lvalue referring to the result.
1095///
1096/// \param Info - Information about the ongoing evaluation.
1097/// \param BO - The member pointer access operation.
1098/// \param LV - Filled in with a reference to the resulting object.
1099/// \param IncludeMember - Specifies whether the member itself is included in
1100/// the resulting LValue subobject designator. This is not possible when
1101/// creating a bound member function.
1102/// \return The field or method declaration to which the member pointer refers,
1103/// or 0 if evaluation fails.
1104static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1105 const BinaryOperator *BO,
1106 LValue &LV,
1107 bool IncludeMember = true) {
1108 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1109
1110 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1111 return 0;
1112
1113 MemberPtr MemPtr;
1114 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1115 return 0;
1116
1117 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1118 // member value, the behavior is undefined.
1119 if (!MemPtr.getDecl())
1120 return 0;
1121
1122 if (MemPtr.isDerivedMember()) {
1123 // This is a member of some derived class. Truncate LV appropriately.
1124 const CXXRecordDecl *MostDerivedType;
1125 unsigned MostDerivedPathLength;
1126 bool MostDerivedIsArrayElement;
1127 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1128 MostDerivedIsArrayElement))
1129 return 0;
1130
1131 // The end of the derived-to-base path for the base object must match the
1132 // derived-to-base path for the member pointer.
1133 if (MostDerivedPathLength + MemPtr.Path.size() >
1134 LV.Designator.Entries.size())
1135 return 0;
1136 unsigned PathLengthToMember =
1137 LV.Designator.Entries.size() - MemPtr.Path.size();
1138 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1139 const CXXRecordDecl *LVDecl = getAsBaseClass(
1140 LV.Designator.Entries[PathLengthToMember + I]);
1141 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1142 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1143 return 0;
1144 }
1145
1146 // Truncate the lvalue to the appropriate derived class.
1147 bool ResultIsArray = false;
1148 if (PathLengthToMember == MostDerivedPathLength)
1149 ResultIsArray = MostDerivedIsArrayElement;
1150 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1151 PathLengthToMember, ResultIsArray);
1152 } else if (!MemPtr.Path.empty()) {
1153 // Extend the LValue path with the member pointer's path.
1154 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1155 MemPtr.Path.size() + IncludeMember);
1156
1157 // Walk down to the appropriate base class.
1158 QualType LVType = BO->getLHS()->getType();
1159 if (const PointerType *PT = LVType->getAs<PointerType>())
1160 LVType = PT->getPointeeType();
1161 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1162 assert(RD && "member pointer access on non-class-type expression");
1163 // The first class in the path is that of the lvalue.
1164 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1165 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1166 HandleLValueDirectBase(Info, LV, RD, Base);
1167 RD = Base;
1168 }
1169 // Finally cast to the class containing the member.
1170 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1171 }
1172
1173 // Add the member. Note that we cannot build bound member functions here.
1174 if (IncludeMember) {
1175 // FIXME: Deal with IndirectFieldDecls.
1176 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1177 if (!FD) return 0;
1178 HandleLValueMember(Info, LV, FD);
1179 }
1180
1181 return MemPtr.getDecl();
1182}
1183
1184/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1185/// the provided lvalue, which currently refers to the base object.
1186static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1187 LValue &Result) {
1188 const CXXRecordDecl *MostDerivedType;
1189 unsigned MostDerivedPathLength;
1190 bool MostDerivedIsArrayElement;
1191
1192 // Check this cast doesn't take us outside the object.
1193 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1194 MostDerivedPathLength,
1195 MostDerivedIsArrayElement))
1196 return false;
1197 SubobjectDesignator &D = Result.Designator;
1198 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1199 return false;
1200
1201 // Check the type of the final cast. We don't need to check the path,
1202 // since a cast can only be formed if the path is unique.
1203 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1204 bool ResultIsArray = false;
1205 QualType TargetQT = E->getType();
1206 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1207 TargetQT = PT->getPointeeType();
1208 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1209 const CXXRecordDecl *FinalType;
1210 if (NewEntriesSize == MostDerivedPathLength) {
1211 ResultIsArray = MostDerivedIsArrayElement;
1212 FinalType = MostDerivedType;
1213 } else
1214 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1215 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1216 return false;
1217
1218 // Truncate the lvalue to the appropriate derived class.
1219 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1220 ResultIsArray);
1221 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001222}
1223
Mike Stumpc4c90452009-10-27 22:09:17 +00001224namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001225enum EvalStmtResult {
1226 /// Evaluation failed.
1227 ESR_Failed,
1228 /// Hit a 'return' statement.
1229 ESR_Returned,
1230 /// Evaluation succeeded.
1231 ESR_Succeeded
1232};
1233}
1234
1235// Evaluate a statement.
Richard Smith47a1eed2011-10-29 20:57:55 +00001236static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001237 const Stmt *S) {
1238 switch (S->getStmtClass()) {
1239 default:
1240 return ESR_Failed;
1241
1242 case Stmt::NullStmtClass:
1243 case Stmt::DeclStmtClass:
1244 return ESR_Succeeded;
1245
1246 case Stmt::ReturnStmtClass:
1247 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1248 return ESR_Returned;
1249 return ESR_Failed;
1250
1251 case Stmt::CompoundStmtClass: {
1252 const CompoundStmt *CS = cast<CompoundStmt>(S);
1253 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1254 BE = CS->body_end(); BI != BE; ++BI) {
1255 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1256 if (ESR != ESR_Succeeded)
1257 return ESR;
1258 }
1259 return ESR_Succeeded;
1260 }
1261 }
1262}
1263
Richard Smith180f4792011-11-10 06:34:14 +00001264namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001265typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001266}
1267
1268/// EvaluateArgs - Evaluate the arguments to a function call.
1269static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1270 EvalInfo &Info) {
1271 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1272 I != E; ++I)
1273 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1274 return false;
1275 return true;
1276}
1277
Richard Smithd0dccea2011-10-28 22:34:42 +00001278/// Evaluate a function call.
Richard Smith59efe262011-11-11 04:05:33 +00001279static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args,
1280 const Stmt *Body, EvalInfo &Info,
1281 CCValue &Result) {
Richard Smithc18c4232011-11-21 19:36:32 +00001282 if (Info.atCallLimit())
Richard Smithd0dccea2011-10-28 22:34:42 +00001283 return false;
1284
Richard Smith180f4792011-11-10 06:34:14 +00001285 ArgVector ArgValues(Args.size());
1286 if (!EvaluateArgs(Args, ArgValues, Info))
1287 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001288
Richard Smith180f4792011-11-10 06:34:14 +00001289 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001290 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1291}
1292
Richard Smith180f4792011-11-10 06:34:14 +00001293/// Evaluate a constructor call.
Richard Smith59efe262011-11-11 04:05:33 +00001294static bool HandleConstructorCall(const LValue &This,
1295 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001296 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001297 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001298 APValue &Result) {
Richard Smithc18c4232011-11-21 19:36:32 +00001299 if (Info.atCallLimit())
Richard Smith180f4792011-11-10 06:34:14 +00001300 return false;
1301
1302 ArgVector ArgValues(Args.size());
1303 if (!EvaluateArgs(Args, ArgValues, Info))
1304 return false;
1305
1306 CallStackFrame Frame(Info, &This, ArgValues.data());
1307
1308 // If it's a delegating constructor, just delegate.
1309 if (Definition->isDelegatingConstructor()) {
1310 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1311 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1312 }
1313
1314 // Reserve space for the struct members.
1315 const CXXRecordDecl *RD = Definition->getParent();
1316 if (!RD->isUnion())
1317 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1318 std::distance(RD->field_begin(), RD->field_end()));
1319
1320 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1321
1322 unsigned BasesSeen = 0;
1323#ifndef NDEBUG
1324 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1325#endif
1326 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1327 E = Definition->init_end(); I != E; ++I) {
1328 if ((*I)->isBaseInitializer()) {
1329 QualType BaseType((*I)->getBaseClass(), 0);
1330#ifndef NDEBUG
1331 // Non-virtual base classes are initialized in the order in the class
1332 // definition. We cannot have a virtual base class for a literal type.
1333 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1334 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1335 "base class initializers not in expected order");
1336 ++BaseIt;
1337#endif
1338 LValue Subobject = This;
1339 HandleLValueDirectBase(Info, Subobject, RD,
1340 BaseType->getAsCXXRecordDecl(), &Layout);
1341 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1342 Subobject, (*I)->getInit()))
1343 return false;
1344 } else if (FieldDecl *FD = (*I)->getMember()) {
1345 LValue Subobject = This;
1346 HandleLValueMember(Info, Subobject, FD, &Layout);
1347 if (RD->isUnion()) {
1348 Result = APValue(FD);
1349 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1350 Subobject, (*I)->getInit()))
1351 return false;
1352 } else if (!EvaluateConstantExpression(
1353 Result.getStructField(FD->getFieldIndex()),
1354 Info, Subobject, (*I)->getInit()))
1355 return false;
1356 } else {
1357 // FIXME: handle indirect field initializers
1358 return false;
1359 }
1360 }
1361
1362 return true;
1363}
1364
Richard Smithd0dccea2011-10-28 22:34:42 +00001365namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001366class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001367 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001368 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001369public:
1370
Richard Smith1e12c592011-10-16 21:26:27 +00001371 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001372
1373 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001374 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001375 return true;
1376 }
1377
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001378 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1379 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001380 return Visit(E->getResultExpr());
1381 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001382 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001383 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001384 return true;
1385 return false;
1386 }
John McCallf85e1932011-06-15 23:02:42 +00001387 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001388 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001389 return true;
1390 return false;
1391 }
1392 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001393 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001394 return true;
1395 return false;
1396 }
1397
Mike Stumpc4c90452009-10-27 22:09:17 +00001398 // We don't want to evaluate BlockExprs multiple times, as they generate
1399 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001400 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1401 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1402 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001403 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001404 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1405 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1406 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1407 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1408 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1409 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001410 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001411 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001412 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001413 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001414 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001415 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1416 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1417 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1418 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001419 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001420 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1421 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1422 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1423 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1424 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001425 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001426 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001427 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001428 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001429 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001430
1431 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001432 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001433 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1434 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001435 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001436 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001437 return false;
1438 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001439
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001440 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001441};
1442
John McCall56ca35d2011-02-17 10:25:35 +00001443class OpaqueValueEvaluation {
1444 EvalInfo &info;
1445 OpaqueValueExpr *opaqueValue;
1446
1447public:
1448 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1449 Expr *value)
1450 : info(info), opaqueValue(opaqueValue) {
1451
1452 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001453 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001454 this->opaqueValue = 0;
1455 return;
1456 }
John McCall56ca35d2011-02-17 10:25:35 +00001457 }
1458
1459 bool hasError() const { return opaqueValue == 0; }
1460
1461 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001462 // FIXME: This will not work for recursive constexpr functions using opaque
1463 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001464 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1465 }
1466};
1467
Mike Stumpc4c90452009-10-27 22:09:17 +00001468} // end anonymous namespace
1469
Eli Friedman4efaa272008-11-12 09:44:48 +00001470//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001471// Generic Evaluation
1472//===----------------------------------------------------------------------===//
1473namespace {
1474
1475template <class Derived, typename RetTy=void>
1476class ExprEvaluatorBase
1477 : public ConstStmtVisitor<Derived, RetTy> {
1478private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001479 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001480 return static_cast<Derived*>(this)->Success(V, E);
1481 }
1482 RetTy DerivedError(const Expr *E) {
1483 return static_cast<Derived*>(this)->Error(E);
1484 }
Richard Smithf10d9172011-10-11 21:43:33 +00001485 RetTy DerivedValueInitialization(const Expr *E) {
1486 return static_cast<Derived*>(this)->ValueInitialization(E);
1487 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001488
1489protected:
1490 EvalInfo &Info;
1491 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1492 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1493
Richard Smithf10d9172011-10-11 21:43:33 +00001494 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1495
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001496public:
1497 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1498
1499 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001500 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001501 }
1502 RetTy VisitExpr(const Expr *E) {
1503 return DerivedError(E);
1504 }
1505
1506 RetTy VisitParenExpr(const ParenExpr *E)
1507 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1508 RetTy VisitUnaryExtension(const UnaryOperator *E)
1509 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1510 RetTy VisitUnaryPlus(const UnaryOperator *E)
1511 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1512 RetTy VisitChooseExpr(const ChooseExpr *E)
1513 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1514 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1515 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001516 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1517 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001518 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1519 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001520
Richard Smithe24f5fc2011-11-17 22:56:20 +00001521 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1522 switch (E->getOpcode()) {
1523 default:
1524 return DerivedError(E);
1525
1526 case BO_Comma:
1527 VisitIgnoredValue(E->getLHS());
1528 return StmtVisitorTy::Visit(E->getRHS());
1529
1530 case BO_PtrMemD:
1531 case BO_PtrMemI: {
1532 LValue Obj;
1533 if (!HandleMemberPointerAccess(Info, E, Obj))
1534 return false;
1535 CCValue Result;
1536 if (!HandleLValueToRValueConversion(Info, E->getType(), Obj, Result))
1537 return false;
1538 return DerivedSuccess(Result, E);
1539 }
1540 }
1541 }
1542
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001543 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1544 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1545 if (opaque.hasError())
1546 return DerivedError(E);
1547
1548 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001549 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001550 return DerivedError(E);
1551
1552 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1553 }
1554
1555 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1556 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001557 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001558 return DerivedError(E);
1559
Richard Smithc49bd112011-10-28 17:51:58 +00001560 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001561 return StmtVisitorTy::Visit(EvalExpr);
1562 }
1563
1564 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001565 const CCValue *Value = Info.getOpaqueValue(E);
1566 if (!Value)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001567 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
1568 : DerivedError(E));
Richard Smith47a1eed2011-10-29 20:57:55 +00001569 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001570 }
Richard Smithf10d9172011-10-11 21:43:33 +00001571
Richard Smithd0dccea2011-10-28 22:34:42 +00001572 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001573 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00001574 QualType CalleeType = Callee->getType();
1575
Richard Smithd0dccea2011-10-28 22:34:42 +00001576 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001577 LValue *This = 0, ThisVal;
1578 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001579
Richard Smith59efe262011-11-11 04:05:33 +00001580 // Extract function decl and 'this' pointer from the callee.
1581 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001582 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1583 // Explicit bound member calls, such as x.f() or p->g();
1584 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
1585 return DerivedError(ME->getBase());
1586 This = &ThisVal;
1587 FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1588 if (!FD)
1589 return DerivedError(ME);
1590 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1591 // Indirect bound member calls ('.*' or '->*').
1592 const ValueDecl *Member = HandleMemberPointerAccess(Info, BE, ThisVal,
1593 false);
1594 This = &ThisVal;
1595 FD = dyn_cast_or_null<FunctionDecl>(Member);
1596 if (!FD)
1597 return DerivedError(Callee);
1598 } else
Richard Smith59efe262011-11-11 04:05:33 +00001599 return DerivedError(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001600 } else if (CalleeType->isFunctionPointerType()) {
1601 CCValue Call;
1602 if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001603 !Call.getLValueOffset().isZero())
Richard Smith59efe262011-11-11 04:05:33 +00001604 return DerivedError(Callee);
1605
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001606 FD = dyn_cast_or_null<FunctionDecl>(
1607 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001608 if (!FD)
1609 return DerivedError(Callee);
1610
1611 // Overloaded operator calls to member functions are represented as normal
1612 // calls with '*this' as the first argument.
1613 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1614 if (MD && !MD->isStatic()) {
1615 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1616 return false;
1617 This = &ThisVal;
1618 Args = Args.slice(1);
1619 }
1620
1621 // Don't call function pointers which have been cast to some other type.
1622 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1623 return DerivedError(E);
1624 } else
Devang Patel6142ca72011-11-10 17:47:39 +00001625 return DerivedError(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001626
1627 const FunctionDecl *Definition;
1628 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001629 CCValue CCResult;
1630 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001631
1632 if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
Richard Smith59efe262011-11-11 04:05:33 +00001633 HandleFunctionCall(This, Args, Body, Info, CCResult) &&
Richard Smith69c2c502011-11-04 05:33:44 +00001634 CheckConstantExpression(CCResult, Result))
1635 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001636
1637 return DerivedError(E);
1638 }
1639
Richard Smithc49bd112011-10-28 17:51:58 +00001640 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1641 return StmtVisitorTy::Visit(E->getInitializer());
1642 }
Richard Smithf10d9172011-10-11 21:43:33 +00001643 RetTy VisitInitListExpr(const InitListExpr *E) {
1644 if (Info.getLangOpts().CPlusPlus0x) {
1645 if (E->getNumInits() == 0)
1646 return DerivedValueInitialization(E);
1647 if (E->getNumInits() == 1)
1648 return StmtVisitorTy::Visit(E->getInit(0));
1649 }
1650 return DerivedError(E);
1651 }
1652 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1653 return DerivedValueInitialization(E);
1654 }
1655 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1656 return DerivedValueInitialization(E);
1657 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001658 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1659 return DerivedValueInitialization(E);
1660 }
Richard Smithf10d9172011-10-11 21:43:33 +00001661
Richard Smith180f4792011-11-10 06:34:14 +00001662 /// A member expression where the object is a prvalue is itself a prvalue.
1663 RetTy VisitMemberExpr(const MemberExpr *E) {
1664 assert(!E->isArrow() && "missing call to bound member function?");
1665
1666 CCValue Val;
1667 if (!Evaluate(Val, Info, E->getBase()))
1668 return false;
1669
1670 QualType BaseTy = E->getBase()->getType();
1671
1672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1673 if (!FD) return false;
1674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1675 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1677
1678 SubobjectDesignator Designator;
1679 Designator.addDecl(FD);
1680
1681 return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1682 DerivedSuccess(Val, E);
1683 }
1684
Richard Smithc49bd112011-10-28 17:51:58 +00001685 RetTy VisitCastExpr(const CastExpr *E) {
1686 switch (E->getCastKind()) {
1687 default:
1688 break;
1689
1690 case CK_NoOp:
1691 return StmtVisitorTy::Visit(E->getSubExpr());
1692
1693 case CK_LValueToRValue: {
1694 LValue LVal;
1695 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001696 CCValue RVal;
Richard Smithc49bd112011-10-28 17:51:58 +00001697 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1698 return DerivedSuccess(RVal, E);
1699 }
1700 break;
1701 }
1702 }
1703
1704 return DerivedError(E);
1705 }
1706
Richard Smith8327fad2011-10-24 18:44:57 +00001707 /// Visit a value which is evaluated, but whose value is ignored.
1708 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001709 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00001710 if (!Evaluate(Scratch, Info, E))
1711 Info.EvalStatus.HasSideEffects = true;
1712 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001713};
1714
1715}
1716
1717//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00001718// Common base class for lvalue and temporary evaluation.
1719//===----------------------------------------------------------------------===//
1720namespace {
1721template<class Derived>
1722class LValueExprEvaluatorBase
1723 : public ExprEvaluatorBase<Derived, bool> {
1724protected:
1725 LValue &Result;
1726 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1727 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1728
1729 bool Success(APValue::LValueBase B) {
1730 Result.set(B);
1731 return true;
1732 }
1733
1734public:
1735 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1736 ExprEvaluatorBaseTy(Info), Result(Result) {}
1737
1738 bool Success(const CCValue &V, const Expr *E) {
1739 Result.setFrom(V);
1740 return true;
1741 }
1742 bool Error(const Expr *E) {
1743 return false;
1744 }
1745
1746 bool CheckValidLValue() {
1747 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1748 // there are no null references, nor once-past-the-end references.
1749 // FIXME: Check for one-past-the-end array indices
1750 return Result.Base && !Result.Designator.Invalid &&
1751 !Result.Designator.OnePastTheEnd;
1752 }
1753
1754 bool VisitMemberExpr(const MemberExpr *E) {
1755 // Handle non-static data members.
1756 QualType BaseTy;
1757 if (E->isArrow()) {
1758 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1759 return false;
1760 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1761 } else {
1762 if (!this->Visit(E->getBase()))
1763 return false;
1764 BaseTy = E->getBase()->getType();
1765 }
1766 // FIXME: In C++11, require the result to be a valid lvalue.
1767
1768 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1769 // FIXME: Handle IndirectFieldDecls
1770 if (!FD) return false;
1771 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1772 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1773 (void)BaseTy;
1774
1775 HandleLValueMember(this->Info, Result, FD);
1776
1777 if (FD->getType()->isReferenceType()) {
1778 CCValue RefValue;
1779 if (!HandleLValueToRValueConversion(this->Info, FD->getType(), Result,
1780 RefValue))
1781 return false;
1782 return Success(RefValue, E);
1783 }
1784 return true;
1785 }
1786
1787 bool VisitBinaryOperator(const BinaryOperator *E) {
1788 switch (E->getOpcode()) {
1789 default:
1790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
1791
1792 case BO_PtrMemD:
1793 case BO_PtrMemI:
1794 return HandleMemberPointerAccess(this->Info, E, Result);
1795 }
1796 }
1797
1798 bool VisitCastExpr(const CastExpr *E) {
1799 switch (E->getCastKind()) {
1800 default:
1801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1802
1803 case CK_DerivedToBase:
1804 case CK_UncheckedDerivedToBase: {
1805 if (!this->Visit(E->getSubExpr()))
1806 return false;
1807 if (!CheckValidLValue())
1808 return false;
1809
1810 // Now figure out the necessary offset to add to the base LV to get from
1811 // the derived class to the base class.
1812 QualType Type = E->getSubExpr()->getType();
1813
1814 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1815 PathE = E->path_end(); PathI != PathE; ++PathI) {
1816 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
1817 *PathI))
1818 return false;
1819 Type = (*PathI)->getType();
1820 }
1821
1822 return true;
1823 }
1824 }
1825 }
1826};
1827}
1828
1829//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00001830// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00001831//
1832// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1833// function designators (in C), decl references to void objects (in C), and
1834// temporaries (if building with -Wno-address-of-temporary).
1835//
1836// LValue evaluation produces values comprising a base expression of one of the
1837// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001838// - Declarations
1839// * VarDecl
1840// * FunctionDecl
1841// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00001842// * CompoundLiteralExpr in C
1843// * StringLiteral
1844// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00001845// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00001846// * ObjCEncodeExpr
1847// * AddrLabelExpr
1848// * BlockExpr
1849// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001850// - Locals and temporaries
1851// * Any Expr, with a Frame indicating the function in which the temporary was
1852// evaluated.
1853// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00001854//===----------------------------------------------------------------------===//
1855namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001856class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00001857 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00001858public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00001859 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
1860 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Richard Smithc49bd112011-10-28 17:51:58 +00001862 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1863
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001864 bool VisitDeclRefExpr(const DeclRefExpr *E);
1865 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00001866 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001867 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1868 bool VisitMemberExpr(const MemberExpr *E);
1869 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1870 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1871 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1872 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001873
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001874 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00001875 switch (E->getCastKind()) {
1876 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00001877 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001878
Eli Friedmandb924222011-10-11 00:13:24 +00001879 case CK_LValueBitCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00001880 if (!Visit(E->getSubExpr()))
1881 return false;
1882 Result.Designator.setInvalid();
1883 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00001884
Richard Smithe24f5fc2011-11-17 22:56:20 +00001885 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00001886 if (!Visit(E->getSubExpr()))
1887 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001888 if (!CheckValidLValue())
1889 return false;
1890 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00001891 }
1892 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00001893
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001894 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001895
Eli Friedman4efaa272008-11-12 09:44:48 +00001896};
1897} // end anonymous namespace
1898
Richard Smithc49bd112011-10-28 17:51:58 +00001899/// Evaluate an expression as an lvalue. This can be legitimately called on
1900/// expressions which are not glvalues, in a few cases:
1901/// * function designators in C,
1902/// * "extern void" objects,
1903/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00001904static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00001905 assert((E->isGLValue() || E->getType()->isFunctionType() ||
1906 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1907 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001908 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001909}
1910
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001911bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001912 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
1913 return Success(FD);
1914 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00001915 return VisitVarDecl(E, VD);
1916 return Error(E);
1917}
Richard Smith436c8892011-10-24 23:14:33 +00001918
Richard Smithc49bd112011-10-28 17:51:58 +00001919bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00001920 if (!VD->getType()->isReferenceType()) {
1921 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001922 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00001923 return true;
1924 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001925 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00001926 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00001927
Richard Smith47a1eed2011-10-29 20:57:55 +00001928 CCValue V;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001929 if (EvaluateVarDeclInit(Info, VD, Info.CurrentCall, V))
Richard Smith47a1eed2011-10-29 20:57:55 +00001930 return Success(V, E);
Richard Smithc49bd112011-10-28 17:51:58 +00001931
1932 return Error(E);
Anders Carlsson35873c42008-11-24 04:41:22 +00001933}
1934
Richard Smithbd552ef2011-10-31 05:52:43 +00001935bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1936 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001937 if (E->GetTemporaryExpr()->isRValue()) {
1938 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
1939 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
1940
1941 Result.set(E, Info.CurrentCall);
1942 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1943 Result, E->GetTemporaryExpr());
1944 }
1945
1946 // Materialization of an lvalue temporary occurs when we need to force a copy
1947 // (for instance, if it's a bitfield).
1948 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
1949 if (!Visit(E->GetTemporaryExpr()))
1950 return false;
1951 if (!HandleLValueToRValueConversion(Info, E->getType(), Result,
1952 Info.CurrentCall->Temporaries[E]))
1953 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001954 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00001956}
1957
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001958bool
1959LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001960 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1961 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1962 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00001963 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001964}
1965
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001966bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001967 // Handle static data members.
1968 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1969 VisitIgnoredValue(E->getBase());
1970 return VisitVarDecl(E, VD);
1971 }
1972
Richard Smithd0dccea2011-10-28 22:34:42 +00001973 // Handle static member functions.
1974 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1975 if (MD->isStatic()) {
1976 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001977 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00001978 }
1979 }
1980
Richard Smith180f4792011-11-10 06:34:14 +00001981 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001982 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001983}
1984
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001985bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00001986 // FIXME: Deal with vectors as array subscript bases.
1987 if (E->getBase()->getType()->isVectorType())
1988 return false;
1989
Anders Carlsson3068d112008-11-16 19:01:22 +00001990 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001991 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Anders Carlsson3068d112008-11-16 19:01:22 +00001993 APSInt Index;
1994 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00001995 return false;
Richard Smith180f4792011-11-10 06:34:14 +00001996 int64_t IndexValue
1997 = Index.isSigned() ? Index.getSExtValue()
1998 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00001999
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002001 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002002}
Eli Friedman4efaa272008-11-12 09:44:48 +00002003
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002004bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002005 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002006 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002007}
2008
Eli Friedman4efaa272008-11-12 09:44:48 +00002009//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002010// Pointer Evaluation
2011//===----------------------------------------------------------------------===//
2012
Anders Carlssonc754aa62008-07-08 05:13:58 +00002013namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002014class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002015 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002016 LValue &Result;
2017
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002018 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002019 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002020 return true;
2021 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002022public:
Mike Stump1eb44332009-09-09 15:08:12 +00002023
John McCallefdb83e2010-05-07 21:00:08 +00002024 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002025 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002026
Richard Smith47a1eed2011-10-29 20:57:55 +00002027 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002028 Result.setFrom(V);
2029 return true;
2030 }
2031 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +00002032 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +00002033 }
Richard Smithf10d9172011-10-11 21:43:33 +00002034 bool ValueInitialization(const Expr *E) {
2035 return Success((Expr*)0);
2036 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002037
John McCallefdb83e2010-05-07 21:00:08 +00002038 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002039 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002040 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002041 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002042 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002043 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002044 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002045 bool VisitCallExpr(const CallExpr *E);
2046 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002047 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002048 return Success(E);
2049 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +00002050 }
Richard Smith180f4792011-11-10 06:34:14 +00002051 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2052 if (!Info.CurrentCall->This)
2053 return false;
2054 Result = *Info.CurrentCall->This;
2055 return true;
2056 }
John McCall56ca35d2011-02-17 10:25:35 +00002057
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002058 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002059};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002060} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002061
John McCallefdb83e2010-05-07 21:00:08 +00002062static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002063 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002064 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002065}
2066
John McCallefdb83e2010-05-07 21:00:08 +00002067bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002068 if (E->getOpcode() != BO_Add &&
2069 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002072 const Expr *PExp = E->getLHS();
2073 const Expr *IExp = E->getRHS();
2074 if (IExp->getType()->isPointerType())
2075 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002076
John McCallefdb83e2010-05-07 21:00:08 +00002077 if (!EvaluatePointer(PExp, Result, Info))
2078 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002079
John McCallefdb83e2010-05-07 21:00:08 +00002080 llvm::APSInt Offset;
2081 if (!EvaluateInteger(IExp, Offset, Info))
2082 return false;
2083 int64_t AdditionalOffset
2084 = Offset.isSigned() ? Offset.getSExtValue()
2085 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002086 if (E->getOpcode() == BO_Sub)
2087 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002088
Richard Smith180f4792011-11-10 06:34:14 +00002089 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002090 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002091 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002092}
Eli Friedman4efaa272008-11-12 09:44:48 +00002093
John McCallefdb83e2010-05-07 21:00:08 +00002094bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2095 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002096}
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002098bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2099 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002100
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002101 switch (E->getCastKind()) {
2102 default:
2103 break;
2104
John McCall2de56d12010-08-25 11:45:40 +00002105 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002106 case CK_CPointerToObjCPointerCast:
2107 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002108 case CK_AnyPointerToBlockPointerCast:
Richard Smith0a3bdb62011-11-04 02:25:55 +00002109 if (!Visit(SubExpr))
2110 return false;
2111 Result.Designator.setInvalid();
2112 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002113
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002114 case CK_DerivedToBase:
2115 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002116 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002117 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002118 if (!Result.Base && Result.Offset.isZero())
2119 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002120
Richard Smith180f4792011-11-10 06:34:14 +00002121 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002122 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002123 QualType Type =
2124 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002125
Richard Smith180f4792011-11-10 06:34:14 +00002126 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002127 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002128 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002129 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002130 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002131 }
2132
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002133 return true;
2134 }
2135
Richard Smithe24f5fc2011-11-17 22:56:20 +00002136 case CK_BaseToDerived:
2137 if (!Visit(E->getSubExpr()))
2138 return false;
2139 if (!Result.Base && Result.Offset.isZero())
2140 return true;
2141 return HandleBaseToDerivedCast(Info, E, Result);
2142
Richard Smith47a1eed2011-10-29 20:57:55 +00002143 case CK_NullToPointer:
2144 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002145
John McCall2de56d12010-08-25 11:45:40 +00002146 case CK_IntegralToPointer: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002147 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002148 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002149 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002150
John McCallefdb83e2010-05-07 21:00:08 +00002151 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002152 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2153 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002154 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002155 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002156 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002157 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002158 return true;
2159 } else {
2160 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002161 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002162 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002163 }
2164 }
John McCall2de56d12010-08-25 11:45:40 +00002165 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002166 if (SubExpr->isGLValue()) {
2167 if (!EvaluateLValue(SubExpr, Result, Info))
2168 return false;
2169 } else {
2170 Result.set(SubExpr, Info.CurrentCall);
2171 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2172 Info, Result, SubExpr))
2173 return false;
2174 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002175 // The result is a pointer to the first element of the array.
2176 Result.Designator.addIndex(0);
2177 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002178
John McCall2de56d12010-08-25 11:45:40 +00002179 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002180 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002181 }
2182
Richard Smithc49bd112011-10-28 17:51:58 +00002183 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002184}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002185
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002186bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002187 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002188 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002189
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002190 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002191}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002192
2193//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002194// Member Pointer Evaluation
2195//===----------------------------------------------------------------------===//
2196
2197namespace {
2198class MemberPointerExprEvaluator
2199 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2200 MemberPtr &Result;
2201
2202 bool Success(const ValueDecl *D) {
2203 Result = MemberPtr(D);
2204 return true;
2205 }
2206public:
2207
2208 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2209 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2210
2211 bool Success(const CCValue &V, const Expr *E) {
2212 Result.setFrom(V);
2213 return true;
2214 }
2215 bool Error(const Stmt *S) {
2216 return false;
2217 }
2218 bool ValueInitialization(const Expr *E) {
2219 return Success((const ValueDecl*)0);
2220 }
2221
2222 bool VisitCastExpr(const CastExpr *E);
2223 bool VisitUnaryAddrOf(const UnaryOperator *E);
2224};
2225} // end anonymous namespace
2226
2227static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2228 EvalInfo &Info) {
2229 assert(E->isRValue() && E->getType()->isMemberPointerType());
2230 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2231}
2232
2233bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2234 switch (E->getCastKind()) {
2235 default:
2236 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2237
2238 case CK_NullToMemberPointer:
2239 return ValueInitialization(E);
2240
2241 case CK_BaseToDerivedMemberPointer: {
2242 if (!Visit(E->getSubExpr()))
2243 return false;
2244 if (E->path_empty())
2245 return true;
2246 // Base-to-derived member pointer casts store the path in derived-to-base
2247 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2248 // the wrong end of the derived->base arc, so stagger the path by one class.
2249 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2250 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2251 PathI != PathE; ++PathI) {
2252 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2253 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2254 if (!Result.castToDerived(Derived))
2255 return false;
2256 }
2257 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2258 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
2259 return false;
2260 return true;
2261 }
2262
2263 case CK_DerivedToBaseMemberPointer:
2264 if (!Visit(E->getSubExpr()))
2265 return false;
2266 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2267 PathE = E->path_end(); PathI != PathE; ++PathI) {
2268 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2269 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2270 if (!Result.castToBase(Base))
2271 return false;
2272 }
2273 return true;
2274 }
2275}
2276
2277bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2278 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2279 // member can be formed.
2280 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2281}
2282
2283//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002284// Record Evaluation
2285//===----------------------------------------------------------------------===//
2286
2287namespace {
2288 class RecordExprEvaluator
2289 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2290 const LValue &This;
2291 APValue &Result;
2292 public:
2293
2294 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2295 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2296
2297 bool Success(const CCValue &V, const Expr *E) {
2298 return CheckConstantExpression(V, Result);
2299 }
2300 bool Error(const Expr *E) { return false; }
2301
Richard Smith59efe262011-11-11 04:05:33 +00002302 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002303 bool VisitInitListExpr(const InitListExpr *E);
2304 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2305 };
2306}
2307
Richard Smith59efe262011-11-11 04:05:33 +00002308bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2309 switch (E->getCastKind()) {
2310 default:
2311 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2312
2313 case CK_ConstructorConversion:
2314 return Visit(E->getSubExpr());
2315
2316 case CK_DerivedToBase:
2317 case CK_UncheckedDerivedToBase: {
2318 CCValue DerivedObject;
2319 if (!Evaluate(DerivedObject, Info, E->getSubExpr()) ||
2320 !DerivedObject.isStruct())
2321 return false;
2322
2323 // Derived-to-base rvalue conversion: just slice off the derived part.
2324 APValue *Value = &DerivedObject;
2325 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2326 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2327 PathE = E->path_end(); PathI != PathE; ++PathI) {
2328 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2329 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2330 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2331 RD = Base;
2332 }
2333 Result = *Value;
2334 return true;
2335 }
2336 }
2337}
2338
Richard Smith180f4792011-11-10 06:34:14 +00002339bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2340 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2341 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2342
2343 if (RD->isUnion()) {
2344 Result = APValue(E->getInitializedFieldInUnion());
2345 if (!E->getNumInits())
2346 return true;
2347 LValue Subobject = This;
2348 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2349 &Layout);
2350 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2351 Subobject, E->getInit(0));
2352 }
2353
2354 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2355 "initializer list for class with base classes");
2356 Result = APValue(APValue::UninitStruct(), 0,
2357 std::distance(RD->field_begin(), RD->field_end()));
2358 unsigned ElementNo = 0;
2359 for (RecordDecl::field_iterator Field = RD->field_begin(),
2360 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2361 // Anonymous bit-fields are not considered members of the class for
2362 // purposes of aggregate initialization.
2363 if (Field->isUnnamedBitfield())
2364 continue;
2365
2366 LValue Subobject = This;
2367 HandleLValueMember(Info, Subobject, *Field, &Layout);
2368
2369 if (ElementNo < E->getNumInits()) {
2370 if (!EvaluateConstantExpression(
2371 Result.getStructField((*Field)->getFieldIndex()),
2372 Info, Subobject, E->getInit(ElementNo++)))
2373 return false;
2374 } else {
2375 // Perform an implicit value-initialization for members beyond the end of
2376 // the initializer list.
2377 ImplicitValueInitExpr VIE(Field->getType());
2378 if (!EvaluateConstantExpression(
2379 Result.getStructField((*Field)->getFieldIndex()),
2380 Info, Subobject, &VIE))
2381 return false;
2382 }
2383 }
2384
2385 return true;
2386}
2387
2388bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2389 const CXXConstructorDecl *FD = E->getConstructor();
2390 const FunctionDecl *Definition = 0;
2391 FD->getBody(Definition);
2392
2393 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
2394 return false;
2395
2396 // FIXME: Elide the copy/move construction wherever we can.
2397 if (E->isElidable())
2398 if (const MaterializeTemporaryExpr *ME
2399 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2400 return Visit(ME->GetTemporaryExpr());
2401
2402 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith59efe262011-11-11 04:05:33 +00002403 return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition),
2404 Info, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002405}
2406
2407static bool EvaluateRecord(const Expr *E, const LValue &This,
2408 APValue &Result, EvalInfo &Info) {
2409 assert(E->isRValue() && E->getType()->isRecordType() &&
2410 E->getType()->isLiteralType() &&
2411 "can't evaluate expression as a record rvalue");
2412 return RecordExprEvaluator(Info, This, Result).Visit(E);
2413}
2414
2415//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002416// Temporary Evaluation
2417//
2418// Temporaries are represented in the AST as rvalues, but generally behave like
2419// lvalues. The full-object of which the temporary is a subobject is implicitly
2420// materialized so that a reference can bind to it.
2421//===----------------------------------------------------------------------===//
2422namespace {
2423class TemporaryExprEvaluator
2424 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2425public:
2426 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2427 LValueExprEvaluatorBaseTy(Info, Result) {}
2428
2429 /// Visit an expression which constructs the value of this temporary.
2430 bool VisitConstructExpr(const Expr *E) {
2431 Result.set(E, Info.CurrentCall);
2432 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2433 Result, E);
2434 }
2435
2436 bool VisitCastExpr(const CastExpr *E) {
2437 switch (E->getCastKind()) {
2438 default:
2439 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2440
2441 case CK_ConstructorConversion:
2442 return VisitConstructExpr(E->getSubExpr());
2443 }
2444 }
2445 bool VisitInitListExpr(const InitListExpr *E) {
2446 return VisitConstructExpr(E);
2447 }
2448 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2449 return VisitConstructExpr(E);
2450 }
2451 bool VisitCallExpr(const CallExpr *E) {
2452 return VisitConstructExpr(E);
2453 }
2454};
2455} // end anonymous namespace
2456
2457/// Evaluate an expression of record type as a temporary.
2458static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2459 assert(E->isRValue() && E->getType()->isRecordType() &&
2460 E->getType()->isLiteralType());
2461 return TemporaryExprEvaluator(Info, Result).Visit(E);
2462}
2463
2464//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002465// Vector Evaluation
2466//===----------------------------------------------------------------------===//
2467
2468namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002469 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002470 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2471 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002472 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Richard Smith07fc6572011-10-22 21:10:00 +00002474 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2475 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Richard Smith07fc6572011-10-22 21:10:00 +00002477 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2478 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2479 // FIXME: remove this APValue copy.
2480 Result = APValue(V.data(), V.size());
2481 return true;
2482 }
Richard Smith69c2c502011-11-04 05:33:44 +00002483 bool Success(const CCValue &V, const Expr *E) {
2484 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002485 Result = V;
2486 return true;
2487 }
2488 bool Error(const Expr *E) { return false; }
2489 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002490
Richard Smith07fc6572011-10-22 21:10:00 +00002491 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002492 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002493 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002494 bool VisitInitListExpr(const InitListExpr *E);
2495 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002496 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002497 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002498 // shufflevector, ExtVectorElementExpr
2499 // (Note that these require implementing conversions
2500 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002501 };
2502} // end anonymous namespace
2503
2504static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002505 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002506 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002507}
2508
Richard Smith07fc6572011-10-22 21:10:00 +00002509bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2510 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002511 QualType EltTy = VTy->getElementType();
2512 unsigned NElts = VTy->getNumElements();
2513 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002514
Nate Begeman59b5da62009-01-18 03:20:47 +00002515 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002516 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002517
Eli Friedman46a52322011-03-25 00:43:55 +00002518 switch (E->getCastKind()) {
2519 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002520 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002521 if (SETy->isIntegerType()) {
2522 APSInt IntResult;
2523 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002524 return Error(E);
2525 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002526 } else if (SETy->isRealFloatingType()) {
2527 APFloat F(0.0);
2528 if (!EvaluateFloat(SE, F, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002529 return Error(E);
2530 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002531 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002532 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002533 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002534
2535 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002536 SmallVector<APValue, 4> Elts(NElts, Val);
2537 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002538 }
Eli Friedman46a52322011-03-25 00:43:55 +00002539 case CK_BitCast: {
Richard Smith07fc6572011-10-22 21:10:00 +00002540 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedman46a52322011-03-25 00:43:55 +00002541 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002542 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002543
Eli Friedman46a52322011-03-25 00:43:55 +00002544 if (!SETy->isIntegerType())
Richard Smith07fc6572011-10-22 21:10:00 +00002545 return Error(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002546
Eli Friedman46a52322011-03-25 00:43:55 +00002547 APSInt Init;
2548 if (!EvaluateInteger(SE, Init, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002549 return Error(E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002550
Eli Friedman46a52322011-03-25 00:43:55 +00002551 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
2552 "Vectors must be composed of ints or floats");
2553
Chris Lattner5f9e2722011-07-23 10:55:15 +00002554 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +00002555 for (unsigned i = 0; i != NElts; ++i) {
2556 APSInt Tmp = Init.extOrTrunc(EltWidth);
2557
2558 if (EltTy->isIntegerType())
2559 Elts.push_back(APValue(Tmp));
2560 else
2561 Elts.push_back(APValue(APFloat(Tmp)));
2562
2563 Init >>= EltWidth;
2564 }
Richard Smith07fc6572011-10-22 21:10:00 +00002565 return Success(Elts, E);
Nate Begemanc0b8b192009-07-01 07:50:47 +00002566 }
Eli Friedman46a52322011-03-25 00:43:55 +00002567 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002568 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002569 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002570}
2571
Richard Smith07fc6572011-10-22 21:10:00 +00002572bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002573VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002574 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002575 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002576 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002577
Nate Begeman59b5da62009-01-18 03:20:47 +00002578 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002579 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002580
John McCalla7d6c222010-06-11 17:54:15 +00002581 // If a vector is initialized with a single element, that value
2582 // becomes every element of the vector, not just the first.
2583 // This is the behavior described in the IBM AltiVec documentation.
2584 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002585
2586 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002587 // vector (OpenCL 6.1.6).
2588 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002589 return Visit(E->getInit(0));
2590
John McCalla7d6c222010-06-11 17:54:15 +00002591 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002592 if (EltTy->isIntegerType()) {
2593 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002594 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002595 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002596 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002597 } else {
2598 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002599 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002600 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002601 InitValue = APValue(f);
2602 }
2603 for (unsigned i = 0; i < NumElements; i++) {
2604 Elements.push_back(InitValue);
2605 }
2606 } else {
2607 for (unsigned i = 0; i < NumElements; i++) {
2608 if (EltTy->isIntegerType()) {
2609 llvm::APSInt sInt(32);
2610 if (i < NumInits) {
2611 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002612 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002613 } else {
2614 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2615 }
2616 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002617 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002618 llvm::APFloat f(0.0);
2619 if (i < NumInits) {
2620 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith07fc6572011-10-22 21:10:00 +00002621 return Error(E);
John McCalla7d6c222010-06-11 17:54:15 +00002622 } else {
2623 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2624 }
2625 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002626 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002627 }
2628 }
Richard Smith07fc6572011-10-22 21:10:00 +00002629 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002630}
2631
Richard Smith07fc6572011-10-22 21:10:00 +00002632bool
2633VectorExprEvaluator::ValueInitialization(const Expr *E) {
2634 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002635 QualType EltTy = VT->getElementType();
2636 APValue ZeroElement;
2637 if (EltTy->isIntegerType())
2638 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2639 else
2640 ZeroElement =
2641 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2642
Chris Lattner5f9e2722011-07-23 10:55:15 +00002643 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002644 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002645}
2646
Richard Smith07fc6572011-10-22 21:10:00 +00002647bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002648 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002649 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002650}
2651
Nate Begeman59b5da62009-01-18 03:20:47 +00002652//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002653// Array Evaluation
2654//===----------------------------------------------------------------------===//
2655
2656namespace {
2657 class ArrayExprEvaluator
2658 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002659 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002660 APValue &Result;
2661 public:
2662
Richard Smith180f4792011-11-10 06:34:14 +00002663 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2664 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002665
2666 bool Success(const APValue &V, const Expr *E) {
2667 assert(V.isArray() && "Expected array type");
2668 Result = V;
2669 return true;
2670 }
2671 bool Error(const Expr *E) { return false; }
2672
Richard Smith180f4792011-11-10 06:34:14 +00002673 bool ValueInitialization(const Expr *E) {
2674 const ConstantArrayType *CAT =
2675 Info.Ctx.getAsConstantArrayType(E->getType());
2676 if (!CAT)
2677 return false;
2678
2679 Result = APValue(APValue::UninitArray(), 0,
2680 CAT->getSize().getZExtValue());
2681 if (!Result.hasArrayFiller()) return true;
2682
2683 // Value-initialize all elements.
2684 LValue Subobject = This;
2685 Subobject.Designator.addIndex(0);
2686 ImplicitValueInitExpr VIE(CAT->getElementType());
2687 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2688 Subobject, &VIE);
2689 }
2690
Richard Smithcc5d4f62011-11-07 09:22:26 +00002691 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002692 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002693 };
2694} // end anonymous namespace
2695
Richard Smith180f4792011-11-10 06:34:14 +00002696static bool EvaluateArray(const Expr *E, const LValue &This,
2697 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002698 assert(E->isRValue() && E->getType()->isArrayType() &&
2699 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002700 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002701}
2702
2703bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2704 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2705 if (!CAT)
2706 return false;
2707
2708 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2709 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002710 LValue Subobject = This;
2711 Subobject.Designator.addIndex(0);
2712 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002713 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00002714 I != End; ++I, ++Index) {
2715 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2716 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00002717 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002718 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2719 return false;
2720 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002721
2722 if (!Result.hasArrayFiller()) return true;
2723 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00002724 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2725 // but sometimes does:
2726 // struct S { constexpr S() : p(&p) {} void *p; };
2727 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00002728 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00002729 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00002730}
2731
Richard Smithe24f5fc2011-11-17 22:56:20 +00002732bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2733 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2734 if (!CAT)
2735 return false;
2736
2737 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2738 if (!Result.hasArrayFiller())
2739 return true;
2740
2741 const CXXConstructorDecl *FD = E->getConstructor();
2742 const FunctionDecl *Definition = 0;
2743 FD->getBody(Definition);
2744
2745 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
2746 return false;
2747
2748 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2749 // but sometimes does:
2750 // struct S { constexpr S() : p(&p) {} void *p; };
2751 // S s[10];
2752 LValue Subobject = This;
2753 Subobject.Designator.addIndex(0);
2754 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2755 return HandleConstructorCall(Subobject, Args,
2756 cast<CXXConstructorDecl>(Definition),
2757 Info, Result.getArrayFiller());
2758}
2759
Richard Smithcc5d4f62011-11-07 09:22:26 +00002760//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002761// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002762//
2763// As a GNU extension, we support casting pointers to sufficiently-wide integer
2764// types and back in constant folding. Integer values are thus represented
2765// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002766//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002767
2768namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002769class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002770 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00002771 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00002772public:
Richard Smith47a1eed2011-10-29 20:57:55 +00002773 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002774 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002775
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002776 bool Success(const llvm::APSInt &SI, const Expr *E) {
2777 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002778 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002779 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002780 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002781 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002782 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002783 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002784 return true;
2785 }
2786
Daniel Dunbar131eb432009-02-19 09:06:44 +00002787 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002788 assert(E->getType()->isIntegralOrEnumerationType() &&
2789 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002790 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002791 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002792 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00002793 Result.getInt().setIsUnsigned(
2794 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00002795 return true;
2796 }
2797
2798 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002799 assert(E->getType()->isIntegralOrEnumerationType() &&
2800 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002801 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00002802 return true;
2803 }
2804
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00002805 bool Success(CharUnits Size, const Expr *E) {
2806 return Success(Size.getQuantity(), E);
2807 }
2808
2809
Anders Carlsson82206e22008-11-30 18:14:57 +00002810 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00002811 // Take the first error.
Richard Smith1e12c592011-10-16 21:26:27 +00002812 if (Info.EvalStatus.Diag == 0) {
2813 Info.EvalStatus.DiagLoc = L;
2814 Info.EvalStatus.Diag = D;
2815 Info.EvalStatus.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +00002816 }
Chris Lattner54176fd2008-07-12 00:14:42 +00002817 return false;
Chris Lattner7a767782008-07-11 19:24:49 +00002818 }
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Richard Smith47a1eed2011-10-29 20:57:55 +00002820 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00002821 if (V.isLValue()) {
2822 Result = V;
2823 return true;
2824 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002825 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00002826 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002827 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00002828 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00002829 }
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Richard Smithf10d9172011-10-11 21:43:33 +00002831 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2832
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002833 //===--------------------------------------------------------------------===//
2834 // Visitor Methods
2835 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00002836
Chris Lattner4c4867e2008-07-12 00:38:25 +00002837 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002838 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002839 }
2840 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002841 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00002842 }
Eli Friedman04309752009-11-24 05:28:59 +00002843
2844 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2845 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002846 if (CheckReferencedDecl(E, E->getDecl()))
2847 return true;
2848
2849 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002850 }
2851 bool VisitMemberExpr(const MemberExpr *E) {
2852 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00002853 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00002854 return true;
2855 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002856
2857 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00002858 }
2859
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002860 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002861 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002862 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00002863 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00002864
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002865 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002866 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00002867
Anders Carlsson3068d112008-11-16 19:01:22 +00002868 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00002869 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00002870 }
Mike Stump1eb44332009-09-09 15:08:12 +00002871
Richard Smithf10d9172011-10-11 21:43:33 +00002872 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00002873 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002874 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00002875 }
2876
Sebastian Redl64b45f72009-01-05 20:52:13 +00002877 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00002878 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002879 }
2880
Francois Pichet6ad6f282010-12-07 00:08:36 +00002881 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2882 return Success(E->getValue(), E);
2883 }
2884
John Wiegley21ff2e52011-04-28 00:16:57 +00002885 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2886 return Success(E->getValue(), E);
2887 }
2888
John Wiegley55262202011-04-25 06:54:41 +00002889 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2890 return Success(E->getValue(), E);
2891 }
2892
Eli Friedman722c7172009-02-28 03:59:05 +00002893 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002894 bool VisitUnaryImag(const UnaryOperator *E);
2895
Sebastian Redl295995c2010-09-10 20:55:47 +00002896 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00002897 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00002898
Chris Lattnerfcee0012008-07-11 21:24:13 +00002899private:
Ken Dyck8b752f12010-01-27 17:10:57 +00002900 CharUnits GetAlignOfExpr(const Expr *E);
2901 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002902 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002903 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00002904 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00002905};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002906} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002907
Richard Smithc49bd112011-10-28 17:51:58 +00002908/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2909/// produce either the integer value or a pointer.
2910///
2911/// GCC has a heinous extension which folds casts between pointer types and
2912/// pointer-sized integral types. We support this by allowing the evaluation of
2913/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2914/// Some simple arithmetic on such values is supported (they are treated much
2915/// like char*).
Richard Smith47a1eed2011-10-29 20:57:55 +00002916static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2917 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002918 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002919 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002920}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002921
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002922static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002923 CCValue Val;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002924 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2925 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002926 Result = Val.getInt();
2927 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00002928}
Anders Carlsson650c92f2008-07-08 15:34:11 +00002929
Eli Friedman04309752009-11-24 05:28:59 +00002930bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00002931 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002932 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002933 // Check for signedness/width mismatches between E type and ECD value.
2934 bool SameSign = (ECD->getInitVal().isSigned()
2935 == E->getType()->isSignedIntegerOrEnumerationType());
2936 bool SameWidth = (ECD->getInitVal().getBitWidth()
2937 == Info.Ctx.getIntWidth(E->getType()));
2938 if (SameSign && SameWidth)
2939 return Success(ECD->getInitVal(), E);
2940 else {
2941 // Get rid of mismatch (otherwise Success assertions will fail)
2942 // by computing a new value matching the type of E.
2943 llvm::APSInt Val = ECD->getInitVal();
2944 if (!SameSign)
2945 Val.setIsSigned(!ECD->getInitVal().isSigned());
2946 if (!SameWidth)
2947 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2948 return Success(Val, E);
2949 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00002950 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002951 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00002952}
2953
Chris Lattnera4d55d82008-10-06 06:40:35 +00002954/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2955/// as GCC.
2956static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2957 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002958 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00002959 enum gcc_type_class {
2960 no_type_class = -1,
2961 void_type_class, integer_type_class, char_type_class,
2962 enumeral_type_class, boolean_type_class,
2963 pointer_type_class, reference_type_class, offset_type_class,
2964 real_type_class, complex_type_class,
2965 function_type_class, method_type_class,
2966 record_type_class, union_type_class,
2967 array_type_class, string_type_class,
2968 lang_type_class
2969 };
Mike Stump1eb44332009-09-09 15:08:12 +00002970
2971 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00002972 // ideal, however it is what gcc does.
2973 if (E->getNumArgs() == 0)
2974 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Chris Lattnera4d55d82008-10-06 06:40:35 +00002976 QualType ArgTy = E->getArg(0)->getType();
2977 if (ArgTy->isVoidType())
2978 return void_type_class;
2979 else if (ArgTy->isEnumeralType())
2980 return enumeral_type_class;
2981 else if (ArgTy->isBooleanType())
2982 return boolean_type_class;
2983 else if (ArgTy->isCharType())
2984 return string_type_class; // gcc doesn't appear to use char_type_class
2985 else if (ArgTy->isIntegerType())
2986 return integer_type_class;
2987 else if (ArgTy->isPointerType())
2988 return pointer_type_class;
2989 else if (ArgTy->isReferenceType())
2990 return reference_type_class;
2991 else if (ArgTy->isRealType())
2992 return real_type_class;
2993 else if (ArgTy->isComplexType())
2994 return complex_type_class;
2995 else if (ArgTy->isFunctionType())
2996 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00002997 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00002998 return record_type_class;
2999 else if (ArgTy->isUnionType())
3000 return union_type_class;
3001 else if (ArgTy->isArrayType())
3002 return array_type_class;
3003 else if (ArgTy->isUnionType())
3004 return union_type_class;
3005 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003006 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003007 return -1;
3008}
3009
John McCall42c8f872010-05-10 23:27:23 +00003010/// Retrieves the "underlying object type" of the given expression,
3011/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003012QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3013 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3014 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003015 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003016 } else if (const Expr *E = B.get<const Expr*>()) {
3017 if (isa<CompoundLiteralExpr>(E))
3018 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003019 }
3020
3021 return QualType();
3022}
3023
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003024bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003025 // TODO: Perhaps we should let LLVM lower this?
3026 LValue Base;
3027 if (!EvaluatePointer(E->getArg(0), Base, Info))
3028 return false;
3029
3030 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003031 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003032
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003033 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003034 if (T.isNull() ||
3035 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003036 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003037 T->isVariablyModifiedType() ||
3038 T->isDependentType())
3039 return false;
3040
3041 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3042 CharUnits Offset = Base.getLValueOffset();
3043
3044 if (!Offset.isNegative() && Offset <= Size)
3045 Size -= Offset;
3046 else
3047 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003048 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003049}
3050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003052 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003053 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003054 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003055
3056 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003057 if (TryEvaluateBuiltinObjectSize(E))
3058 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003059
Eric Christopherb2aaf512010-01-19 22:58:35 +00003060 // If evaluating the argument has side-effects we can't determine
3061 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003062 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003063 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003064 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003065 return Success(0, E);
3066 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003067
Mike Stump64eda9e2009-10-26 18:35:08 +00003068 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3069 }
3070
Chris Lattner019f4e82008-10-06 05:28:25 +00003071 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003072 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003074 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00003075 // __builtin_constant_p always has one operand: it returns true if that
3076 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00003077 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003078
3079 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003080 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003081 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003082 return Success(Operand, E);
3083 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003084
3085 case Builtin::BI__builtin_expect:
3086 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003087
3088 case Builtin::BIstrlen:
3089 case Builtin::BI__builtin_strlen:
3090 // As an extension, we support strlen() and __builtin_strlen() as constant
3091 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003092 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003093 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3094 // The string literal may have embedded null characters. Find the first
3095 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003096 StringRef Str = S->getString();
3097 StringRef::size_type Pos = Str.find(0);
3098 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003099 Str = Str.substr(0, Pos);
3100
3101 return Success(Str.size(), E);
3102 }
3103
3104 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003105
3106 case Builtin::BI__atomic_is_lock_free: {
3107 APSInt SizeVal;
3108 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3109 return false;
3110
3111 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3112 // of two less than the maximum inline atomic width, we know it is
3113 // lock-free. If the size isn't a power of two, or greater than the
3114 // maximum alignment where we promote atomics, we know it is not lock-free
3115 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3116 // the answer can only be determined at runtime; for example, 16-byte
3117 // atomics have lock-free implementations on some, but not all,
3118 // x86-64 processors.
3119
3120 // Check power-of-two.
3121 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3122 if (!Size.isPowerOfTwo())
3123#if 0
3124 // FIXME: Suppress this folding until the ABI for the promotion width
3125 // settles.
3126 return Success(0, E);
3127#else
3128 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3129#endif
3130
3131#if 0
3132 // Check against promotion width.
3133 // FIXME: Suppress this folding until the ABI for the promotion width
3134 // settles.
3135 unsigned PromoteWidthBits =
3136 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3137 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3138 return Success(0, E);
3139#endif
3140
3141 // Check against inlining width.
3142 unsigned InlineWidthBits =
3143 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3144 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3145 return Success(1, E);
3146
3147 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
3148 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003149 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003150}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003151
Richard Smith625b8072011-10-31 01:37:14 +00003152static bool HasSameBase(const LValue &A, const LValue &B) {
3153 if (!A.getLValueBase())
3154 return !B.getLValueBase();
3155 if (!B.getLValueBase())
3156 return false;
3157
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003158 if (A.getLValueBase().getOpaqueValue() !=
3159 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003160 const Decl *ADecl = GetLValueBaseDecl(A);
3161 if (!ADecl)
3162 return false;
3163 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003164 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003165 return false;
3166 }
3167
3168 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003169 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003170}
3171
Chris Lattnerb542afe2008-07-11 19:10:17 +00003172bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003173 if (E->isAssignmentOp())
3174 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
3175
John McCall2de56d12010-08-25 11:45:40 +00003176 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003177 VisitIgnoredValue(E->getLHS());
3178 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003179 }
3180
3181 if (E->isLogicalOp()) {
3182 // These need to be handled specially because the operands aren't
3183 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003184 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Richard Smithc49bd112011-10-28 17:51:58 +00003186 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003187 // We were able to evaluate the LHS, see if we can get away with not
3188 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003189 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003190 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003191
Richard Smithc49bd112011-10-28 17:51:58 +00003192 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003193 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003194 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003195 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003196 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003197 }
3198 } else {
Richard Smithc49bd112011-10-28 17:51:58 +00003199 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003200 // We can't evaluate the LHS; however, sometimes the result
3201 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00003202 if (rhsResult == (E->getOpcode() == BO_LOr) ||
3203 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003204 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003205 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003206 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003207
3208 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003209 }
3210 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003211 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003212
Eli Friedmana6afa762008-11-13 06:09:17 +00003213 return false;
3214 }
3215
Anders Carlsson286f85e2008-11-16 07:17:21 +00003216 QualType LHSTy = E->getLHS()->getType();
3217 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003218
3219 if (LHSTy->isAnyComplexType()) {
3220 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003221 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003222
3223 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3224 return false;
3225
3226 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3227 return false;
3228
3229 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003230 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003231 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003232 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003233 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3234
John McCall2de56d12010-08-25 11:45:40 +00003235 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003236 return Success((CR_r == APFloat::cmpEqual &&
3237 CR_i == APFloat::cmpEqual), E);
3238 else {
John McCall2de56d12010-08-25 11:45:40 +00003239 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003240 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003241 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003242 CR_r == APFloat::cmpLessThan ||
3243 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003244 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003245 CR_i == APFloat::cmpLessThan ||
3246 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003247 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003248 } else {
John McCall2de56d12010-08-25 11:45:40 +00003249 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003250 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3251 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3252 else {
John McCall2de56d12010-08-25 11:45:40 +00003253 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003254 "Invalid compex comparison.");
3255 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3256 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3257 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003258 }
3259 }
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Anders Carlsson286f85e2008-11-16 07:17:21 +00003261 if (LHSTy->isRealFloatingType() &&
3262 RHSTy->isRealFloatingType()) {
3263 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Anders Carlsson286f85e2008-11-16 07:17:21 +00003265 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3266 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003267
Anders Carlsson286f85e2008-11-16 07:17:21 +00003268 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3269 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003270
Anders Carlsson286f85e2008-11-16 07:17:21 +00003271 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003272
Anders Carlsson286f85e2008-11-16 07:17:21 +00003273 switch (E->getOpcode()) {
3274 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003275 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003276 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003277 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003278 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003279 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003280 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003281 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003282 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003283 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003284 E);
John McCall2de56d12010-08-25 11:45:40 +00003285 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003286 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003287 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003288 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003289 || CR == APFloat::cmpLessThan
3290 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003291 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003292 }
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003294 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003295 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003296 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003297 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3298 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003299
John McCallefdb83e2010-05-07 21:00:08 +00003300 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003301 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3302 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003303
Richard Smith625b8072011-10-31 01:37:14 +00003304 // Reject differing bases from the normal codepath; we special-case
3305 // comparisons to null.
3306 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003307 // Inequalities and subtractions between unrelated pointers have
3308 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003309 if (!E->isEqualityOp())
3310 return false;
Eli Friedmanffbda402011-10-31 22:28:05 +00003311 // A constant address may compare equal to the address of a symbol.
3312 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003313 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003314 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3315 (!RHSValue.Base && !RHSValue.Offset.isZero()))
3316 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00003317 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003318 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003319 // distinct. However, we do know that the address of a literal will be
3320 // non-null.
3321 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3322 LHSValue.Base && RHSValue.Base)
Eli Friedman5bc86102009-06-14 02:17:33 +00003323 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00003324 // We can't tell whether weak symbols will end up pointing to the same
3325 // object.
3326 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Eli Friedman5bc86102009-06-14 02:17:33 +00003327 return false;
Richard Smith9e36b532011-10-31 05:11:32 +00003328 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003329 // (Note that clang defaults to -fmerge-all-constants, which can
3330 // lead to inconsistent results for comparisons involving the address
3331 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003332 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003333 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003334
Richard Smithcc5d4f62011-11-07 09:22:26 +00003335 // FIXME: Implement the C++11 restrictions:
3336 // - Pointer subtractions must be on elements of the same array.
3337 // - Pointer comparisons must be between members with the same access.
3338
John McCall2de56d12010-08-25 11:45:40 +00003339 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003340 QualType Type = E->getLHS()->getType();
3341 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003342
Richard Smith180f4792011-11-10 06:34:14 +00003343 CharUnits ElementSize;
3344 if (!HandleSizeof(Info, ElementType, ElementSize))
3345 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003346
Richard Smith180f4792011-11-10 06:34:14 +00003347 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003348 RHSValue.getLValueOffset();
3349 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003350 }
Richard Smith625b8072011-10-31 01:37:14 +00003351
3352 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3353 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3354 switch (E->getOpcode()) {
3355 default: llvm_unreachable("missing comparison operator");
3356 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3357 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3358 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3359 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3360 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3361 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003362 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003363 }
3364 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003365 if (!LHSTy->isIntegralOrEnumerationType() ||
3366 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003367 // We can't continue from here for non-integral types.
3368 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003369 }
3370
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003371 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003372 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003373 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner54176fd2008-07-12 00:14:42 +00003374 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003375
Richard Smithc49bd112011-10-28 17:51:58 +00003376 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003377 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003378 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003379
3380 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003381 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003382 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3383 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003384 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003385 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003386 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003387 LHSVal.getLValueOffset() -= AdditionalOffset;
3388 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003389 return true;
3390 }
3391
3392 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003393 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003394 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003395 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3396 LHSVal.getInt().getZExtValue());
3397 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003398 return true;
3399 }
3400
3401 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003402 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00003403 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00003404
Richard Smithc49bd112011-10-28 17:51:58 +00003405 APSInt &LHS = LHSVal.getInt();
3406 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003407
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003408 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003409 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003410 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smithc49bd112011-10-28 17:51:58 +00003411 case BO_Mul: return Success(LHS * RHS, E);
3412 case BO_Add: return Success(LHS + RHS, E);
3413 case BO_Sub: return Success(LHS - RHS, E);
3414 case BO_And: return Success(LHS & RHS, E);
3415 case BO_Xor: return Success(LHS ^ RHS, E);
3416 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003417 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003418 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003419 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00003420 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003421 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003422 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003423 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smithc49bd112011-10-28 17:51:58 +00003424 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003425 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00003426 // During constant-folding, a negative shift is an opposite shift.
3427 if (RHS.isSigned() && RHS.isNegative()) {
3428 RHS = -RHS;
3429 goto shift_right;
3430 }
3431
3432 shift_left:
3433 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00003434 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3435 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003436 }
John McCall2de56d12010-08-25 11:45:40 +00003437 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00003438 // During constant-folding, a negative shift is an opposite shift.
3439 if (RHS.isSigned() && RHS.isNegative()) {
3440 RHS = -RHS;
3441 goto shift_left;
3442 }
3443
3444 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00003445 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00003446 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3447 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Richard Smithc49bd112011-10-28 17:51:58 +00003450 case BO_LT: return Success(LHS < RHS, E);
3451 case BO_GT: return Success(LHS > RHS, E);
3452 case BO_LE: return Success(LHS <= RHS, E);
3453 case BO_GE: return Success(LHS >= RHS, E);
3454 case BO_EQ: return Success(LHS == RHS, E);
3455 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00003456 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003457}
3458
Ken Dyck8b752f12010-01-27 17:10:57 +00003459CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00003460 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3461 // the result is the size of the referenced type."
3462 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3463 // result shall be the alignment of the referenced type."
3464 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3465 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00003466
3467 // __alignof is defined to return the preferred alignment.
3468 return Info.Ctx.toCharUnitsFromBits(
3469 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00003470}
3471
Ken Dyck8b752f12010-01-27 17:10:57 +00003472CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00003473 E = E->IgnoreParens();
3474
3475 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00003476 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00003477 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003478 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3479 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00003480
Chris Lattneraf707ab2009-01-24 21:53:27 +00003481 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003482 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3483 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00003484
Chris Lattnere9feb472009-01-24 21:09:06 +00003485 return GetAlignOfType(E->getType());
3486}
3487
3488
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003489/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3490/// a result as the expression's type.
3491bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3492 const UnaryExprOrTypeTraitExpr *E) {
3493 switch(E->getKind()) {
3494 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00003495 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003496 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003497 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003498 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003499 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003500
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003501 case UETT_VecStep: {
3502 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00003503
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003504 if (Ty->isVectorType()) {
3505 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00003506
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003507 // The vec_step built-in functions that take a 3-component
3508 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3509 if (n == 3)
3510 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00003511
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003512 return Success(n, E);
3513 } else
3514 return Success(1, E);
3515 }
3516
3517 case UETT_SizeOf: {
3518 QualType SrcTy = E->getTypeOfArgument();
3519 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3520 // the result is the size of the referenced type."
3521 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3522 // result shall be the alignment of the referenced type."
3523 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3524 SrcTy = Ref->getPointeeType();
3525
Richard Smith180f4792011-11-10 06:34:14 +00003526 CharUnits Sizeof;
3527 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003528 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003529 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003530 }
3531 }
3532
3533 llvm_unreachable("unknown expr/type trait");
3534 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00003535}
3536
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003537bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003538 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003539 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003540 if (n == 0)
3541 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003542 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003543 for (unsigned i = 0; i != n; ++i) {
3544 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3545 switch (ON.getKind()) {
3546 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003547 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003548 APSInt IdxResult;
3549 if (!EvaluateInteger(Idx, IdxResult, Info))
3550 return false;
3551 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3552 if (!AT)
3553 return false;
3554 CurrentType = AT->getElementType();
3555 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3556 Result += IdxResult.getSExtValue() * ElementSize;
3557 break;
3558 }
3559
3560 case OffsetOfExpr::OffsetOfNode::Field: {
3561 FieldDecl *MemberDecl = ON.getField();
3562 const RecordType *RT = CurrentType->getAs<RecordType>();
3563 if (!RT)
3564 return false;
3565 RecordDecl *RD = RT->getDecl();
3566 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003567 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003568 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003569 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003570 CurrentType = MemberDecl->getType().getNonReferenceType();
3571 break;
3572 }
3573
3574 case OffsetOfExpr::OffsetOfNode::Identifier:
3575 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003576 return false;
3577
3578 case OffsetOfExpr::OffsetOfNode::Base: {
3579 CXXBaseSpecifier *BaseSpec = ON.getBase();
3580 if (BaseSpec->isVirtual())
3581 return false;
3582
3583 // Find the layout of the class whose base we are looking into.
3584 const RecordType *RT = CurrentType->getAs<RecordType>();
3585 if (!RT)
3586 return false;
3587 RecordDecl *RD = RT->getDecl();
3588 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3589
3590 // Find the base class itself.
3591 CurrentType = BaseSpec->getType();
3592 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3593 if (!BaseRT)
3594 return false;
3595
3596 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003597 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003598 break;
3599 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003600 }
3601 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003602 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003603}
3604
Chris Lattnerb542afe2008-07-11 19:10:17 +00003605bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003606 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00003607 // LNot's operand isn't necessarily an integer, so we handle it specially.
3608 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003609 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003610 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003611 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003612 }
3613
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003614 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003615 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00003616 return false;
3617
Richard Smithc49bd112011-10-28 17:51:58 +00003618 // Get the operand value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003619 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00003620 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00003621 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003622
Chris Lattner75a48812008-07-11 22:15:16 +00003623 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003624 default:
Chris Lattner75a48812008-07-11 22:15:16 +00003625 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3626 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00003627 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00003628 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00003629 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3630 // If so, we could clear the diagnostic ID.
Richard Smithc49bd112011-10-28 17:51:58 +00003631 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003632 case UO_Plus:
Richard Smithc49bd112011-10-28 17:51:58 +00003633 // The result is just the value.
3634 return Success(Val, E);
John McCall2de56d12010-08-25 11:45:40 +00003635 case UO_Minus:
Richard Smithc49bd112011-10-28 17:51:58 +00003636 if (!Val.isInt()) return false;
3637 return Success(-Val.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00003638 case UO_Not:
Richard Smithc49bd112011-10-28 17:51:58 +00003639 if (!Val.isInt()) return false;
3640 return Success(~Val.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003641 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003642}
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Chris Lattner732b2232008-07-12 01:15:53 +00003644/// HandleCast - This is used to evaluate implicit or explicit casts where the
3645/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003646bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3647 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003648 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003649 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003650
Eli Friedman46a52322011-03-25 00:43:55 +00003651 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003652 case CK_BaseToDerived:
3653 case CK_DerivedToBase:
3654 case CK_UncheckedDerivedToBase:
3655 case CK_Dynamic:
3656 case CK_ToUnion:
3657 case CK_ArrayToPointerDecay:
3658 case CK_FunctionToPointerDecay:
3659 case CK_NullToPointer:
3660 case CK_NullToMemberPointer:
3661 case CK_BaseToDerivedMemberPointer:
3662 case CK_DerivedToBaseMemberPointer:
3663 case CK_ConstructorConversion:
3664 case CK_IntegralToPointer:
3665 case CK_ToVoid:
3666 case CK_VectorSplat:
3667 case CK_IntegralToFloating:
3668 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003669 case CK_CPointerToObjCPointerCast:
3670 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003671 case CK_AnyPointerToBlockPointerCast:
3672 case CK_ObjCObjectLValueCast:
3673 case CK_FloatingRealToComplex:
3674 case CK_FloatingComplexToReal:
3675 case CK_FloatingComplexCast:
3676 case CK_FloatingComplexToIntegralComplex:
3677 case CK_IntegralRealToComplex:
3678 case CK_IntegralComplexCast:
3679 case CK_IntegralComplexToFloatingComplex:
3680 llvm_unreachable("invalid cast kind for integral value");
3681
Eli Friedmane50c2972011-03-25 19:07:11 +00003682 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003683 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003684 case CK_LValueBitCast:
3685 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00003686 case CK_ARCProduceObject:
3687 case CK_ARCConsumeObject:
3688 case CK_ARCReclaimReturnedObject:
3689 case CK_ARCExtendBlockObject:
Eli Friedman46a52322011-03-25 00:43:55 +00003690 return false;
3691
3692 case CK_LValueToRValue:
3693 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003694 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003695
3696 case CK_MemberPointerToBoolean:
3697 case CK_PointerToBoolean:
3698 case CK_IntegralToBoolean:
3699 case CK_FloatingToBoolean:
3700 case CK_FloatingComplexToBoolean:
3701 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003702 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00003703 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003704 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003705 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003706 }
3707
Eli Friedman46a52322011-03-25 00:43:55 +00003708 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00003709 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003710 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003711
Eli Friedmanbe265702009-02-20 01:15:07 +00003712 if (!Result.isInt()) {
3713 // Only allow casts of lvalues if they are lossless.
3714 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3715 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003716
Daniel Dunbardd211642009-02-19 22:24:01 +00003717 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003718 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00003719 }
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Eli Friedman46a52322011-03-25 00:43:55 +00003721 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00003722 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00003723 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003724 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003725
Daniel Dunbardd211642009-02-19 22:24:01 +00003726 if (LV.getLValueBase()) {
3727 // Only allow based lvalue casts if they are lossless.
3728 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3729 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003730
Richard Smithb755a9d2011-11-16 07:18:12 +00003731 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003732 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00003733 return true;
3734 }
3735
Ken Dycka7305832010-01-15 12:37:54 +00003736 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3737 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00003738 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00003739 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003740
Eli Friedman46a52322011-03-25 00:43:55 +00003741 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00003742 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00003743 if (!EvaluateComplex(SubExpr, C, Info))
3744 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00003745 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00003746 }
Eli Friedman2217c872009-02-22 11:46:18 +00003747
Eli Friedman46a52322011-03-25 00:43:55 +00003748 case CK_FloatingToIntegral: {
3749 APFloat F(0.0);
3750 if (!EvaluateFloat(SubExpr, F, Info))
3751 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00003752
Eli Friedman46a52322011-03-25 00:43:55 +00003753 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3754 }
3755 }
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Eli Friedman46a52322011-03-25 00:43:55 +00003757 llvm_unreachable("unknown cast resulting in integral value");
3758 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003759}
Anders Carlsson2bad1682008-07-08 14:30:00 +00003760
Eli Friedman722c7172009-02-28 03:59:05 +00003761bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3762 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003763 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003764 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3765 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3766 return Success(LV.getComplexIntReal(), E);
3767 }
3768
3769 return Visit(E->getSubExpr());
3770}
3771
Eli Friedman664a1042009-02-27 04:45:43 +00003772bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00003773 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00003774 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00003775 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3776 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3777 return Success(LV.getComplexIntImag(), E);
3778 }
3779
Richard Smith8327fad2011-10-24 18:44:57 +00003780 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00003781 return Success(0, E);
3782}
3783
Douglas Gregoree8aff02011-01-04 17:33:58 +00003784bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3785 return Success(E->getPackLength(), E);
3786}
3787
Sebastian Redl295995c2010-09-10 20:55:47 +00003788bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3789 return Success(E->getValue(), E);
3790}
3791
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003792//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003793// Float Evaluation
3794//===----------------------------------------------------------------------===//
3795
3796namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003797class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003798 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003799 APFloat &Result;
3800public:
3801 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003802 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003803
Richard Smith47a1eed2011-10-29 20:57:55 +00003804 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003805 Result = V.getFloat();
3806 return true;
3807 }
3808 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003809 return false;
3810 }
3811
Richard Smithf10d9172011-10-11 21:43:33 +00003812 bool ValueInitialization(const Expr *E) {
3813 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3814 return true;
3815 }
3816
Chris Lattner019f4e82008-10-06 05:28:25 +00003817 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003818
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003819 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003820 bool VisitBinaryOperator(const BinaryOperator *E);
3821 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003822 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00003823
John McCallabd3a852010-05-07 22:08:54 +00003824 bool VisitUnaryReal(const UnaryOperator *E);
3825 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003826
John McCallabd3a852010-05-07 22:08:54 +00003827 // FIXME: Missing: array subscript of vector, member of vector,
3828 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003829};
3830} // end anonymous namespace
3831
3832static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003833 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003834 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003835}
3836
Jay Foad4ba2a172011-01-12 09:06:06 +00003837static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00003838 QualType ResultTy,
3839 const Expr *Arg,
3840 bool SNaN,
3841 llvm::APFloat &Result) {
3842 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3843 if (!S) return false;
3844
3845 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3846
3847 llvm::APInt fill;
3848
3849 // Treat empty strings as if they were zero.
3850 if (S->getString().empty())
3851 fill = llvm::APInt(32, 0);
3852 else if (S->getString().getAsInteger(0, fill))
3853 return false;
3854
3855 if (SNaN)
3856 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3857 else
3858 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3859 return true;
3860}
3861
Chris Lattner019f4e82008-10-06 05:28:25 +00003862bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003863 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003864 default:
3865 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3866
Chris Lattner019f4e82008-10-06 05:28:25 +00003867 case Builtin::BI__builtin_huge_val:
3868 case Builtin::BI__builtin_huge_valf:
3869 case Builtin::BI__builtin_huge_vall:
3870 case Builtin::BI__builtin_inf:
3871 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003872 case Builtin::BI__builtin_infl: {
3873 const llvm::fltSemantics &Sem =
3874 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00003875 Result = llvm::APFloat::getInf(Sem);
3876 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00003877 }
Mike Stump1eb44332009-09-09 15:08:12 +00003878
John McCalldb7b72a2010-02-28 13:00:19 +00003879 case Builtin::BI__builtin_nans:
3880 case Builtin::BI__builtin_nansf:
3881 case Builtin::BI__builtin_nansl:
3882 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3883 true, Result);
3884
Chris Lattner9e621712008-10-06 06:31:58 +00003885 case Builtin::BI__builtin_nan:
3886 case Builtin::BI__builtin_nanf:
3887 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00003888 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00003889 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00003890 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3891 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003892
3893 case Builtin::BI__builtin_fabs:
3894 case Builtin::BI__builtin_fabsf:
3895 case Builtin::BI__builtin_fabsl:
3896 if (!EvaluateFloat(E->getArg(0), Result, Info))
3897 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003898
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003899 if (Result.isNegative())
3900 Result.changeSign();
3901 return true;
3902
Mike Stump1eb44332009-09-09 15:08:12 +00003903 case Builtin::BI__builtin_copysign:
3904 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003905 case Builtin::BI__builtin_copysignl: {
3906 APFloat RHS(0.);
3907 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3908 !EvaluateFloat(E->getArg(1), RHS, Info))
3909 return false;
3910 Result.copySign(RHS);
3911 return true;
3912 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003913 }
3914}
3915
John McCallabd3a852010-05-07 22:08:54 +00003916bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003917 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3918 ComplexValue CV;
3919 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3920 return false;
3921 Result = CV.FloatReal;
3922 return true;
3923 }
3924
3925 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00003926}
3927
3928bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00003929 if (E->getSubExpr()->getType()->isAnyComplexType()) {
3930 ComplexValue CV;
3931 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3932 return false;
3933 Result = CV.FloatImag;
3934 return true;
3935 }
3936
Richard Smith8327fad2011-10-24 18:44:57 +00003937 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00003938 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3939 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00003940 return true;
3941}
3942
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003943bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003944 switch (E->getOpcode()) {
3945 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003946 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003947 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00003948 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00003949 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3950 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003951 Result.changeSign();
3952 return true;
3953 }
3954}
Chris Lattner019f4e82008-10-06 05:28:25 +00003955
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003956bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003957 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
3958 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00003959
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00003960 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003961 if (!EvaluateFloat(E->getLHS(), Result, Info))
3962 return false;
3963 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3964 return false;
3965
3966 switch (E->getOpcode()) {
3967 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00003968 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003969 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3970 return true;
John McCall2de56d12010-08-25 11:45:40 +00003971 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003972 Result.add(RHS, APFloat::rmNearestTiesToEven);
3973 return true;
John McCall2de56d12010-08-25 11:45:40 +00003974 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003975 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3976 return true;
John McCall2de56d12010-08-25 11:45:40 +00003977 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003978 Result.divide(RHS, APFloat::rmNearestTiesToEven);
3979 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00003980 }
3981}
3982
3983bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3984 Result = E->getValue();
3985 return true;
3986}
3987
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
3989 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Eli Friedman2a523ee2011-03-25 00:54:52 +00003991 switch (E->getCastKind()) {
3992 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003993 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00003994
3995 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003996 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003997 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003998 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003999 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004000 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00004001 return true;
4002 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004003
4004 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004005 if (!Visit(SubExpr))
4006 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00004007 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
4008 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00004009 return true;
4010 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004011
Eli Friedman2a523ee2011-03-25 00:54:52 +00004012 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004013 ComplexValue V;
4014 if (!EvaluateComplex(SubExpr, V, Info))
4015 return false;
4016 Result = V.getComplexFloatReal();
4017 return true;
4018 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004019 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004020
4021 return false;
4022}
4023
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004024//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004025// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004026//===----------------------------------------------------------------------===//
4027
4028namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004029class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004030 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004031 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004033public:
John McCallf4cf1a12010-05-07 17:22:02 +00004034 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004035 : ExprEvaluatorBaseTy(info), Result(Result) {}
4036
Richard Smith47a1eed2011-10-29 20:57:55 +00004037 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004038 Result.setFrom(V);
4039 return true;
4040 }
4041 bool Error(const Expr *E) {
4042 return false;
4043 }
Mike Stump1eb44332009-09-09 15:08:12 +00004044
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004045 //===--------------------------------------------------------------------===//
4046 // Visitor Methods
4047 //===--------------------------------------------------------------------===//
4048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004049 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004051 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004052
John McCallf4cf1a12010-05-07 17:22:02 +00004053 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004054 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004055 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004056};
4057} // end anonymous namespace
4058
John McCallf4cf1a12010-05-07 17:22:02 +00004059static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4060 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004061 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004062 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004063}
4064
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004065bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4066 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004067
4068 if (SubExpr->getType()->isRealFloatingType()) {
4069 Result.makeComplexFloat();
4070 APFloat &Imag = Result.FloatImag;
4071 if (!EvaluateFloat(SubExpr, Imag, Info))
4072 return false;
4073
4074 Result.FloatReal = APFloat(Imag.getSemantics());
4075 return true;
4076 } else {
4077 assert(SubExpr->getType()->isIntegerType() &&
4078 "Unexpected imaginary literal.");
4079
4080 Result.makeComplexInt();
4081 APSInt &Imag = Result.IntImag;
4082 if (!EvaluateInteger(SubExpr, Imag, Info))
4083 return false;
4084
4085 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4086 return true;
4087 }
4088}
4089
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004090bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004091
John McCall8786da72010-12-14 17:51:41 +00004092 switch (E->getCastKind()) {
4093 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004094 case CK_BaseToDerived:
4095 case CK_DerivedToBase:
4096 case CK_UncheckedDerivedToBase:
4097 case CK_Dynamic:
4098 case CK_ToUnion:
4099 case CK_ArrayToPointerDecay:
4100 case CK_FunctionToPointerDecay:
4101 case CK_NullToPointer:
4102 case CK_NullToMemberPointer:
4103 case CK_BaseToDerivedMemberPointer:
4104 case CK_DerivedToBaseMemberPointer:
4105 case CK_MemberPointerToBoolean:
4106 case CK_ConstructorConversion:
4107 case CK_IntegralToPointer:
4108 case CK_PointerToIntegral:
4109 case CK_PointerToBoolean:
4110 case CK_ToVoid:
4111 case CK_VectorSplat:
4112 case CK_IntegralCast:
4113 case CK_IntegralToBoolean:
4114 case CK_IntegralToFloating:
4115 case CK_FloatingToIntegral:
4116 case CK_FloatingToBoolean:
4117 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004118 case CK_CPointerToObjCPointerCast:
4119 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004120 case CK_AnyPointerToBlockPointerCast:
4121 case CK_ObjCObjectLValueCast:
4122 case CK_FloatingComplexToReal:
4123 case CK_FloatingComplexToBoolean:
4124 case CK_IntegralComplexToReal:
4125 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004126 case CK_ARCProduceObject:
4127 case CK_ARCConsumeObject:
4128 case CK_ARCReclaimReturnedObject:
4129 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004130 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004131
John McCall8786da72010-12-14 17:51:41 +00004132 case CK_LValueToRValue:
4133 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004134 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004135
4136 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004137 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004138 case CK_UserDefinedConversion:
4139 return false;
4140
4141 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004142 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004143 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004144 return false;
4145
John McCall8786da72010-12-14 17:51:41 +00004146 Result.makeComplexFloat();
4147 Result.FloatImag = APFloat(Real.getSemantics());
4148 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004149 }
4150
John McCall8786da72010-12-14 17:51:41 +00004151 case CK_FloatingComplexCast: {
4152 if (!Visit(E->getSubExpr()))
4153 return false;
4154
4155 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4156 QualType From
4157 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4158
4159 Result.FloatReal
4160 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
4161 Result.FloatImag
4162 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
4163 return true;
4164 }
4165
4166 case CK_FloatingComplexToIntegralComplex: {
4167 if (!Visit(E->getSubExpr()))
4168 return false;
4169
4170 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4171 QualType From
4172 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4173 Result.makeComplexInt();
4174 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
4175 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
4176 return true;
4177 }
4178
4179 case CK_IntegralRealToComplex: {
4180 APSInt &Real = Result.IntReal;
4181 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4182 return false;
4183
4184 Result.makeComplexInt();
4185 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4186 return true;
4187 }
4188
4189 case CK_IntegralComplexCast: {
4190 if (!Visit(E->getSubExpr()))
4191 return false;
4192
4193 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4194 QualType From
4195 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4196
4197 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4198 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4199 return true;
4200 }
4201
4202 case CK_IntegralComplexToFloatingComplex: {
4203 if (!Visit(E->getSubExpr()))
4204 return false;
4205
4206 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4207 QualType From
4208 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4209 Result.makeComplexFloat();
4210 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
4211 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
4212 return true;
4213 }
4214 }
4215
4216 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004217 return false;
4218}
4219
John McCallf4cf1a12010-05-07 17:22:02 +00004220bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004221 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004222 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4223
John McCallf4cf1a12010-05-07 17:22:02 +00004224 if (!Visit(E->getLHS()))
4225 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004226
John McCallf4cf1a12010-05-07 17:22:02 +00004227 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004228 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004229 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004230
Daniel Dunbar3f279872009-01-29 01:32:56 +00004231 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4232 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004233 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004234 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00004235 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004236 if (Result.isComplexFloat()) {
4237 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4238 APFloat::rmNearestTiesToEven);
4239 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4240 APFloat::rmNearestTiesToEven);
4241 } else {
4242 Result.getComplexIntReal() += RHS.getComplexIntReal();
4243 Result.getComplexIntImag() += RHS.getComplexIntImag();
4244 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004245 break;
John McCall2de56d12010-08-25 11:45:40 +00004246 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004247 if (Result.isComplexFloat()) {
4248 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4249 APFloat::rmNearestTiesToEven);
4250 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4251 APFloat::rmNearestTiesToEven);
4252 } else {
4253 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4254 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4255 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004256 break;
John McCall2de56d12010-08-25 11:45:40 +00004257 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004258 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004259 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004260 APFloat &LHS_r = LHS.getComplexFloatReal();
4261 APFloat &LHS_i = LHS.getComplexFloatImag();
4262 APFloat &RHS_r = RHS.getComplexFloatReal();
4263 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Daniel Dunbar3f279872009-01-29 01:32:56 +00004265 APFloat Tmp = LHS_r;
4266 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4267 Result.getComplexFloatReal() = Tmp;
4268 Tmp = LHS_i;
4269 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4270 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4271
4272 Tmp = LHS_r;
4273 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4274 Result.getComplexFloatImag() = Tmp;
4275 Tmp = LHS_i;
4276 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4277 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4278 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004279 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004280 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004281 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4282 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004283 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004284 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4285 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4286 }
4287 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004288 case BO_Div:
4289 if (Result.isComplexFloat()) {
4290 ComplexValue LHS = Result;
4291 APFloat &LHS_r = LHS.getComplexFloatReal();
4292 APFloat &LHS_i = LHS.getComplexFloatImag();
4293 APFloat &RHS_r = RHS.getComplexFloatReal();
4294 APFloat &RHS_i = RHS.getComplexFloatImag();
4295 APFloat &Res_r = Result.getComplexFloatReal();
4296 APFloat &Res_i = Result.getComplexFloatImag();
4297
4298 APFloat Den = RHS_r;
4299 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4300 APFloat Tmp = RHS_i;
4301 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4302 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4303
4304 Res_r = LHS_r;
4305 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4306 Tmp = LHS_i;
4307 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4308 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4309 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4310
4311 Res_i = LHS_i;
4312 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4313 Tmp = LHS_r;
4314 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4315 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4316 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4317 } else {
4318 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
4319 // FIXME: what about diagnostics?
4320 return false;
4321 }
4322 ComplexValue LHS = Result;
4323 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4324 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4325 Result.getComplexIntReal() =
4326 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4327 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4328 Result.getComplexIntImag() =
4329 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4330 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4331 }
4332 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004333 }
4334
John McCallf4cf1a12010-05-07 17:22:02 +00004335 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004336}
4337
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004338bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4339 // Get the operand value into 'Result'.
4340 if (!Visit(E->getSubExpr()))
4341 return false;
4342
4343 switch (E->getOpcode()) {
4344 default:
4345 // FIXME: what about diagnostics?
4346 return false;
4347 case UO_Extension:
4348 return true;
4349 case UO_Plus:
4350 // The result is always just the subexpr.
4351 return true;
4352 case UO_Minus:
4353 if (Result.isComplexFloat()) {
4354 Result.getComplexFloatReal().changeSign();
4355 Result.getComplexFloatImag().changeSign();
4356 }
4357 else {
4358 Result.getComplexIntReal() = -Result.getComplexIntReal();
4359 Result.getComplexIntImag() = -Result.getComplexIntImag();
4360 }
4361 return true;
4362 case UO_Not:
4363 if (Result.isComplexFloat())
4364 Result.getComplexFloatImag().changeSign();
4365 else
4366 Result.getComplexIntImag() = -Result.getComplexIntImag();
4367 return true;
4368 }
4369}
4370
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004371//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004372// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004373//===----------------------------------------------------------------------===//
4374
Richard Smith47a1eed2011-10-29 20:57:55 +00004375static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004376 // In C, function designators are not lvalues, but we evaluate them as if they
4377 // are.
4378 if (E->isGLValue() || E->getType()->isFunctionType()) {
4379 LValue LV;
4380 if (!EvaluateLValue(E, LV, Info))
4381 return false;
4382 LV.moveInto(Result);
4383 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004384 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004385 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004386 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004387 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004388 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004389 } else if (E->getType()->hasPointerRepresentation()) {
4390 LValue LV;
4391 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004392 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004393 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004394 } else if (E->getType()->isRealFloatingType()) {
4395 llvm::APFloat F(0.0);
4396 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004397 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004398 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004399 } else if (E->getType()->isAnyComplexType()) {
4400 ComplexValue C;
4401 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004402 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004403 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00004404 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004405 MemberPtr P;
4406 if (!EvaluateMemberPointer(E, P, Info))
4407 return false;
4408 P.moveInto(Result);
4409 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00004410 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004411 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004412 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004413 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00004414 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004415 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00004416 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004417 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004418 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004419 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4420 return false;
4421 Result = Info.CurrentCall->Temporaries[E];
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004422 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00004423 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004424
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00004425 return true;
4426}
4427
Richard Smith69c2c502011-11-04 05:33:44 +00004428/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4429/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4430/// since later initializers for an object can indirectly refer to subobjects
4431/// which were initialized earlier.
4432static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00004433 const LValue &This, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00004434 if (E->isRValue() && E->getType()->isLiteralType()) {
4435 // Evaluate arrays and record types in-place, so that later initializers can
4436 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00004437 if (E->getType()->isArrayType())
4438 return EvaluateArray(E, This, Result, Info);
4439 else if (E->getType()->isRecordType())
4440 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00004441 }
4442
4443 // For any other type, in-place evaluation is unimportant.
4444 CCValue CoreConstResult;
4445 return Evaluate(CoreConstResult, Info, E) &&
4446 CheckConstantExpression(CoreConstResult, Result);
4447}
4448
Richard Smithc49bd112011-10-28 17:51:58 +00004449
Richard Smith51f47082011-10-29 00:50:52 +00004450/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00004451/// any crazy technique (that has nothing to do with language standards) that
4452/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00004453/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4454/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00004455bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith1445bba2011-11-10 03:30:42 +00004456 // FIXME: Evaluating initializers for large arrays can cause performance
4457 // problems, and we don't use such values yet. Once we have a more efficient
4458 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004459 // The same problem affects large records.
4460 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4461 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00004462 return false;
4463
John McCall56ca35d2011-02-17 10:25:35 +00004464 EvalInfo Info(Ctx, Result);
Richard Smithc49bd112011-10-28 17:51:58 +00004465
Richard Smith180f4792011-11-10 06:34:14 +00004466 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smith47a1eed2011-10-29 20:57:55 +00004467 CCValue Value;
4468 if (!::Evaluate(Value, Info, this))
Richard Smithc49bd112011-10-28 17:51:58 +00004469 return false;
4470
4471 if (isGLValue()) {
4472 LValue LV;
Richard Smith47a1eed2011-10-29 20:57:55 +00004473 LV.setFrom(Value);
4474 if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
4475 return false;
Richard Smithc49bd112011-10-28 17:51:58 +00004476 }
4477
Richard Smith47a1eed2011-10-29 20:57:55 +00004478 // Check this core constant expression is a constant expression, and if so,
Richard Smith69c2c502011-11-04 05:33:44 +00004479 // convert it to one.
4480 return CheckConstantExpression(Value, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00004481}
4482
Jay Foad4ba2a172011-01-12 09:06:06 +00004483bool Expr::EvaluateAsBooleanCondition(bool &Result,
4484 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004485 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00004486 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00004487 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00004488 Result);
John McCallcd7a4452010-01-05 23:42:56 +00004489}
4490
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004491bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004492 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00004493 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithc49bd112011-10-28 17:51:58 +00004494 !ExprResult.Val.isInt()) {
4495 return false;
4496 }
4497 Result = ExprResult.Val.getInt();
4498 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004499}
4500
Jay Foad4ba2a172011-01-12 09:06:06 +00004501bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00004502 EvalInfo Info(Ctx, Result);
4503
John McCallefdb83e2010-05-07 21:00:08 +00004504 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00004505 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
4506 CheckLValueConstantExpression(LV, Result.Val);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00004507}
4508
Richard Smith51f47082011-10-29 00:50:52 +00004509/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4510/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004511bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004512 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00004513 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00004514}
Anders Carlsson51fe9962008-11-22 21:04:56 +00004515
Jay Foad4ba2a172011-01-12 09:06:06 +00004516bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00004517 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004518}
4519
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004520APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004521 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00004522 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004523 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004524 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004525 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004526
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004527 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004528}
John McCalld905f5a2010-05-07 05:32:02 +00004529
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004530 bool Expr::EvalResult::isGlobalLValue() const {
4531 assert(Val.isLValue());
4532 return IsGlobalLValue(Val.getLValueBase());
4533 }
4534
4535
John McCalld905f5a2010-05-07 05:32:02 +00004536/// isIntegerConstantExpr - this recursive routine will test if an expression is
4537/// an integer constant expression.
4538
4539/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4540/// comma, etc
4541///
4542/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4543/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4544/// cast+dereference.
4545
4546// CheckICE - This function does the fundamental ICE checking: the returned
4547// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4548// Note that to reduce code duplication, this helper does no evaluation
4549// itself; the caller checks whether the expression is evaluatable, and
4550// in the rare cases where CheckICE actually cares about the evaluated
4551// value, it calls into Evalute.
4552//
4553// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004554// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004555// 1: This expression is not an ICE, but if it isn't evaluated, it's
4556// a legal subexpression for an ICE. This return value is used to handle
4557// the comma operator in C99 mode.
4558// 2: This expression is not an ICE, and is not a legal subexpression for one.
4559
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004560namespace {
4561
John McCalld905f5a2010-05-07 05:32:02 +00004562struct ICEDiag {
4563 unsigned Val;
4564 SourceLocation Loc;
4565
4566 public:
4567 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4568 ICEDiag() : Val(0) {}
4569};
4570
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004571}
4572
4573static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004574
4575static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4576 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004577 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004578 !EVResult.Val.isInt()) {
4579 return ICEDiag(2, E->getLocStart());
4580 }
4581 return NoDiag();
4582}
4583
4584static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4585 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004586 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004587 return ICEDiag(2, E->getLocStart());
4588 }
4589
4590 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004591#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004592#define STMT(Node, Base) case Expr::Node##Class:
4593#define EXPR(Node, Base)
4594#include "clang/AST/StmtNodes.inc"
4595 case Expr::PredefinedExprClass:
4596 case Expr::FloatingLiteralClass:
4597 case Expr::ImaginaryLiteralClass:
4598 case Expr::StringLiteralClass:
4599 case Expr::ArraySubscriptExprClass:
4600 case Expr::MemberExprClass:
4601 case Expr::CompoundAssignOperatorClass:
4602 case Expr::CompoundLiteralExprClass:
4603 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004604 case Expr::DesignatedInitExprClass:
4605 case Expr::ImplicitValueInitExprClass:
4606 case Expr::ParenListExprClass:
4607 case Expr::VAArgExprClass:
4608 case Expr::AddrLabelExprClass:
4609 case Expr::StmtExprClass:
4610 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004611 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004612 case Expr::CXXDynamicCastExprClass:
4613 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004614 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004615 case Expr::CXXNullPtrLiteralExprClass:
4616 case Expr::CXXThisExprClass:
4617 case Expr::CXXThrowExprClass:
4618 case Expr::CXXNewExprClass:
4619 case Expr::CXXDeleteExprClass:
4620 case Expr::CXXPseudoDestructorExprClass:
4621 case Expr::UnresolvedLookupExprClass:
4622 case Expr::DependentScopeDeclRefExprClass:
4623 case Expr::CXXConstructExprClass:
4624 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00004625 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00004626 case Expr::CXXTemporaryObjectExprClass:
4627 case Expr::CXXUnresolvedConstructExprClass:
4628 case Expr::CXXDependentScopeMemberExprClass:
4629 case Expr::UnresolvedMemberExprClass:
4630 case Expr::ObjCStringLiteralClass:
4631 case Expr::ObjCEncodeExprClass:
4632 case Expr::ObjCMessageExprClass:
4633 case Expr::ObjCSelectorExprClass:
4634 case Expr::ObjCProtocolExprClass:
4635 case Expr::ObjCIvarRefExprClass:
4636 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004637 case Expr::ObjCIsaExprClass:
4638 case Expr::ShuffleVectorExprClass:
4639 case Expr::BlockExprClass:
4640 case Expr::BlockDeclRefExprClass:
4641 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00004642 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00004643 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00004644 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004645 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004646 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00004647 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00004648 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00004649 case Expr::AtomicExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004650 return ICEDiag(2, E->getLocStart());
4651
Sebastian Redlcea8d962011-09-24 17:48:14 +00004652 case Expr::InitListExprClass:
4653 if (Ctx.getLangOptions().CPlusPlus0x) {
4654 const InitListExpr *ILE = cast<InitListExpr>(E);
4655 if (ILE->getNumInits() == 0)
4656 return NoDiag();
4657 if (ILE->getNumInits() == 1)
4658 return CheckICE(ILE->getInit(0), Ctx);
4659 // Fall through for more than 1 expression.
4660 }
4661 return ICEDiag(2, E->getLocStart());
4662
Douglas Gregoree8aff02011-01-04 17:33:58 +00004663 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004664 case Expr::GNUNullExprClass:
4665 // GCC considers the GNU __null value to be an integral constant expression.
4666 return NoDiag();
4667
John McCall91a57552011-07-15 05:09:51 +00004668 case Expr::SubstNonTypeTemplateParmExprClass:
4669 return
4670 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4671
John McCalld905f5a2010-05-07 05:32:02 +00004672 case Expr::ParenExprClass:
4673 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00004674 case Expr::GenericSelectionExprClass:
4675 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004676 case Expr::IntegerLiteralClass:
4677 case Expr::CharacterLiteralClass:
4678 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00004679 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004680 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00004681 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00004682 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00004683 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00004684 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004685 return NoDiag();
4686 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00004687 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00004688 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4689 // constant expressions, but they can never be ICEs because an ICE cannot
4690 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00004691 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00004692 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00004693 return CheckEvalInICE(E, Ctx);
4694 return ICEDiag(2, E->getLocStart());
4695 }
4696 case Expr::DeclRefExprClass:
4697 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4698 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00004699 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00004700 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4701
4702 // Parameter variables are never constants. Without this check,
4703 // getAnyInitializer() can find a default argument, which leads
4704 // to chaos.
4705 if (isa<ParmVarDecl>(D))
4706 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4707
4708 // C++ 7.1.5.1p2
4709 // A variable of non-volatile const-qualified integral or enumeration
4710 // type initialized by an ICE can be used in ICEs.
4711 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00004712 if (!Dcl->getType()->isIntegralOrEnumerationType())
4713 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4714
John McCalld905f5a2010-05-07 05:32:02 +00004715 // Look for a declaration of this variable that has an initializer.
4716 const VarDecl *ID = 0;
4717 const Expr *Init = Dcl->getAnyInitializer(ID);
4718 if (Init) {
4719 if (ID->isInitKnownICE()) {
4720 // We have already checked whether this subexpression is an
4721 // integral constant expression.
4722 if (ID->isInitICE())
4723 return NoDiag();
4724 else
4725 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4726 }
4727
4728 // It's an ICE whether or not the definition we found is
4729 // out-of-line. See DR 721 and the discussion in Clang PR
4730 // 6206 for details.
4731
4732 if (Dcl->isCheckingICE()) {
4733 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4734 }
4735
4736 Dcl->setCheckingICE();
4737 ICEDiag Result = CheckICE(Init, Ctx);
4738 // Cache the result of the ICE test.
4739 Dcl->setInitKnownICE(Result.Val == 0);
4740 return Result;
4741 }
4742 }
4743 }
4744 return ICEDiag(2, E->getLocStart());
4745 case Expr::UnaryOperatorClass: {
4746 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4747 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004748 case UO_PostInc:
4749 case UO_PostDec:
4750 case UO_PreInc:
4751 case UO_PreDec:
4752 case UO_AddrOf:
4753 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00004754 // C99 6.6/3 allows increment and decrement within unevaluated
4755 // subexpressions of constant expressions, but they can never be ICEs
4756 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004757 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00004758 case UO_Extension:
4759 case UO_LNot:
4760 case UO_Plus:
4761 case UO_Minus:
4762 case UO_Not:
4763 case UO_Real:
4764 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00004765 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004766 }
4767
4768 // OffsetOf falls through here.
4769 }
4770 case Expr::OffsetOfExprClass: {
4771 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00004772 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00004773 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00004774 // compliance: we should warn earlier for offsetof expressions with
4775 // array subscripts that aren't ICEs, and if the array subscripts
4776 // are ICEs, the value of the offsetof must be an integer constant.
4777 return CheckEvalInICE(E, Ctx);
4778 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004779 case Expr::UnaryExprOrTypeTraitExprClass: {
4780 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4781 if ((Exp->getKind() == UETT_SizeOf) &&
4782 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00004783 return ICEDiag(2, E->getLocStart());
4784 return NoDiag();
4785 }
4786 case Expr::BinaryOperatorClass: {
4787 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4788 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00004789 case BO_PtrMemD:
4790 case BO_PtrMemI:
4791 case BO_Assign:
4792 case BO_MulAssign:
4793 case BO_DivAssign:
4794 case BO_RemAssign:
4795 case BO_AddAssign:
4796 case BO_SubAssign:
4797 case BO_ShlAssign:
4798 case BO_ShrAssign:
4799 case BO_AndAssign:
4800 case BO_XorAssign:
4801 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00004802 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4803 // constant expressions, but they can never be ICEs because an ICE cannot
4804 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00004805 return ICEDiag(2, E->getLocStart());
4806
John McCall2de56d12010-08-25 11:45:40 +00004807 case BO_Mul:
4808 case BO_Div:
4809 case BO_Rem:
4810 case BO_Add:
4811 case BO_Sub:
4812 case BO_Shl:
4813 case BO_Shr:
4814 case BO_LT:
4815 case BO_GT:
4816 case BO_LE:
4817 case BO_GE:
4818 case BO_EQ:
4819 case BO_NE:
4820 case BO_And:
4821 case BO_Xor:
4822 case BO_Or:
4823 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00004824 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4825 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00004826 if (Exp->getOpcode() == BO_Div ||
4827 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00004828 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00004829 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00004830 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004831 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004832 if (REval == 0)
4833 return ICEDiag(1, E->getLocStart());
4834 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004835 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004836 if (LEval.isMinSignedValue())
4837 return ICEDiag(1, E->getLocStart());
4838 }
4839 }
4840 }
John McCall2de56d12010-08-25 11:45:40 +00004841 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00004842 if (Ctx.getLangOptions().C99) {
4843 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4844 // if it isn't evaluated.
4845 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4846 return ICEDiag(1, E->getLocStart());
4847 } else {
4848 // In both C89 and C++, commas in ICEs are illegal.
4849 return ICEDiag(2, E->getLocStart());
4850 }
4851 }
4852 if (LHSResult.Val >= RHSResult.Val)
4853 return LHSResult;
4854 return RHSResult;
4855 }
John McCall2de56d12010-08-25 11:45:40 +00004856 case BO_LAnd:
4857 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00004858 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00004859
4860 // C++0x [expr.const]p2:
4861 // [...] subexpressions of logical AND (5.14), logical OR
4862 // (5.15), and condi- tional (5.16) operations that are not
4863 // evaluated are not considered.
4864 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4865 if (Exp->getOpcode() == BO_LAnd &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004866 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004867 return LHSResult;
4868
4869 if (Exp->getOpcode() == BO_LOr &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004870 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregor63fe6812011-05-24 16:02:01 +00004871 return LHSResult;
4872 }
4873
John McCalld905f5a2010-05-07 05:32:02 +00004874 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4875 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4876 // Rare case where the RHS has a comma "side-effect"; we need
4877 // to actually check the condition to see whether the side
4878 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00004879 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004880 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00004881 return RHSResult;
4882 return NoDiag();
4883 }
4884
4885 if (LHSResult.Val >= RHSResult.Val)
4886 return LHSResult;
4887 return RHSResult;
4888 }
4889 }
4890 }
4891 case Expr::ImplicitCastExprClass:
4892 case Expr::CStyleCastExprClass:
4893 case Expr::CXXFunctionalCastExprClass:
4894 case Expr::CXXStaticCastExprClass:
4895 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00004896 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004897 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00004898 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00004899 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00004900 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4901 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00004902 switch (cast<CastExpr>(E)->getCastKind()) {
4903 case CK_LValueToRValue:
4904 case CK_NoOp:
4905 case CK_IntegralToBoolean:
4906 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00004907 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00004908 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00004909 return ICEDiag(2, E->getLocStart());
4910 }
John McCalld905f5a2010-05-07 05:32:02 +00004911 }
John McCall56ca35d2011-02-17 10:25:35 +00004912 case Expr::BinaryConditionalOperatorClass: {
4913 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4914 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4915 if (CommonResult.Val == 2) return CommonResult;
4916 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4917 if (FalseResult.Val == 2) return FalseResult;
4918 if (CommonResult.Val == 1) return CommonResult;
4919 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004920 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00004921 return FalseResult;
4922 }
John McCalld905f5a2010-05-07 05:32:02 +00004923 case Expr::ConditionalOperatorClass: {
4924 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4925 // If the condition (ignoring parens) is a __builtin_constant_p call,
4926 // then only the true side is actually considered in an integer constant
4927 // expression, and it is fully evaluated. This is an important GNU
4928 // extension. See GCC PR38377 for discussion.
4929 if (const CallExpr *CallCE
4930 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00004931 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00004932 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004933 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004934 !EVResult.Val.isInt()) {
4935 return ICEDiag(2, E->getLocStart());
4936 }
4937 return NoDiag();
4938 }
4939 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004940 if (CondResult.Val == 2)
4941 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00004942
4943 // C++0x [expr.const]p2:
4944 // subexpressions of [...] conditional (5.16) operations that
4945 // are not evaluated are not considered
4946 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004947 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregor63fe6812011-05-24 16:02:01 +00004948 : false;
4949 ICEDiag TrueResult = NoDiag();
4950 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4951 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4952 ICEDiag FalseResult = NoDiag();
4953 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
4954 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4955
John McCalld905f5a2010-05-07 05:32:02 +00004956 if (TrueResult.Val == 2)
4957 return TrueResult;
4958 if (FalseResult.Val == 2)
4959 return FalseResult;
4960 if (CondResult.Val == 1)
4961 return CondResult;
4962 if (TrueResult.Val == 0 && FalseResult.Val == 0)
4963 return NoDiag();
4964 // Rare case where the diagnostics depend on which side is evaluated
4965 // Note that if we get here, CondResult is 0, and at least one of
4966 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004967 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00004968 return FalseResult;
4969 }
4970 return TrueResult;
4971 }
4972 case Expr::CXXDefaultArgExprClass:
4973 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
4974 case Expr::ChooseExprClass: {
4975 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
4976 }
4977 }
4978
4979 // Silence a GCC warning
4980 return ICEDiag(2, E->getLocStart());
4981}
4982
4983bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
4984 SourceLocation *Loc, bool isEvaluated) const {
4985 ICEDiag d = CheckICE(this, Ctx);
4986 if (d.Val != 0) {
4987 if (Loc) *Loc = d.Loc;
4988 return false;
4989 }
Richard Smithc49bd112011-10-28 17:51:58 +00004990 if (!EvaluateAsInt(Result, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00004991 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00004992 return true;
4993}