blob: 1ef3605f20642d1f144dc36d5704b0f1a490b96a [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000046 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000049
Richard Smithce40ad62011-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 Smithd62306a2011-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 Smith80815602011-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 Smithd62306a2011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith80815602011-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 Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith96e0c102011-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 Smith80815602011-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 Smithce40ad62011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith80815602011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smith027bf112011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith96e0c102011-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 Smith80815602011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith96e0c102011-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 Smithd62306a2011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-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 Smithf3e9e432011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith80815602011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith96e0c102011-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 Smith0b0a0b62011-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 Smith027bf112011-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 Smith0b0a0b62011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smithfec09922011-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 Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000195 public:
Richard Smithfec09922011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith0b0a0b62011-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 Smithfec09922011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smithce40ad62011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith96e0c102011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith80815602011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smithfec09922011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith80815602011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smith027bf112011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith0b0a0b62011-10-29 20:57:55 +0000213
Richard Smithfec09922011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smithfec09922011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith0b0a0b62011-10-29 20:57:55 +0000217 }
Richard Smith96e0c102011-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 Smith0b0a0b62011-10-29 20:57:55 +0000225 };
226
Richard Smith254a73d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000233
Richard Smithd62306a2011-11-10 06:34:14 +0000234 /// This - The binding for the this pointer in this call, if any.
235 const LValue *This;
236
Richard Smith254a73d2011-10-28 22:34:42 +0000237 /// ParmBindings - Parameter bindings for this function call, indexed by
238 /// parameters' function scope indices.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000239 const CCValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000240
Richard Smith4e4c78ff2011-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 Smithd62306a2011-11-10 06:34:14 +0000246 CallStackFrame(EvalInfo &Info, const LValue *This,
247 const CCValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000248 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000249 };
250
Richard Smith4e4c78ff2011-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 Smith4e4c78ff2011-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 Smithd62306a2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000280
281 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith9a568822011-11-21 19:36:32 +0000282 : Ctx(C), EvalStatus(S), CurrentCall(0), CallStackDepth(0),
Richard Smithd62306a2011-11-10 06:34:14 +0000283 BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000284
Richard Smith4e4c78ff2011-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 Smithd62306a2011-11-10 06:34:14 +0000291 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
292 EvaluatingDecl = VD;
293 EvaluatingDeclValue = &Value;
294 }
295
Richard Smith9a568822011-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 Smithf57d8cb2011-12-09 22:58:01 +0000301
302 /// Diagnose that the evaluation does not produce a C++11 core constant
303 /// expression.
304 void CCEDiag(const Expr *E, SourceLocation Loc, diag::kind Diag) {
305 // Don't override a previous diagnostic.
306 if (EvalStatus.Diag == 0) {
307 EvalStatus.DiagLoc = Loc;
308 EvalStatus.Diag = Diag;
309 EvalStatus.DiagExpr = E;
310 }
311 }
312
313 /// Diagnose that the evaluation cannot be folded.
314 void Diag(const Expr *E, SourceLocation Loc, diag::kind Diag) {
315 // If we have a prior diagnostic, it will be noting that the expression
316 // isn't a constant expression. This diagnostic is more important.
317 // FIXME: We might want to show both diagnostics to the user.
318 EvalStatus.DiagLoc = Loc;
319 EvalStatus.Diag = Diag;
320 EvalStatus.DiagExpr = E;
321 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000322 };
323
Richard Smithd62306a2011-11-10 06:34:14 +0000324 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
325 const CCValue *Arguments)
326 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000327 Info.CurrentCall = this;
328 ++Info.CallStackDepth;
329 }
330
331 CallStackFrame::~CallStackFrame() {
332 assert(Info.CurrentCall == this && "calls retired out of order");
333 --Info.CallStackDepth;
334 Info.CurrentCall = Caller;
335 }
336
John McCall93d91dc2010-05-07 17:22:02 +0000337 struct ComplexValue {
338 private:
339 bool IsInt;
340
341 public:
342 APSInt IntReal, IntImag;
343 APFloat FloatReal, FloatImag;
344
345 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
346
347 void makeComplexFloat() { IsInt = false; }
348 bool isComplexFloat() const { return !IsInt; }
349 APFloat &getComplexFloatReal() { return FloatReal; }
350 APFloat &getComplexFloatImag() { return FloatImag; }
351
352 void makeComplexInt() { IsInt = true; }
353 bool isComplexInt() const { return IsInt; }
354 APSInt &getComplexIntReal() { return IntReal; }
355 APSInt &getComplexIntImag() { return IntImag; }
356
Richard Smith0b0a0b62011-10-29 20:57:55 +0000357 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000358 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000359 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000360 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000361 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000362 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000363 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000364 assert(v.isComplexFloat() || v.isComplexInt());
365 if (v.isComplexFloat()) {
366 makeComplexFloat();
367 FloatReal = v.getComplexFloatReal();
368 FloatImag = v.getComplexFloatImag();
369 } else {
370 makeComplexInt();
371 IntReal = v.getComplexIntReal();
372 IntImag = v.getComplexIntImag();
373 }
374 }
John McCall93d91dc2010-05-07 17:22:02 +0000375 };
John McCall45d55e42010-05-07 21:00:08 +0000376
377 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000378 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000379 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000380 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000381 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000382
Richard Smithce40ad62011-11-12 22:28:03 +0000383 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000384 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000385 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000386 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000387 SubobjectDesignator &getLValueDesignator() { return Designator; }
388 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000389
Richard Smith0b0a0b62011-10-29 20:57:55 +0000390 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000391 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000392 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000393 void setFrom(const CCValue &V) {
394 assert(V.isLValue());
395 Base = V.getLValueBase();
396 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000397 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000398 Designator = V.getLValueDesignator();
399 }
400
Richard Smithce40ad62011-11-12 22:28:03 +0000401 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
402 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000403 Offset = CharUnits::Zero();
404 Frame = F;
405 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000406 }
John McCall45d55e42010-05-07 21:00:08 +0000407 };
Richard Smith027bf112011-11-17 22:56:20 +0000408
409 struct MemberPtr {
410 MemberPtr() {}
411 explicit MemberPtr(const ValueDecl *Decl) :
412 DeclAndIsDerivedMember(Decl, false), Path() {}
413
414 /// The member or (direct or indirect) field referred to by this member
415 /// pointer, or 0 if this is a null member pointer.
416 const ValueDecl *getDecl() const {
417 return DeclAndIsDerivedMember.getPointer();
418 }
419 /// Is this actually a member of some type derived from the relevant class?
420 bool isDerivedMember() const {
421 return DeclAndIsDerivedMember.getInt();
422 }
423 /// Get the class which the declaration actually lives in.
424 const CXXRecordDecl *getContainingRecord() const {
425 return cast<CXXRecordDecl>(
426 DeclAndIsDerivedMember.getPointer()->getDeclContext());
427 }
428
429 void moveInto(CCValue &V) const {
430 V = CCValue(getDecl(), isDerivedMember(), Path);
431 }
432 void setFrom(const CCValue &V) {
433 assert(V.isMemberPointer());
434 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
435 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
436 Path.clear();
437 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
438 Path.insert(Path.end(), P.begin(), P.end());
439 }
440
441 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
442 /// whether the member is a member of some class derived from the class type
443 /// of the member pointer.
444 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
445 /// Path - The path of base/derived classes from the member declaration's
446 /// class (exclusive) to the class type of the member pointer (inclusive).
447 SmallVector<const CXXRecordDecl*, 4> Path;
448
449 /// Perform a cast towards the class of the Decl (either up or down the
450 /// hierarchy).
451 bool castBack(const CXXRecordDecl *Class) {
452 assert(!Path.empty());
453 const CXXRecordDecl *Expected;
454 if (Path.size() >= 2)
455 Expected = Path[Path.size() - 2];
456 else
457 Expected = getContainingRecord();
458 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
459 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
460 // if B does not contain the original member and is not a base or
461 // derived class of the class containing the original member, the result
462 // of the cast is undefined.
463 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
464 // (D::*). We consider that to be a language defect.
465 return false;
466 }
467 Path.pop_back();
468 return true;
469 }
470 /// Perform a base-to-derived member pointer cast.
471 bool castToDerived(const CXXRecordDecl *Derived) {
472 if (!getDecl())
473 return true;
474 if (!isDerivedMember()) {
475 Path.push_back(Derived);
476 return true;
477 }
478 if (!castBack(Derived))
479 return false;
480 if (Path.empty())
481 DeclAndIsDerivedMember.setInt(false);
482 return true;
483 }
484 /// Perform a derived-to-base member pointer cast.
485 bool castToBase(const CXXRecordDecl *Base) {
486 if (!getDecl())
487 return true;
488 if (Path.empty())
489 DeclAndIsDerivedMember.setInt(true);
490 if (isDerivedMember()) {
491 Path.push_back(Base);
492 return true;
493 }
494 return castBack(Base);
495 }
496 };
John McCall93d91dc2010-05-07 17:22:02 +0000497}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000498
Richard Smith0b0a0b62011-10-29 20:57:55 +0000499static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000500static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +0000501 const LValue &This, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000502static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
503static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000504static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
505 EvalInfo &Info);
506static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000507static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000508static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000509 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000510static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000511static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000512
513//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000514// Misc utilities
515//===----------------------------------------------------------------------===//
516
Richard Smithd62306a2011-11-10 06:34:14 +0000517/// Should this call expression be treated as a string literal?
518static bool IsStringLiteralCall(const CallExpr *E) {
519 unsigned Builtin = E->isBuiltinCall();
520 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
521 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
522}
523
Richard Smithce40ad62011-11-12 22:28:03 +0000524static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000525 // C++11 [expr.const]p3 An address constant expression is a prvalue core
526 // constant expression of pointer type that evaluates to...
527
528 // ... a null pointer value, or a prvalue core constant expression of type
529 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000530 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000531
Richard Smithce40ad62011-11-12 22:28:03 +0000532 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
533 // ... the address of an object with static storage duration,
534 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
535 return VD->hasGlobalStorage();
536 // ... the address of a function,
537 return isa<FunctionDecl>(D);
538 }
539
540 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000541 switch (E->getStmtClass()) {
542 default:
543 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000544 case Expr::CompoundLiteralExprClass:
545 return cast<CompoundLiteralExpr>(E)->isFileScope();
546 // A string literal has static storage duration.
547 case Expr::StringLiteralClass:
548 case Expr::PredefinedExprClass:
549 case Expr::ObjCStringLiteralClass:
550 case Expr::ObjCEncodeExprClass:
551 return true;
552 case Expr::CallExprClass:
553 return IsStringLiteralCall(cast<CallExpr>(E));
554 // For GCC compatibility, &&label has static storage duration.
555 case Expr::AddrLabelExprClass:
556 return true;
557 // A Block literal expression may be used as the initialization value for
558 // Block variables at global or local static scope.
559 case Expr::BlockExprClass:
560 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
561 }
John McCall95007602010-05-10 23:27:23 +0000562}
563
Richard Smith80815602011-11-07 05:07:52 +0000564/// Check that this reference or pointer core constant expression is a valid
565/// value for a constant expression. Type T should be either LValue or CCValue.
566template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000567static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
568 const T &LVal, APValue &Value) {
569 if (!IsGlobalLValue(LVal.getLValueBase())) {
570 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith80815602011-11-07 05:07:52 +0000571 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000572 }
Richard Smith80815602011-11-07 05:07:52 +0000573
574 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
575 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000576 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000577 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith80815602011-11-07 05:07:52 +0000578 // FIXME: This is not a constant expression.
579 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
580 APValue::NoLValuePath());
581 return true;
582 }
583
584 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000585 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000586 return true;
587}
588
Richard Smith0b0a0b62011-10-29 20:57:55 +0000589/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000590/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000591/// If not, report an appropriate diagnostic.
592static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
593 const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000594 if (!CCValue.isLValue()) {
595 Value = CCValue;
596 return true;
597 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000598 return CheckLValueConstantExpression(Info, E, CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000599}
600
Richard Smith83c68212011-10-31 05:11:32 +0000601const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000602 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000603}
604
605static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000606 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000607}
608
Richard Smithcecf1842011-11-01 21:06:14 +0000609static bool IsWeakLValue(const LValue &Value) {
610 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000611 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000612}
613
Richard Smith027bf112011-11-17 22:56:20 +0000614static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000615 // A null base expression indicates a null pointer. These are always
616 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000617 if (!Value.getLValueBase()) {
618 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000619 return true;
620 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000621
John McCall95007602010-05-10 23:27:23 +0000622 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000623 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000624 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000625
Richard Smith027bf112011-11-17 22:56:20 +0000626 // We have a non-null base. These are generally known to be true, but if it's
627 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000628 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000629 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000630 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000631}
632
Richard Smith0b0a0b62011-10-29 20:57:55 +0000633static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000634 switch (Val.getKind()) {
635 case APValue::Uninitialized:
636 return false;
637 case APValue::Int:
638 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000639 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000640 case APValue::Float:
641 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000642 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000643 case APValue::ComplexInt:
644 Result = Val.getComplexIntReal().getBoolValue() ||
645 Val.getComplexIntImag().getBoolValue();
646 return true;
647 case APValue::ComplexFloat:
648 Result = !Val.getComplexFloatReal().isZero() ||
649 !Val.getComplexFloatImag().isZero();
650 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000651 case APValue::LValue:
652 return EvalPointerValueAsBool(Val, Result);
653 case APValue::MemberPointer:
654 Result = Val.getMemberPointerDecl();
655 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000656 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000657 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000658 case APValue::Struct:
659 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000660 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000661 }
662
Richard Smith11562c52011-10-28 17:51:58 +0000663 llvm_unreachable("unknown APValue kind");
664}
665
666static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
667 EvalInfo &Info) {
668 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000669 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000670 if (!Evaluate(Val, Info, E))
671 return false;
672 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000673}
674
Mike Stump11289f42009-09-09 15:08:12 +0000675static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000676 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000677 unsigned DestWidth = Ctx.getIntWidth(DestType);
678 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000679 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000680
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000681 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000682 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000683 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000684 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
685 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000686}
687
Mike Stump11289f42009-09-09 15:08:12 +0000688static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000689 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000690 bool ignored;
691 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000692 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000693 APFloat::rmNearestTiesToEven, &ignored);
694 return Result;
695}
696
Mike Stump11289f42009-09-09 15:08:12 +0000697static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000698 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000699 unsigned DestWidth = Ctx.getIntWidth(DestType);
700 APSInt Result = Value;
701 // Figure out if this is a truncate, extend or noop cast.
702 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000703 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000704 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000705 return Result;
706}
707
Mike Stump11289f42009-09-09 15:08:12 +0000708static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000709 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000710
711 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
712 Result.convertFromAPInt(Value, Value.isSigned(),
713 APFloat::rmNearestTiesToEven);
714 return Result;
715}
716
Richard Smith027bf112011-11-17 22:56:20 +0000717static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
718 const CXXRecordDecl *&MostDerivedType,
719 unsigned &MostDerivedPathLength,
720 bool &MostDerivedIsArrayElement) {
721 const SubobjectDesignator &D = LVal.Designator;
722 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000723 return false;
724
Richard Smith027bf112011-11-17 22:56:20 +0000725 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000726
727 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000728 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000729 MostDerivedPathLength = 0;
730 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000731
732 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
733 bool IsArray = T && T->isArrayType();
734 if (IsArray)
735 T = T->getBaseElementTypeUnsafe();
736 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
737 T = FD->getType().getTypePtr();
738 else
739 T = 0;
740
741 if (T) {
742 MostDerivedType = T->getAsCXXRecordDecl();
743 MostDerivedPathLength = I + 1;
744 MostDerivedIsArrayElement = IsArray;
745 }
746 }
747
Richard Smithd62306a2011-11-10 06:34:14 +0000748 // (B*)&d + 1 has no most-derived object.
749 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
750 return false;
751
Richard Smith027bf112011-11-17 22:56:20 +0000752 return MostDerivedType != 0;
753}
754
755static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
756 const RecordDecl *TruncatedType,
757 unsigned TruncatedElements,
758 bool IsArrayElement) {
759 SubobjectDesignator &D = Result.Designator;
760 const RecordDecl *RD = TruncatedType;
761 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000762 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
763 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000764 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000765 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000766 else
Richard Smithd62306a2011-11-10 06:34:14 +0000767 Result.Offset -= Layout.getBaseClassOffset(Base);
768 RD = Base;
769 }
Richard Smith027bf112011-11-17 22:56:20 +0000770 D.Entries.resize(TruncatedElements);
771 D.ArrayElement = IsArrayElement;
772}
773
774/// If the given LValue refers to a base subobject of some object, find the most
775/// derived object and the corresponding complete record type. This is necessary
776/// in order to find the offset of a virtual base class.
777static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
778 const CXXRecordDecl *&MostDerivedType) {
779 unsigned MostDerivedPathLength;
780 bool MostDerivedIsArrayElement;
781 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
782 MostDerivedPathLength, MostDerivedIsArrayElement))
783 return false;
784
785 // Remove the trailing base class path entries and their offsets.
786 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
787 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000788 return true;
789}
790
791static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
792 const CXXRecordDecl *Derived,
793 const CXXRecordDecl *Base,
794 const ASTRecordLayout *RL = 0) {
795 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
796 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
797 Obj.Designator.addDecl(Base, /*Virtual*/ false);
798}
799
800static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
801 const CXXRecordDecl *DerivedDecl,
802 const CXXBaseSpecifier *Base) {
803 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
804
805 if (!Base->isVirtual()) {
806 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
807 return true;
808 }
809
810 // Extract most-derived object and corresponding type.
811 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
812 return false;
813
814 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
815 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
816 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
817 return true;
818}
819
820/// Update LVal to refer to the given field, which must be a member of the type
821/// currently described by LVal.
822static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
823 const FieldDecl *FD,
824 const ASTRecordLayout *RL = 0) {
825 if (!RL)
826 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
827
828 unsigned I = FD->getFieldIndex();
829 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
830 LVal.Designator.addDecl(FD);
831}
832
833/// Get the size of the given type in char units.
834static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
835 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
836 // extension.
837 if (Type->isVoidType() || Type->isFunctionType()) {
838 Size = CharUnits::One();
839 return true;
840 }
841
842 if (!Type->isConstantSizeType()) {
843 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
844 return false;
845 }
846
847 Size = Info.Ctx.getTypeSizeInChars(Type);
848 return true;
849}
850
851/// Update a pointer value to model pointer arithmetic.
852/// \param Info - Information about the ongoing evaluation.
853/// \param LVal - The pointer value to be updated.
854/// \param EltTy - The pointee type represented by LVal.
855/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
856static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
857 QualType EltTy, int64_t Adjustment) {
858 CharUnits SizeOfPointee;
859 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
860 return false;
861
862 // Compute the new offset in the appropriate width.
863 LVal.Offset += Adjustment * SizeOfPointee;
864 LVal.Designator.adjustIndex(Adjustment);
865 return true;
866}
867
Richard Smith27908702011-10-24 17:54:18 +0000868/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000869static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
870 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000871 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000872 // If this is a parameter to an active constexpr function call, perform
873 // argument substitution.
874 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000875 if (!Frame || !Frame->Arguments) {
876 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +0000877 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000878 }
Richard Smithfec09922011-11-01 16:57:24 +0000879 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
880 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000881 }
Richard Smith27908702011-10-24 17:54:18 +0000882
Richard Smithd62306a2011-11-10 06:34:14 +0000883 // If we're currently evaluating the initializer of this declaration, use that
884 // in-flight value.
885 if (Info.EvaluatingDecl == VD) {
886 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
887 return !Result.isUninit();
888 }
889
Richard Smithcecf1842011-11-01 21:06:14 +0000890 // Never evaluate the initializer of a weak variable. We can't be sure that
891 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000892 if (VD->isWeak()) {
893 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +0000894 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000895 }
Richard Smithcecf1842011-11-01 21:06:14 +0000896
Richard Smith27908702011-10-24 17:54:18 +0000897 const Expr *Init = VD->getAnyInitializer();
Richard Smithf57d8cb2011-12-09 22:58:01 +0000898 if (!Init || Init->isValueDependent()) {
899 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000900 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000901 }
Richard Smith27908702011-10-24 17:54:18 +0000902
Richard Smith0b0a0b62011-10-29 20:57:55 +0000903 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000904 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000905 return !Result.isUninit();
906 }
Richard Smith27908702011-10-24 17:54:18 +0000907
Richard Smithf57d8cb2011-12-09 22:58:01 +0000908 if (VD->isEvaluatingValue()) {
909 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000910 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000911 }
Richard Smith27908702011-10-24 17:54:18 +0000912
913 VD->setEvaluatingValue();
914
Richard Smith0b0a0b62011-10-29 20:57:55 +0000915 Expr::EvalStatus EStatus;
916 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithd62306a2011-11-10 06:34:14 +0000917 APValue EvalResult;
918 InitInfo.setEvaluatingDecl(VD, EvalResult);
919 LValue LVal;
Richard Smithce40ad62011-11-12 22:28:03 +0000920 LVal.set(VD);
Richard Smith11562c52011-10-28 17:51:58 +0000921 // FIXME: The caller will need to know whether the value was a constant
922 // expression. If not, we should propagate up a diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +0000923 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000924 // FIXME: If the evaluation failure was not permanent (for instance, if we
925 // hit a variable with no declaration yet, or a constexpr function with no
926 // definition yet), the standard is unclear as to how we should behave.
927 //
928 // Either the initializer should be evaluated when the variable is defined,
929 // or a failed evaluation of the initializer should be reattempted each time
930 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000931 VD->setEvaluatedValue(APValue());
Richard Smithf57d8cb2011-12-09 22:58:01 +0000932 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000933 return false;
934 }
Richard Smith27908702011-10-24 17:54:18 +0000935
Richard Smithed5165f2011-11-04 05:33:44 +0000936 VD->setEvaluatedValue(EvalResult);
937 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000938 return true;
Richard Smith27908702011-10-24 17:54:18 +0000939}
940
Richard Smith11562c52011-10-28 17:51:58 +0000941static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000942 Qualifiers Quals = T.getQualifiers();
943 return Quals.hasConst() && !Quals.hasVolatile();
944}
945
Richard Smithe97cbd72011-11-11 04:05:33 +0000946/// Get the base index of the given base class within an APValue representing
947/// the given derived class.
948static unsigned getBaseIndex(const CXXRecordDecl *Derived,
949 const CXXRecordDecl *Base) {
950 Base = Base->getCanonicalDecl();
951 unsigned Index = 0;
952 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
953 E = Derived->bases_end(); I != E; ++I, ++Index) {
954 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
955 return Index;
956 }
957
958 llvm_unreachable("base class missing from derived class's bases list");
959}
960
Richard Smithf3e9e432011-11-07 09:22:26 +0000961/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000962static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
963 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +0000964 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000965 if (Sub.Invalid || Sub.OnePastTheEnd) {
966 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +0000967 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000968 }
Richard Smith6804be52011-11-11 08:28:03 +0000969 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +0000970 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +0000971
972 assert(!Obj.isLValue() && "extracting subobject of lvalue");
973 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +0000974 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +0000975 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000976 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +0000977 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +0000978 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +0000979 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +0000980 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000981 if (CAT->getSize().ule(Index)) {
982 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +0000983 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000984 }
Richard Smithf3e9e432011-11-07 09:22:26 +0000985 if (O->getArrayInitializedElts() > Index)
986 O = &O->getArrayInitializedElt(Index);
987 else
988 O = &O->getArrayFiller();
989 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +0000990 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
991 // Next subobject is a class, struct or union field.
992 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
993 if (RD->isUnion()) {
994 const FieldDecl *UnionField = O->getUnionField();
995 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +0000996 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
997 Info.Diag(E, E->getExprLoc(),
998 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +0000999 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001000 }
Richard Smithd62306a2011-11-10 06:34:14 +00001001 O = &O->getUnionValue();
1002 } else
1003 O = &O->getStructField(Field->getFieldIndex());
1004 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001005 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001006 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001007 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1008 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1009 O = &O->getStructBase(getBaseIndex(Derived, Base));
1010 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001011 }
Richard Smithd62306a2011-11-10 06:34:14 +00001012
Richard Smithf57d8cb2011-12-09 22:58:01 +00001013 if (O->isUninit()) {
1014 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001015 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001016 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001017 }
1018
Richard Smithf3e9e432011-11-07 09:22:26 +00001019 Obj = CCValue(*O, CCValue::GlobalValue());
1020 return true;
1021}
1022
Richard Smithd62306a2011-11-10 06:34:14 +00001023/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1024/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1025/// for looking up the glvalue referred to by an entity of reference type.
1026///
1027/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001028/// \param Conv - The expression for which we are performing the conversion.
1029/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001030/// \param Type - The type we expect this conversion to produce.
1031/// \param LVal - The glvalue on which we are attempting to perform this action.
1032/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001033static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1034 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001035 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001036 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001037 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001038
Richard Smithf57d8cb2011-12-09 22:58:01 +00001039 if (!LVal.Base) {
1040 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1041 Info.Diag(Conv, Conv->getExprLoc(),
1042 diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001043 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001044 }
Richard Smith11562c52011-10-28 17:51:58 +00001045
Richard Smithce40ad62011-11-12 22:28:03 +00001046 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001047 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1048 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001049 // expressions are constant expressions too. Inside constexpr functions,
1050 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001051 // In C, such things can also be folded, although they are not ICEs.
1052 //
Richard Smith254a73d2011-10-28 22:34:42 +00001053 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1054 // interpretation of C++11 suggests that volatile parameters are OK if
1055 // they're never read (there's no prohibition against constructing volatile
1056 // objects in constant expressions), but lvalue-to-rvalue conversions on
1057 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001058 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001059 if (!VD || VD->isInvalidDecl()) {
1060 Info.Diag(Conv, Conv->getExprLoc(),
1061 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001062 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001063 }
1064
Richard Smithce40ad62011-11-12 22:28:03 +00001065 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001066 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001067 if (!IsConstNonVolatile(VT)) {
1068 Info.Diag(Conv, Conv->getExprLoc(),
1069 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001070 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001071 }
Richard Smitha08acd82011-11-07 03:22:51 +00001072 // FIXME: Allow folding of values of any literal type in all languages.
1073 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001074 !VD->isConstexpr()) {
1075 Info.Diag(Conv, Conv->getExprLoc(),
1076 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001077 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001078 }
Richard Smith96e0c102011-11-04 02:25:55 +00001079 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001080 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001081 return false;
1082
Richard Smith0b0a0b62011-10-29 20:57:55 +00001083 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001084 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001085
1086 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1087 // conversion. This happens when the declaration and the lvalue should be
1088 // considered synonymous, for instance when initializing an array of char
1089 // from a string literal. Continue as if the initializer lvalue was the
1090 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001091 assert(RVal.getLValueOffset().isZero() &&
1092 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001093 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001094 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001095 }
1096
Richard Smith96e0c102011-11-04 02:25:55 +00001097 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1098 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1099 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001100 if (Designator.Invalid || Designator.Entries.size() != 1) {
1101 Info.Diag(Conv, Conv->getExprLoc(),
1102 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001103 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001104 }
Richard Smith96e0c102011-11-04 02:25:55 +00001105
1106 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001107 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001108 if (Index > S->getLength()) {
1109 Info.Diag(Conv, Conv->getExprLoc(),
1110 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001111 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001112 }
Richard Smith96e0c102011-11-04 02:25:55 +00001113 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1114 Type->isUnsignedIntegerType());
1115 if (Index < S->getLength())
1116 Value = S->getCodeUnit(Index);
1117 RVal = CCValue(Value);
1118 return true;
1119 }
1120
Richard Smithf3e9e432011-11-07 09:22:26 +00001121 if (Frame) {
1122 // If this is a temporary expression with a nontrivial initializer, grab the
1123 // value from the relevant stack frame.
1124 RVal = Frame->Temporaries[Base];
1125 } else if (const CompoundLiteralExpr *CLE
1126 = dyn_cast<CompoundLiteralExpr>(Base)) {
1127 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1128 // initializer until now for such expressions. Such an expression can't be
1129 // an ICE in C, so this only matters for fold.
1130 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1131 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1132 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001133 } else {
1134 Info.Diag(Conv, Conv->getExprLoc(),
1135 diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001136 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001137 }
Richard Smith96e0c102011-11-04 02:25:55 +00001138
Richard Smithf57d8cb2011-12-09 22:58:01 +00001139 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1140 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001141}
1142
Richard Smithe97cbd72011-11-11 04:05:33 +00001143/// Build an lvalue for the object argument of a member function call.
1144static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1145 LValue &This) {
1146 if (Object->getType()->isPointerType())
1147 return EvaluatePointer(Object, This, Info);
1148
1149 if (Object->isGLValue())
1150 return EvaluateLValue(Object, This, Info);
1151
Richard Smith027bf112011-11-17 22:56:20 +00001152 if (Object->getType()->isLiteralType())
1153 return EvaluateTemporary(Object, This, Info);
1154
1155 return false;
1156}
1157
1158/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1159/// lvalue referring to the result.
1160///
1161/// \param Info - Information about the ongoing evaluation.
1162/// \param BO - The member pointer access operation.
1163/// \param LV - Filled in with a reference to the resulting object.
1164/// \param IncludeMember - Specifies whether the member itself is included in
1165/// the resulting LValue subobject designator. This is not possible when
1166/// creating a bound member function.
1167/// \return The field or method declaration to which the member pointer refers,
1168/// or 0 if evaluation fails.
1169static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1170 const BinaryOperator *BO,
1171 LValue &LV,
1172 bool IncludeMember = true) {
1173 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1174
1175 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1176 return 0;
1177
1178 MemberPtr MemPtr;
1179 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1180 return 0;
1181
1182 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1183 // member value, the behavior is undefined.
1184 if (!MemPtr.getDecl())
1185 return 0;
1186
1187 if (MemPtr.isDerivedMember()) {
1188 // This is a member of some derived class. Truncate LV appropriately.
1189 const CXXRecordDecl *MostDerivedType;
1190 unsigned MostDerivedPathLength;
1191 bool MostDerivedIsArrayElement;
1192 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1193 MostDerivedIsArrayElement))
1194 return 0;
1195
1196 // The end of the derived-to-base path for the base object must match the
1197 // derived-to-base path for the member pointer.
1198 if (MostDerivedPathLength + MemPtr.Path.size() >
1199 LV.Designator.Entries.size())
1200 return 0;
1201 unsigned PathLengthToMember =
1202 LV.Designator.Entries.size() - MemPtr.Path.size();
1203 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1204 const CXXRecordDecl *LVDecl = getAsBaseClass(
1205 LV.Designator.Entries[PathLengthToMember + I]);
1206 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1207 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1208 return 0;
1209 }
1210
1211 // Truncate the lvalue to the appropriate derived class.
1212 bool ResultIsArray = false;
1213 if (PathLengthToMember == MostDerivedPathLength)
1214 ResultIsArray = MostDerivedIsArrayElement;
1215 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1216 PathLengthToMember, ResultIsArray);
1217 } else if (!MemPtr.Path.empty()) {
1218 // Extend the LValue path with the member pointer's path.
1219 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1220 MemPtr.Path.size() + IncludeMember);
1221
1222 // Walk down to the appropriate base class.
1223 QualType LVType = BO->getLHS()->getType();
1224 if (const PointerType *PT = LVType->getAs<PointerType>())
1225 LVType = PT->getPointeeType();
1226 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1227 assert(RD && "member pointer access on non-class-type expression");
1228 // The first class in the path is that of the lvalue.
1229 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1230 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1231 HandleLValueDirectBase(Info, LV, RD, Base);
1232 RD = Base;
1233 }
1234 // Finally cast to the class containing the member.
1235 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1236 }
1237
1238 // Add the member. Note that we cannot build bound member functions here.
1239 if (IncludeMember) {
1240 // FIXME: Deal with IndirectFieldDecls.
1241 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1242 if (!FD) return 0;
1243 HandleLValueMember(Info, LV, FD);
1244 }
1245
1246 return MemPtr.getDecl();
1247}
1248
1249/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1250/// the provided lvalue, which currently refers to the base object.
1251static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1252 LValue &Result) {
1253 const CXXRecordDecl *MostDerivedType;
1254 unsigned MostDerivedPathLength;
1255 bool MostDerivedIsArrayElement;
1256
1257 // Check this cast doesn't take us outside the object.
1258 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1259 MostDerivedPathLength,
1260 MostDerivedIsArrayElement))
1261 return false;
1262 SubobjectDesignator &D = Result.Designator;
1263 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1264 return false;
1265
1266 // Check the type of the final cast. We don't need to check the path,
1267 // since a cast can only be formed if the path is unique.
1268 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1269 bool ResultIsArray = false;
1270 QualType TargetQT = E->getType();
1271 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1272 TargetQT = PT->getPointeeType();
1273 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1274 const CXXRecordDecl *FinalType;
1275 if (NewEntriesSize == MostDerivedPathLength) {
1276 ResultIsArray = MostDerivedIsArrayElement;
1277 FinalType = MostDerivedType;
1278 } else
1279 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1280 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1281 return false;
1282
1283 // Truncate the lvalue to the appropriate derived class.
1284 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1285 ResultIsArray);
1286 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001287}
1288
Mike Stump876387b2009-10-27 22:09:17 +00001289namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001290enum EvalStmtResult {
1291 /// Evaluation failed.
1292 ESR_Failed,
1293 /// Hit a 'return' statement.
1294 ESR_Returned,
1295 /// Evaluation succeeded.
1296 ESR_Succeeded
1297};
1298}
1299
1300// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001301static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001302 const Stmt *S) {
1303 switch (S->getStmtClass()) {
1304 default:
1305 return ESR_Failed;
1306
1307 case Stmt::NullStmtClass:
1308 case Stmt::DeclStmtClass:
1309 return ESR_Succeeded;
1310
1311 case Stmt::ReturnStmtClass:
1312 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1313 return ESR_Returned;
1314 return ESR_Failed;
1315
1316 case Stmt::CompoundStmtClass: {
1317 const CompoundStmt *CS = cast<CompoundStmt>(S);
1318 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1319 BE = CS->body_end(); BI != BE; ++BI) {
1320 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1321 if (ESR != ESR_Succeeded)
1322 return ESR;
1323 }
1324 return ESR_Succeeded;
1325 }
1326 }
1327}
1328
Richard Smithd62306a2011-11-10 06:34:14 +00001329namespace {
Richard Smith60494462011-11-11 05:48:57 +00001330typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001331}
1332
1333/// EvaluateArgs - Evaluate the arguments to a function call.
1334static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1335 EvalInfo &Info) {
1336 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1337 I != E; ++I)
1338 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1339 return false;
1340 return true;
1341}
1342
Richard Smith254a73d2011-10-28 22:34:42 +00001343/// Evaluate a function call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001344static bool HandleFunctionCall(const Expr *CallExpr, const LValue *This,
1345 ArrayRef<const Expr*> Args, const Stmt *Body,
1346 EvalInfo &Info, CCValue &Result) {
1347 if (Info.atCallLimit()) {
1348 // FIXME: Add a specific proper diagnostic for this.
1349 Info.Diag(CallExpr, CallExpr->getExprLoc(),
1350 diag::note_invalid_subexpr_in_const_expr);
Richard Smith254a73d2011-10-28 22:34:42 +00001351 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001352 }
Richard Smith254a73d2011-10-28 22:34:42 +00001353
Richard Smithd62306a2011-11-10 06:34:14 +00001354 ArgVector ArgValues(Args.size());
1355 if (!EvaluateArgs(Args, ArgValues, Info))
1356 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001357
Richard Smithd62306a2011-11-10 06:34:14 +00001358 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001359 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1360}
1361
Richard Smithd62306a2011-11-10 06:34:14 +00001362/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001363static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001364 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001365 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001366 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001367 APValue &Result) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001368 if (Info.atCallLimit()) {
1369 // FIXME: Add a specific diagnostic for this.
1370 Info.Diag(CallExpr, CallExpr->getExprLoc(),
1371 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001372 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001373 }
Richard Smithd62306a2011-11-10 06:34:14 +00001374
1375 ArgVector ArgValues(Args.size());
1376 if (!EvaluateArgs(Args, ArgValues, Info))
1377 return false;
1378
1379 CallStackFrame Frame(Info, &This, ArgValues.data());
1380
1381 // If it's a delegating constructor, just delegate.
1382 if (Definition->isDelegatingConstructor()) {
1383 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1384 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1385 }
1386
1387 // Reserve space for the struct members.
1388 const CXXRecordDecl *RD = Definition->getParent();
1389 if (!RD->isUnion())
1390 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1391 std::distance(RD->field_begin(), RD->field_end()));
1392
1393 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1394
1395 unsigned BasesSeen = 0;
1396#ifndef NDEBUG
1397 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1398#endif
1399 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1400 E = Definition->init_end(); I != E; ++I) {
1401 if ((*I)->isBaseInitializer()) {
1402 QualType BaseType((*I)->getBaseClass(), 0);
1403#ifndef NDEBUG
1404 // Non-virtual base classes are initialized in the order in the class
1405 // definition. We cannot have a virtual base class for a literal type.
1406 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1407 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1408 "base class initializers not in expected order");
1409 ++BaseIt;
1410#endif
1411 LValue Subobject = This;
1412 HandleLValueDirectBase(Info, Subobject, RD,
1413 BaseType->getAsCXXRecordDecl(), &Layout);
1414 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1415 Subobject, (*I)->getInit()))
1416 return false;
1417 } else if (FieldDecl *FD = (*I)->getMember()) {
1418 LValue Subobject = This;
1419 HandleLValueMember(Info, Subobject, FD, &Layout);
1420 if (RD->isUnion()) {
1421 Result = APValue(FD);
1422 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1423 Subobject, (*I)->getInit()))
1424 return false;
1425 } else if (!EvaluateConstantExpression(
1426 Result.getStructField(FD->getFieldIndex()),
1427 Info, Subobject, (*I)->getInit()))
1428 return false;
1429 } else {
1430 // FIXME: handle indirect field initializers
Richard Smithf57d8cb2011-12-09 22:58:01 +00001431 Info.Diag((*I)->getInit(), (*I)->getInit()->getExprLoc(),
1432 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001433 return false;
1434 }
1435 }
1436
1437 return true;
1438}
1439
Richard Smith254a73d2011-10-28 22:34:42 +00001440namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001441class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001442 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001443 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001444public:
1445
Richard Smith725810a2011-10-16 21:26:27 +00001446 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001447
1448 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001449 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001450 return true;
1451 }
1452
Peter Collingbournee9200682011-05-13 03:29:01 +00001453 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1454 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001455 return Visit(E->getResultExpr());
1456 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001457 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001458 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001459 return true;
1460 return false;
1461 }
John McCall31168b02011-06-15 23:02:42 +00001462 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001463 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001464 return true;
1465 return false;
1466 }
1467 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001468 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001469 return true;
1470 return false;
1471 }
1472
Mike Stump876387b2009-10-27 22:09:17 +00001473 // We don't want to evaluate BlockExprs multiple times, as they generate
1474 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001475 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1476 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1477 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001478 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001479 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1480 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1481 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1482 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1483 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1484 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001485 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001486 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001487 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001488 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001489 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001490 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1491 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1492 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1493 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001494 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001495 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1496 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1497 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1498 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1499 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001500 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001501 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001502 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001503 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001504 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001505
1506 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001507 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001508 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1509 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001510 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001511 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001512 return false;
1513 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001514
Peter Collingbournee9200682011-05-13 03:29:01 +00001515 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001516};
1517
John McCallc07a0c72011-02-17 10:25:35 +00001518class OpaqueValueEvaluation {
1519 EvalInfo &info;
1520 OpaqueValueExpr *opaqueValue;
1521
1522public:
1523 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1524 Expr *value)
1525 : info(info), opaqueValue(opaqueValue) {
1526
1527 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001528 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001529 this->opaqueValue = 0;
1530 return;
1531 }
John McCallc07a0c72011-02-17 10:25:35 +00001532 }
1533
1534 bool hasError() const { return opaqueValue == 0; }
1535
1536 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001537 // FIXME: This will not work for recursive constexpr functions using opaque
1538 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001539 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1540 }
1541};
1542
Mike Stump876387b2009-10-27 22:09:17 +00001543} // end anonymous namespace
1544
Eli Friedman9a156e52008-11-12 09:44:48 +00001545//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001546// Generic Evaluation
1547//===----------------------------------------------------------------------===//
1548namespace {
1549
Richard Smithf57d8cb2011-12-09 22:58:01 +00001550// FIXME: RetTy is always bool. Remove it.
1551template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001552class ExprEvaluatorBase
1553 : public ConstStmtVisitor<Derived, RetTy> {
1554private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001555 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001556 return static_cast<Derived*>(this)->Success(V, E);
1557 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001558 RetTy DerivedValueInitialization(const Expr *E) {
1559 return static_cast<Derived*>(this)->ValueInitialization(E);
1560 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001561
1562protected:
1563 EvalInfo &Info;
1564 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1565 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1566
Richard Smithf57d8cb2011-12-09 22:58:01 +00001567 void CCEDiag(const Expr *E, diag::kind D) {
1568 Info.CCEDiag(E, E->getExprLoc(), D);
1569 }
1570
1571 /// Report an evaluation error. This should only be called when an error is
1572 /// first discovered. When propagating an error, just return false.
1573 bool Error(const Expr *E, diag::kind D) {
1574 Info.Diag(E, E->getExprLoc(), D);
1575 return false;
1576 }
1577 bool Error(const Expr *E) {
1578 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1579 }
1580
1581 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001582
Peter Collingbournee9200682011-05-13 03:29:01 +00001583public:
1584 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1585
1586 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001587 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001588 }
1589 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001590 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001591 }
1592
1593 RetTy VisitParenExpr(const ParenExpr *E)
1594 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1595 RetTy VisitUnaryExtension(const UnaryOperator *E)
1596 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1597 RetTy VisitUnaryPlus(const UnaryOperator *E)
1598 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1599 RetTy VisitChooseExpr(const ChooseExpr *E)
1600 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1601 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1602 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001603 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1604 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001605 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1606 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001607
Richard Smith027bf112011-11-17 22:56:20 +00001608 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1609 switch (E->getOpcode()) {
1610 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001611 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001612
1613 case BO_Comma:
1614 VisitIgnoredValue(E->getLHS());
1615 return StmtVisitorTy::Visit(E->getRHS());
1616
1617 case BO_PtrMemD:
1618 case BO_PtrMemI: {
1619 LValue Obj;
1620 if (!HandleMemberPointerAccess(Info, E, Obj))
1621 return false;
1622 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001623 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001624 return false;
1625 return DerivedSuccess(Result, E);
1626 }
1627 }
1628 }
1629
Peter Collingbournee9200682011-05-13 03:29:01 +00001630 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1631 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1632 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001633 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001634
1635 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001636 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001637 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001638
1639 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1640 }
1641
1642 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1643 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001644 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001645 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001646
Richard Smith11562c52011-10-28 17:51:58 +00001647 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001648 return StmtVisitorTy::Visit(EvalExpr);
1649 }
1650
1651 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001652 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001653 if (!Value) {
1654 const Expr *Source = E->getSourceExpr();
1655 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001656 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001657 if (Source == E) { // sanity checking.
1658 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001659 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001660 }
1661 return StmtVisitorTy::Visit(Source);
1662 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001663 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001664 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001665
Richard Smith254a73d2011-10-28 22:34:42 +00001666 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001667 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001668 QualType CalleeType = Callee->getType();
1669
Richard Smith254a73d2011-10-28 22:34:42 +00001670 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001671 LValue *This = 0, ThisVal;
1672 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001673
Richard Smithe97cbd72011-11-11 04:05:33 +00001674 // Extract function decl and 'this' pointer from the callee.
1675 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001676 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001677 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1678 // Explicit bound member calls, such as x.f() or p->g();
1679 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001680 return false;
1681 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001682 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001683 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1684 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001685 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1686 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001687 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001688 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001689 return Error(Callee);
1690
1691 FD = dyn_cast<FunctionDecl>(Member);
1692 if (!FD)
1693 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001694 } else if (CalleeType->isFunctionPointerType()) {
1695 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001696 if (!Evaluate(Call, Info, Callee))
1697 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001698
Richard Smithf57d8cb2011-12-09 22:58:01 +00001699 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1700 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001701 FD = dyn_cast_or_null<FunctionDecl>(
1702 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001703 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001704 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001705
1706 // Overloaded operator calls to member functions are represented as normal
1707 // calls with '*this' as the first argument.
1708 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1709 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001710 // FIXME: When selecting an implicit conversion for an overloaded
1711 // operator delete, we sometimes try to evaluate calls to conversion
1712 // operators without a 'this' parameter!
1713 if (Args.empty())
1714 return Error(E);
1715
Richard Smithe97cbd72011-11-11 04:05:33 +00001716 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1717 return false;
1718 This = &ThisVal;
1719 Args = Args.slice(1);
1720 }
1721
1722 // Don't call function pointers which have been cast to some other type.
1723 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001724 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001725 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001726 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001727
1728 const FunctionDecl *Definition;
1729 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001730 CCValue CCResult;
1731 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001732
Richard Smithf57d8cb2011-12-09 22:58:01 +00001733 if (!Body || !Definition->isConstexpr() || Definition->isInvalidDecl())
1734 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001735
Richard Smithf57d8cb2011-12-09 22:58:01 +00001736 if (!HandleFunctionCall(E, This, Args, Body, Info, CCResult) ||
1737 !CheckConstantExpression(Info, E, CCResult, Result))
1738 return false;
1739
1740 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001741 }
1742
Richard Smith11562c52011-10-28 17:51:58 +00001743 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1744 return StmtVisitorTy::Visit(E->getInitializer());
1745 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001746 RetTy VisitInitListExpr(const InitListExpr *E) {
1747 if (Info.getLangOpts().CPlusPlus0x) {
1748 if (E->getNumInits() == 0)
1749 return DerivedValueInitialization(E);
1750 if (E->getNumInits() == 1)
1751 return StmtVisitorTy::Visit(E->getInit(0));
1752 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001753 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001754 }
1755 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1756 return DerivedValueInitialization(E);
1757 }
1758 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1759 return DerivedValueInitialization(E);
1760 }
Richard Smith027bf112011-11-17 22:56:20 +00001761 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1762 return DerivedValueInitialization(E);
1763 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001764
Richard Smithd62306a2011-11-10 06:34:14 +00001765 /// A member expression where the object is a prvalue is itself a prvalue.
1766 RetTy VisitMemberExpr(const MemberExpr *E) {
1767 assert(!E->isArrow() && "missing call to bound member function?");
1768
1769 CCValue Val;
1770 if (!Evaluate(Val, Info, E->getBase()))
1771 return false;
1772
1773 QualType BaseTy = E->getBase()->getType();
1774
1775 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001776 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001777 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1778 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1779 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1780
1781 SubobjectDesignator Designator;
1782 Designator.addDecl(FD);
1783
Richard Smithf57d8cb2011-12-09 22:58:01 +00001784 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001785 DerivedSuccess(Val, E);
1786 }
1787
Richard Smith11562c52011-10-28 17:51:58 +00001788 RetTy VisitCastExpr(const CastExpr *E) {
1789 switch (E->getCastKind()) {
1790 default:
1791 break;
1792
1793 case CK_NoOp:
1794 return StmtVisitorTy::Visit(E->getSubExpr());
1795
1796 case CK_LValueToRValue: {
1797 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001798 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1799 return false;
1800 CCValue RVal;
1801 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
1802 return false;
1803 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00001804 }
1805 }
1806
Richard Smithf57d8cb2011-12-09 22:58:01 +00001807 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00001808 }
1809
Richard Smith4a678122011-10-24 18:44:57 +00001810 /// Visit a value which is evaluated, but whose value is ignored.
1811 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001812 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001813 if (!Evaluate(Scratch, Info, E))
1814 Info.EvalStatus.HasSideEffects = true;
1815 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001816};
1817
1818}
1819
1820//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00001821// Common base class for lvalue and temporary evaluation.
1822//===----------------------------------------------------------------------===//
1823namespace {
1824template<class Derived>
1825class LValueExprEvaluatorBase
1826 : public ExprEvaluatorBase<Derived, bool> {
1827protected:
1828 LValue &Result;
1829 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1830 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1831
1832 bool Success(APValue::LValueBase B) {
1833 Result.set(B);
1834 return true;
1835 }
1836
1837public:
1838 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1839 ExprEvaluatorBaseTy(Info), Result(Result) {}
1840
1841 bool Success(const CCValue &V, const Expr *E) {
1842 Result.setFrom(V);
1843 return true;
1844 }
Richard Smith027bf112011-11-17 22:56:20 +00001845
1846 bool CheckValidLValue() {
1847 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1848 // there are no null references, nor once-past-the-end references.
1849 // FIXME: Check for one-past-the-end array indices
1850 return Result.Base && !Result.Designator.Invalid &&
1851 !Result.Designator.OnePastTheEnd;
1852 }
1853
1854 bool VisitMemberExpr(const MemberExpr *E) {
1855 // Handle non-static data members.
1856 QualType BaseTy;
1857 if (E->isArrow()) {
1858 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1859 return false;
1860 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1861 } else {
1862 if (!this->Visit(E->getBase()))
1863 return false;
1864 BaseTy = E->getBase()->getType();
1865 }
1866 // FIXME: In C++11, require the result to be a valid lvalue.
1867
1868 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1869 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00001870 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001871 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1872 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1873 (void)BaseTy;
1874
1875 HandleLValueMember(this->Info, Result, FD);
1876
1877 if (FD->getType()->isReferenceType()) {
1878 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001879 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00001880 RefValue))
1881 return false;
1882 return Success(RefValue, E);
1883 }
1884 return true;
1885 }
1886
1887 bool VisitBinaryOperator(const BinaryOperator *E) {
1888 switch (E->getOpcode()) {
1889 default:
1890 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
1891
1892 case BO_PtrMemD:
1893 case BO_PtrMemI:
1894 return HandleMemberPointerAccess(this->Info, E, Result);
1895 }
1896 }
1897
1898 bool VisitCastExpr(const CastExpr *E) {
1899 switch (E->getCastKind()) {
1900 default:
1901 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1902
1903 case CK_DerivedToBase:
1904 case CK_UncheckedDerivedToBase: {
1905 if (!this->Visit(E->getSubExpr()))
1906 return false;
1907 if (!CheckValidLValue())
1908 return false;
1909
1910 // Now figure out the necessary offset to add to the base LV to get from
1911 // the derived class to the base class.
1912 QualType Type = E->getSubExpr()->getType();
1913
1914 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1915 PathE = E->path_end(); PathI != PathE; ++PathI) {
1916 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
1917 *PathI))
1918 return false;
1919 Type = (*PathI)->getType();
1920 }
1921
1922 return true;
1923 }
1924 }
1925 }
1926};
1927}
1928
1929//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001930// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001931//
1932// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1933// function designators (in C), decl references to void objects (in C), and
1934// temporaries (if building with -Wno-address-of-temporary).
1935//
1936// LValue evaluation produces values comprising a base expression of one of the
1937// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00001938// - Declarations
1939// * VarDecl
1940// * FunctionDecl
1941// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00001942// * CompoundLiteralExpr in C
1943// * StringLiteral
1944// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00001945// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00001946// * ObjCEncodeExpr
1947// * AddrLabelExpr
1948// * BlockExpr
1949// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00001950// - Locals and temporaries
1951// * Any Expr, with a Frame indicating the function in which the temporary was
1952// evaluated.
1953// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00001954//===----------------------------------------------------------------------===//
1955namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001956class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00001957 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00001958public:
Richard Smith027bf112011-11-17 22:56:20 +00001959 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
1960 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001961
Richard Smith11562c52011-10-28 17:51:58 +00001962 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1963
Peter Collingbournee9200682011-05-13 03:29:01 +00001964 bool VisitDeclRefExpr(const DeclRefExpr *E);
1965 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001966 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001967 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1968 bool VisitMemberExpr(const MemberExpr *E);
1969 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1970 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1971 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1972 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001973
Peter Collingbournee9200682011-05-13 03:29:01 +00001974 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001975 switch (E->getCastKind()) {
1976 default:
Richard Smith027bf112011-11-17 22:56:20 +00001977 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001978
Eli Friedmance3e02a2011-10-11 00:13:24 +00001979 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001980 if (!Visit(E->getSubExpr()))
1981 return false;
1982 Result.Designator.setInvalid();
1983 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001984
Richard Smith027bf112011-11-17 22:56:20 +00001985 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00001986 if (!Visit(E->getSubExpr()))
1987 return false;
Richard Smith027bf112011-11-17 22:56:20 +00001988 if (!CheckValidLValue())
1989 return false;
1990 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00001991 }
1992 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00001993
Eli Friedman449fe542009-03-23 04:56:01 +00001994 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00001995
Eli Friedman9a156e52008-11-12 09:44:48 +00001996};
1997} // end anonymous namespace
1998
Richard Smith11562c52011-10-28 17:51:58 +00001999/// Evaluate an expression as an lvalue. This can be legitimately called on
2000/// expressions which are not glvalues, in a few cases:
2001/// * function designators in C,
2002/// * "extern void" objects,
2003/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002004static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002005 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2006 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2007 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002008 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002009}
2010
Peter Collingbournee9200682011-05-13 03:29:01 +00002011bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002012 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2013 return Success(FD);
2014 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002015 return VisitVarDecl(E, VD);
2016 return Error(E);
2017}
Richard Smith733237d2011-10-24 23:14:33 +00002018
Richard Smith11562c52011-10-28 17:51:58 +00002019bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002020 if (!VD->getType()->isReferenceType()) {
2021 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002022 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002023 return true;
2024 }
Richard Smithce40ad62011-11-12 22:28:03 +00002025 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002026 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002027
Richard Smith0b0a0b62011-10-29 20:57:55 +00002028 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002029 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2030 return false;
2031 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002032}
2033
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002034bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2035 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002036 if (E->GetTemporaryExpr()->isRValue()) {
2037 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2038 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2039
2040 Result.set(E, Info.CurrentCall);
2041 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2042 Result, E->GetTemporaryExpr());
2043 }
2044
2045 // Materialization of an lvalue temporary occurs when we need to force a copy
2046 // (for instance, if it's a bitfield).
2047 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2048 if (!Visit(E->GetTemporaryExpr()))
2049 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002050 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002051 Info.CurrentCall->Temporaries[E]))
2052 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002053 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002054 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002055}
2056
Peter Collingbournee9200682011-05-13 03:29:01 +00002057bool
2058LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002059 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2060 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2061 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002062 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002063}
2064
Peter Collingbournee9200682011-05-13 03:29:01 +00002065bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002066 // Handle static data members.
2067 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2068 VisitIgnoredValue(E->getBase());
2069 return VisitVarDecl(E, VD);
2070 }
2071
Richard Smith254a73d2011-10-28 22:34:42 +00002072 // Handle static member functions.
2073 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2074 if (MD->isStatic()) {
2075 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002076 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002077 }
2078 }
2079
Richard Smithd62306a2011-11-10 06:34:14 +00002080 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002081 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002082}
2083
Peter Collingbournee9200682011-05-13 03:29:01 +00002084bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002085 // FIXME: Deal with vectors as array subscript bases.
2086 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002087 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002088
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002089 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002090 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002091
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002092 APSInt Index;
2093 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002094 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002095 int64_t IndexValue
2096 = Index.isSigned() ? Index.getSExtValue()
2097 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002098
Richard Smith027bf112011-11-17 22:56:20 +00002099 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002100 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002101}
Eli Friedman9a156e52008-11-12 09:44:48 +00002102
Peter Collingbournee9200682011-05-13 03:29:01 +00002103bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002104 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002105 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002106}
2107
Eli Friedman9a156e52008-11-12 09:44:48 +00002108//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002109// Pointer Evaluation
2110//===----------------------------------------------------------------------===//
2111
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002112namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002113class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002114 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002115 LValue &Result;
2116
Peter Collingbournee9200682011-05-13 03:29:01 +00002117 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002118 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002119 return true;
2120 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002121public:
Mike Stump11289f42009-09-09 15:08:12 +00002122
John McCall45d55e42010-05-07 21:00:08 +00002123 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002124 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002125
Richard Smith0b0a0b62011-10-29 20:57:55 +00002126 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002127 Result.setFrom(V);
2128 return true;
2129 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002130 bool ValueInitialization(const Expr *E) {
2131 return Success((Expr*)0);
2132 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002133
John McCall45d55e42010-05-07 21:00:08 +00002134 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002135 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002136 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002137 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002138 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002139 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002140 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002141 bool VisitCallExpr(const CallExpr *E);
2142 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002143 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002144 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002145 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002146 }
Richard Smithd62306a2011-11-10 06:34:14 +00002147 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2148 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002149 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002150 Result = *Info.CurrentCall->This;
2151 return true;
2152 }
John McCallc07a0c72011-02-17 10:25:35 +00002153
Eli Friedman449fe542009-03-23 04:56:01 +00002154 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002155};
Chris Lattner05706e882008-07-11 18:11:29 +00002156} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002157
John McCall45d55e42010-05-07 21:00:08 +00002158static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002159 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002160 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002161}
2162
John McCall45d55e42010-05-07 21:00:08 +00002163bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002164 if (E->getOpcode() != BO_Add &&
2165 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002166 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002167
Chris Lattner05706e882008-07-11 18:11:29 +00002168 const Expr *PExp = E->getLHS();
2169 const Expr *IExp = E->getRHS();
2170 if (IExp->getType()->isPointerType())
2171 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002172
John McCall45d55e42010-05-07 21:00:08 +00002173 if (!EvaluatePointer(PExp, Result, Info))
2174 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002175
John McCall45d55e42010-05-07 21:00:08 +00002176 llvm::APSInt Offset;
2177 if (!EvaluateInteger(IExp, Offset, Info))
2178 return false;
2179 int64_t AdditionalOffset
2180 = Offset.isSigned() ? Offset.getSExtValue()
2181 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002182 if (E->getOpcode() == BO_Sub)
2183 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002184
Richard Smithd62306a2011-11-10 06:34:14 +00002185 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002186 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002187 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002188}
Eli Friedman9a156e52008-11-12 09:44:48 +00002189
John McCall45d55e42010-05-07 21:00:08 +00002190bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2191 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002192}
Mike Stump11289f42009-09-09 15:08:12 +00002193
Peter Collingbournee9200682011-05-13 03:29:01 +00002194bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2195 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002196
Eli Friedman847a2bc2009-12-27 05:43:15 +00002197 switch (E->getCastKind()) {
2198 default:
2199 break;
2200
John McCalle3027922010-08-25 11:45:40 +00002201 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002202 case CK_CPointerToObjCPointerCast:
2203 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002204 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00002205 if (!Visit(SubExpr))
2206 return false;
2207 Result.Designator.setInvalid();
2208 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002209
Anders Carlsson18275092010-10-31 20:41:46 +00002210 case CK_DerivedToBase:
2211 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002212 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002213 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002214 if (!Result.Base && Result.Offset.isZero())
2215 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002216
Richard Smithd62306a2011-11-10 06:34:14 +00002217 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002218 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002219 QualType Type =
2220 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002221
Richard Smithd62306a2011-11-10 06:34:14 +00002222 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002223 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002224 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002225 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002226 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002227 }
2228
Anders Carlsson18275092010-10-31 20:41:46 +00002229 return true;
2230 }
2231
Richard Smith027bf112011-11-17 22:56:20 +00002232 case CK_BaseToDerived:
2233 if (!Visit(E->getSubExpr()))
2234 return false;
2235 if (!Result.Base && Result.Offset.isZero())
2236 return true;
2237 return HandleBaseToDerivedCast(Info, E, Result);
2238
Richard Smith0b0a0b62011-10-29 20:57:55 +00002239 case CK_NullToPointer:
2240 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002241
John McCalle3027922010-08-25 11:45:40 +00002242 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002243 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002244 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002245 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002246
John McCall45d55e42010-05-07 21:00:08 +00002247 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002248 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2249 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002250 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002251 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002252 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002253 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002254 return true;
2255 } else {
2256 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002257 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002258 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002259 }
2260 }
John McCalle3027922010-08-25 11:45:40 +00002261 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002262 if (SubExpr->isGLValue()) {
2263 if (!EvaluateLValue(SubExpr, Result, Info))
2264 return false;
2265 } else {
2266 Result.set(SubExpr, Info.CurrentCall);
2267 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2268 Info, Result, SubExpr))
2269 return false;
2270 }
Richard Smith96e0c102011-11-04 02:25:55 +00002271 // The result is a pointer to the first element of the array.
2272 Result.Designator.addIndex(0);
2273 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002274
John McCalle3027922010-08-25 11:45:40 +00002275 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002276 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002277 }
2278
Richard Smith11562c52011-10-28 17:51:58 +00002279 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002280}
Chris Lattner05706e882008-07-11 18:11:29 +00002281
Peter Collingbournee9200682011-05-13 03:29:01 +00002282bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002283 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002284 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002285
Peter Collingbournee9200682011-05-13 03:29:01 +00002286 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002287}
Chris Lattner05706e882008-07-11 18:11:29 +00002288
2289//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002290// Member Pointer Evaluation
2291//===----------------------------------------------------------------------===//
2292
2293namespace {
2294class MemberPointerExprEvaluator
2295 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2296 MemberPtr &Result;
2297
2298 bool Success(const ValueDecl *D) {
2299 Result = MemberPtr(D);
2300 return true;
2301 }
2302public:
2303
2304 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2305 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2306
2307 bool Success(const CCValue &V, const Expr *E) {
2308 Result.setFrom(V);
2309 return true;
2310 }
Richard Smith027bf112011-11-17 22:56:20 +00002311 bool ValueInitialization(const Expr *E) {
2312 return Success((const ValueDecl*)0);
2313 }
2314
2315 bool VisitCastExpr(const CastExpr *E);
2316 bool VisitUnaryAddrOf(const UnaryOperator *E);
2317};
2318} // end anonymous namespace
2319
2320static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2321 EvalInfo &Info) {
2322 assert(E->isRValue() && E->getType()->isMemberPointerType());
2323 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2324}
2325
2326bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2327 switch (E->getCastKind()) {
2328 default:
2329 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2330
2331 case CK_NullToMemberPointer:
2332 return ValueInitialization(E);
2333
2334 case CK_BaseToDerivedMemberPointer: {
2335 if (!Visit(E->getSubExpr()))
2336 return false;
2337 if (E->path_empty())
2338 return true;
2339 // Base-to-derived member pointer casts store the path in derived-to-base
2340 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2341 // the wrong end of the derived->base arc, so stagger the path by one class.
2342 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2343 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2344 PathI != PathE; ++PathI) {
2345 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2346 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2347 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002348 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002349 }
2350 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2351 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002352 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002353 return true;
2354 }
2355
2356 case CK_DerivedToBaseMemberPointer:
2357 if (!Visit(E->getSubExpr()))
2358 return false;
2359 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2360 PathE = E->path_end(); PathI != PathE; ++PathI) {
2361 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2362 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2363 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002364 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002365 }
2366 return true;
2367 }
2368}
2369
2370bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2371 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2372 // member can be formed.
2373 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2374}
2375
2376//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002377// Record Evaluation
2378//===----------------------------------------------------------------------===//
2379
2380namespace {
2381 class RecordExprEvaluator
2382 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2383 const LValue &This;
2384 APValue &Result;
2385 public:
2386
2387 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2388 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2389
2390 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002391 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002392 }
Richard Smithd62306a2011-11-10 06:34:14 +00002393
Richard Smithe97cbd72011-11-11 04:05:33 +00002394 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002395 bool VisitInitListExpr(const InitListExpr *E);
2396 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2397 };
2398}
2399
Richard Smithe97cbd72011-11-11 04:05:33 +00002400bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2401 switch (E->getCastKind()) {
2402 default:
2403 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2404
2405 case CK_ConstructorConversion:
2406 return Visit(E->getSubExpr());
2407
2408 case CK_DerivedToBase:
2409 case CK_UncheckedDerivedToBase: {
2410 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002411 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002412 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002413 if (!DerivedObject.isStruct())
2414 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002415
2416 // Derived-to-base rvalue conversion: just slice off the derived part.
2417 APValue *Value = &DerivedObject;
2418 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2419 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2420 PathE = E->path_end(); PathI != PathE; ++PathI) {
2421 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2422 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2423 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2424 RD = Base;
2425 }
2426 Result = *Value;
2427 return true;
2428 }
2429 }
2430}
2431
Richard Smithd62306a2011-11-10 06:34:14 +00002432bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2433 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2434 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2435
2436 if (RD->isUnion()) {
2437 Result = APValue(E->getInitializedFieldInUnion());
2438 if (!E->getNumInits())
2439 return true;
2440 LValue Subobject = This;
2441 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2442 &Layout);
2443 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2444 Subobject, E->getInit(0));
2445 }
2446
2447 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2448 "initializer list for class with base classes");
2449 Result = APValue(APValue::UninitStruct(), 0,
2450 std::distance(RD->field_begin(), RD->field_end()));
2451 unsigned ElementNo = 0;
2452 for (RecordDecl::field_iterator Field = RD->field_begin(),
2453 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2454 // Anonymous bit-fields are not considered members of the class for
2455 // purposes of aggregate initialization.
2456 if (Field->isUnnamedBitfield())
2457 continue;
2458
2459 LValue Subobject = This;
2460 HandleLValueMember(Info, Subobject, *Field, &Layout);
2461
2462 if (ElementNo < E->getNumInits()) {
2463 if (!EvaluateConstantExpression(
2464 Result.getStructField((*Field)->getFieldIndex()),
2465 Info, Subobject, E->getInit(ElementNo++)))
2466 return false;
2467 } else {
2468 // Perform an implicit value-initialization for members beyond the end of
2469 // the initializer list.
2470 ImplicitValueInitExpr VIE(Field->getType());
2471 if (!EvaluateConstantExpression(
2472 Result.getStructField((*Field)->getFieldIndex()),
2473 Info, Subobject, &VIE))
2474 return false;
2475 }
2476 }
2477
2478 return true;
2479}
2480
2481bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2482 const CXXConstructorDecl *FD = E->getConstructor();
2483 const FunctionDecl *Definition = 0;
2484 FD->getBody(Definition);
2485
2486 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002487 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002488
2489 // FIXME: Elide the copy/move construction wherever we can.
2490 if (E->isElidable())
2491 if (const MaterializeTemporaryExpr *ME
2492 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2493 return Visit(ME->GetTemporaryExpr());
2494
2495 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002496 return HandleConstructorCall(E, This, Args,
2497 cast<CXXConstructorDecl>(Definition), Info,
2498 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002499}
2500
2501static bool EvaluateRecord(const Expr *E, const LValue &This,
2502 APValue &Result, EvalInfo &Info) {
2503 assert(E->isRValue() && E->getType()->isRecordType() &&
2504 E->getType()->isLiteralType() &&
2505 "can't evaluate expression as a record rvalue");
2506 return RecordExprEvaluator(Info, This, Result).Visit(E);
2507}
2508
2509//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002510// Temporary Evaluation
2511//
2512// Temporaries are represented in the AST as rvalues, but generally behave like
2513// lvalues. The full-object of which the temporary is a subobject is implicitly
2514// materialized so that a reference can bind to it.
2515//===----------------------------------------------------------------------===//
2516namespace {
2517class TemporaryExprEvaluator
2518 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2519public:
2520 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2521 LValueExprEvaluatorBaseTy(Info, Result) {}
2522
2523 /// Visit an expression which constructs the value of this temporary.
2524 bool VisitConstructExpr(const Expr *E) {
2525 Result.set(E, Info.CurrentCall);
2526 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2527 Result, E);
2528 }
2529
2530 bool VisitCastExpr(const CastExpr *E) {
2531 switch (E->getCastKind()) {
2532 default:
2533 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2534
2535 case CK_ConstructorConversion:
2536 return VisitConstructExpr(E->getSubExpr());
2537 }
2538 }
2539 bool VisitInitListExpr(const InitListExpr *E) {
2540 return VisitConstructExpr(E);
2541 }
2542 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2543 return VisitConstructExpr(E);
2544 }
2545 bool VisitCallExpr(const CallExpr *E) {
2546 return VisitConstructExpr(E);
2547 }
2548};
2549} // end anonymous namespace
2550
2551/// Evaluate an expression of record type as a temporary.
2552static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2553 assert(E->isRValue() && E->getType()->isRecordType() &&
2554 E->getType()->isLiteralType());
2555 return TemporaryExprEvaluator(Info, Result).Visit(E);
2556}
2557
2558//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002559// Vector Evaluation
2560//===----------------------------------------------------------------------===//
2561
2562namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002563 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002564 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2565 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002566 public:
Mike Stump11289f42009-09-09 15:08:12 +00002567
Richard Smith2d406342011-10-22 21:10:00 +00002568 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2569 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002570
Richard Smith2d406342011-10-22 21:10:00 +00002571 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2572 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2573 // FIXME: remove this APValue copy.
2574 Result = APValue(V.data(), V.size());
2575 return true;
2576 }
Richard Smithed5165f2011-11-04 05:33:44 +00002577 bool Success(const CCValue &V, const Expr *E) {
2578 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002579 Result = V;
2580 return true;
2581 }
Richard Smith2d406342011-10-22 21:10:00 +00002582 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002583
Richard Smith2d406342011-10-22 21:10:00 +00002584 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002585 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002586 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002587 bool VisitInitListExpr(const InitListExpr *E);
2588 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002589 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002590 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002591 // shufflevector, ExtVectorElementExpr
2592 // (Note that these require implementing conversions
2593 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002594 };
2595} // end anonymous namespace
2596
2597static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002598 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002599 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002600}
2601
Richard Smith2d406342011-10-22 21:10:00 +00002602bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2603 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002604 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002605
Richard Smith161f09a2011-12-06 22:44:34 +00002606 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002607 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002608
Eli Friedmanc757de22011-03-25 00:43:55 +00002609 switch (E->getCastKind()) {
2610 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002611 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002612 if (SETy->isIntegerType()) {
2613 APSInt IntResult;
2614 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002615 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002616 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002617 } else if (SETy->isRealFloatingType()) {
2618 APFloat F(0.0);
2619 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002620 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002621 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002622 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002623 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002624 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002625
2626 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002627 SmallVector<APValue, 4> Elts(NElts, Val);
2628 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002629 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002630 default:
Richard Smith11562c52011-10-28 17:51:58 +00002631 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002632 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002633}
2634
Richard Smith2d406342011-10-22 21:10:00 +00002635bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002636VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002637 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002638 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002639 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002640
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002641 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002642 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002643
John McCall875679e2010-06-11 17:54:15 +00002644 // If a vector is initialized with a single element, that value
2645 // becomes every element of the vector, not just the first.
2646 // This is the behavior described in the IBM AltiVec documentation.
2647 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002648
2649 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002650 // vector (OpenCL 6.1.6).
2651 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002652 return Visit(E->getInit(0));
2653
John McCall875679e2010-06-11 17:54:15 +00002654 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002655 if (EltTy->isIntegerType()) {
2656 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002657 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 return false;
John McCall875679e2010-06-11 17:54:15 +00002659 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002660 } else {
2661 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002662 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002663 return false;
John McCall875679e2010-06-11 17:54:15 +00002664 InitValue = APValue(f);
2665 }
2666 for (unsigned i = 0; i < NumElements; i++) {
2667 Elements.push_back(InitValue);
2668 }
2669 } else {
2670 for (unsigned i = 0; i < NumElements; i++) {
2671 if (EltTy->isIntegerType()) {
2672 llvm::APSInt sInt(32);
2673 if (i < NumInits) {
2674 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002675 return false;
John McCall875679e2010-06-11 17:54:15 +00002676 } else {
2677 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2678 }
2679 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002680 } else {
John McCall875679e2010-06-11 17:54:15 +00002681 llvm::APFloat f(0.0);
2682 if (i < NumInits) {
2683 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002684 return false;
John McCall875679e2010-06-11 17:54:15 +00002685 } else {
2686 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2687 }
2688 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002689 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002690 }
2691 }
Richard Smith2d406342011-10-22 21:10:00 +00002692 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002693}
2694
Richard Smith2d406342011-10-22 21:10:00 +00002695bool
2696VectorExprEvaluator::ValueInitialization(const Expr *E) {
2697 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002698 QualType EltTy = VT->getElementType();
2699 APValue ZeroElement;
2700 if (EltTy->isIntegerType())
2701 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2702 else
2703 ZeroElement =
2704 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2705
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002706 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002707 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002708}
2709
Richard Smith2d406342011-10-22 21:10:00 +00002710bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002711 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002712 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002713}
2714
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002715//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002716// Array Evaluation
2717//===----------------------------------------------------------------------===//
2718
2719namespace {
2720 class ArrayExprEvaluator
2721 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002722 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002723 APValue &Result;
2724 public:
2725
Richard Smithd62306a2011-11-10 06:34:14 +00002726 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2727 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002728
2729 bool Success(const APValue &V, const Expr *E) {
2730 assert(V.isArray() && "Expected array type");
2731 Result = V;
2732 return true;
2733 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002734
Richard Smithd62306a2011-11-10 06:34:14 +00002735 bool ValueInitialization(const Expr *E) {
2736 const ConstantArrayType *CAT =
2737 Info.Ctx.getAsConstantArrayType(E->getType());
2738 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002739 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002740
2741 Result = APValue(APValue::UninitArray(), 0,
2742 CAT->getSize().getZExtValue());
2743 if (!Result.hasArrayFiller()) return true;
2744
2745 // Value-initialize all elements.
2746 LValue Subobject = This;
2747 Subobject.Designator.addIndex(0);
2748 ImplicitValueInitExpr VIE(CAT->getElementType());
2749 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2750 Subobject, &VIE);
2751 }
2752
Richard Smithf3e9e432011-11-07 09:22:26 +00002753 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002754 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002755 };
2756} // end anonymous namespace
2757
Richard Smithd62306a2011-11-10 06:34:14 +00002758static bool EvaluateArray(const Expr *E, const LValue &This,
2759 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002760 assert(E->isRValue() && E->getType()->isArrayType() &&
2761 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002762 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002763}
2764
2765bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2766 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2767 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002768 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002769
2770 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2771 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002772 LValue Subobject = This;
2773 Subobject.Designator.addIndex(0);
2774 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002775 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002776 I != End; ++I, ++Index) {
2777 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2778 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002779 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002780 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2781 return false;
2782 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002783
2784 if (!Result.hasArrayFiller()) return true;
2785 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00002786 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2787 // but sometimes does:
2788 // struct S { constexpr S() : p(&p) {} void *p; };
2789 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00002790 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00002791 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00002792}
2793
Richard Smith027bf112011-11-17 22:56:20 +00002794bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2795 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2796 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002797 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002798
2799 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2800 if (!Result.hasArrayFiller())
2801 return true;
2802
2803 const CXXConstructorDecl *FD = E->getConstructor();
2804 const FunctionDecl *Definition = 0;
2805 FD->getBody(Definition);
2806
2807 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002808 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002809
2810 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2811 // but sometimes does:
2812 // struct S { constexpr S() : p(&p) {} void *p; };
2813 // S s[10];
2814 LValue Subobject = This;
2815 Subobject.Designator.addIndex(0);
2816 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002817 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00002818 cast<CXXConstructorDecl>(Definition),
2819 Info, Result.getArrayFiller());
2820}
2821
Richard Smithf3e9e432011-11-07 09:22:26 +00002822//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002823// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002824//
2825// As a GNU extension, we support casting pointers to sufficiently-wide integer
2826// types and back in constant folding. Integer values are thus represented
2827// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00002828//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002829
2830namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002831class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002832 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002833 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002834public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002835 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002836 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002837
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002838 bool Success(const llvm::APSInt &SI, const Expr *E) {
2839 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002840 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002841 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002842 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002843 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002844 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002845 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002846 return true;
2847 }
2848
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002849 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002850 assert(E->getType()->isIntegralOrEnumerationType() &&
2851 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002852 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002853 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002854 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002855 Result.getInt().setIsUnsigned(
2856 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002857 return true;
2858 }
2859
2860 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002861 assert(E->getType()->isIntegralOrEnumerationType() &&
2862 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002863 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002864 return true;
2865 }
2866
Ken Dyckdbc01912011-03-11 02:13:43 +00002867 bool Success(CharUnits Size, const Expr *E) {
2868 return Success(Size.getQuantity(), E);
2869 }
2870
Richard Smith0b0a0b62011-10-29 20:57:55 +00002871 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00002872 if (V.isLValue()) {
2873 Result = V;
2874 return true;
2875 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002876 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002877 }
Mike Stump11289f42009-09-09 15:08:12 +00002878
Richard Smith4ce706a2011-10-11 21:43:33 +00002879 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2880
Peter Collingbournee9200682011-05-13 03:29:01 +00002881 //===--------------------------------------------------------------------===//
2882 // Visitor Methods
2883 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002884
Chris Lattner7174bf32008-07-12 00:38:25 +00002885 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002886 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002887 }
2888 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002889 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002890 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002891
2892 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2893 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002894 if (CheckReferencedDecl(E, E->getDecl()))
2895 return true;
2896
2897 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002898 }
2899 bool VisitMemberExpr(const MemberExpr *E) {
2900 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00002901 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002902 return true;
2903 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002904
2905 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002906 }
2907
Peter Collingbournee9200682011-05-13 03:29:01 +00002908 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002909 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00002910 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002911 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00002912
Peter Collingbournee9200682011-05-13 03:29:01 +00002913 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002914 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00002915
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002916 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002917 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002918 }
Mike Stump11289f42009-09-09 15:08:12 +00002919
Richard Smith4ce706a2011-10-11 21:43:33 +00002920 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00002921 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002922 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002923 }
2924
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002925 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002926 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002927 }
2928
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002929 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2930 return Success(E->getValue(), E);
2931 }
2932
John Wiegley6242b6a2011-04-28 00:16:57 +00002933 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2934 return Success(E->getValue(), E);
2935 }
2936
John Wiegleyf9f65842011-04-25 06:54:41 +00002937 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2938 return Success(E->getValue(), E);
2939 }
2940
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002941 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002942 bool VisitUnaryImag(const UnaryOperator *E);
2943
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002944 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002945 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002946
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002947private:
Ken Dyck160146e2010-01-27 17:10:57 +00002948 CharUnits GetAlignOfExpr(const Expr *E);
2949 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00002950 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00002951 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002952 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00002953};
Chris Lattner05706e882008-07-11 18:11:29 +00002954} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002955
Richard Smith11562c52011-10-28 17:51:58 +00002956/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2957/// produce either the integer value or a pointer.
2958///
2959/// GCC has a heinous extension which folds casts between pointer types and
2960/// pointer-sized integral types. We support this by allowing the evaluation of
2961/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2962/// Some simple arithmetic on such values is supported (they are treated much
2963/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00002964static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00002965 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002966 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002967 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00002968}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002969
Richard Smithf57d8cb2011-12-09 22:58:01 +00002970static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002971 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002972 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00002973 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002974 if (!Val.isInt()) {
2975 // FIXME: It would be better to produce the diagnostic for casting
2976 // a pointer to an integer.
2977 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
2978 return false;
2979 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002980 Result = Val.getInt();
2981 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002982}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002983
Richard Smithf57d8cb2011-12-09 22:58:01 +00002984/// Check whether the given declaration can be directly converted to an integral
2985/// rvalue. If not, no diagnostic is produced; there are other things we can
2986/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002987bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002988 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00002989 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002990 // Check for signedness/width mismatches between E type and ECD value.
2991 bool SameSign = (ECD->getInitVal().isSigned()
2992 == E->getType()->isSignedIntegerOrEnumerationType());
2993 bool SameWidth = (ECD->getInitVal().getBitWidth()
2994 == Info.Ctx.getIntWidth(E->getType()));
2995 if (SameSign && SameWidth)
2996 return Success(ECD->getInitVal(), E);
2997 else {
2998 // Get rid of mismatch (otherwise Success assertions will fail)
2999 // by computing a new value matching the type of E.
3000 llvm::APSInt Val = ECD->getInitVal();
3001 if (!SameSign)
3002 Val.setIsSigned(!ECD->getInitVal().isSigned());
3003 if (!SameWidth)
3004 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3005 return Success(Val, E);
3006 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003007 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003008 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003009}
3010
Chris Lattner86ee2862008-10-06 06:40:35 +00003011/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3012/// as GCC.
3013static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3014 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003015 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003016 enum gcc_type_class {
3017 no_type_class = -1,
3018 void_type_class, integer_type_class, char_type_class,
3019 enumeral_type_class, boolean_type_class,
3020 pointer_type_class, reference_type_class, offset_type_class,
3021 real_type_class, complex_type_class,
3022 function_type_class, method_type_class,
3023 record_type_class, union_type_class,
3024 array_type_class, string_type_class,
3025 lang_type_class
3026 };
Mike Stump11289f42009-09-09 15:08:12 +00003027
3028 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003029 // ideal, however it is what gcc does.
3030 if (E->getNumArgs() == 0)
3031 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003032
Chris Lattner86ee2862008-10-06 06:40:35 +00003033 QualType ArgTy = E->getArg(0)->getType();
3034 if (ArgTy->isVoidType())
3035 return void_type_class;
3036 else if (ArgTy->isEnumeralType())
3037 return enumeral_type_class;
3038 else if (ArgTy->isBooleanType())
3039 return boolean_type_class;
3040 else if (ArgTy->isCharType())
3041 return string_type_class; // gcc doesn't appear to use char_type_class
3042 else if (ArgTy->isIntegerType())
3043 return integer_type_class;
3044 else if (ArgTy->isPointerType())
3045 return pointer_type_class;
3046 else if (ArgTy->isReferenceType())
3047 return reference_type_class;
3048 else if (ArgTy->isRealType())
3049 return real_type_class;
3050 else if (ArgTy->isComplexType())
3051 return complex_type_class;
3052 else if (ArgTy->isFunctionType())
3053 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003054 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003055 return record_type_class;
3056 else if (ArgTy->isUnionType())
3057 return union_type_class;
3058 else if (ArgTy->isArrayType())
3059 return array_type_class;
3060 else if (ArgTy->isUnionType())
3061 return union_type_class;
3062 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003063 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003064 return -1;
3065}
3066
John McCall95007602010-05-10 23:27:23 +00003067/// Retrieves the "underlying object type" of the given expression,
3068/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003069QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3070 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3071 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003072 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003073 } else if (const Expr *E = B.get<const Expr*>()) {
3074 if (isa<CompoundLiteralExpr>(E))
3075 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003076 }
3077
3078 return QualType();
3079}
3080
Peter Collingbournee9200682011-05-13 03:29:01 +00003081bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003082 // TODO: Perhaps we should let LLVM lower this?
3083 LValue Base;
3084 if (!EvaluatePointer(E->getArg(0), Base, Info))
3085 return false;
3086
3087 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003088 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003089
Richard Smithce40ad62011-11-12 22:28:03 +00003090 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003091 if (T.isNull() ||
3092 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003093 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003094 T->isVariablyModifiedType() ||
3095 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003096 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003097
3098 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3099 CharUnits Offset = Base.getLValueOffset();
3100
3101 if (!Offset.isNegative() && Offset <= Size)
3102 Size -= Offset;
3103 else
3104 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003105 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003106}
3107
Peter Collingbournee9200682011-05-13 03:29:01 +00003108bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003109 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003110 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003111 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003112
3113 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003114 if (TryEvaluateBuiltinObjectSize(E))
3115 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003116
Eric Christopher99469702010-01-19 22:58:35 +00003117 // If evaluating the argument has side-effects we can't determine
3118 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003119 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003120 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003121 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003122 return Success(0, E);
3123 }
Mike Stump876387b2009-10-27 22:09:17 +00003124
Richard Smithf57d8cb2011-12-09 22:58:01 +00003125 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003126 }
3127
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003128 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003129 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003130
Richard Smith10c7c902011-12-09 02:04:48 +00003131 case Builtin::BI__builtin_constant_p: {
3132 const Expr *Arg = E->getArg(0);
3133 QualType ArgType = Arg->getType();
3134 // __builtin_constant_p always has one operand. The rules which gcc follows
3135 // are not precisely documented, but are as follows:
3136 //
3137 // - If the operand is of integral, floating, complex or enumeration type,
3138 // and can be folded to a known value of that type, it returns 1.
3139 // - If the operand and can be folded to a pointer to the first character
3140 // of a string literal (or such a pointer cast to an integral type), it
3141 // returns 1.
3142 //
3143 // Otherwise, it returns 0.
3144 //
3145 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3146 // its support for this does not currently work.
3147 int IsConstant = 0;
3148 if (ArgType->isIntegralOrEnumerationType()) {
3149 // Note, a pointer cast to an integral type is only a constant if it is
3150 // a pointer to the first character of a string literal.
3151 Expr::EvalResult Result;
3152 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3153 APValue &V = Result.Val;
3154 if (V.getKind() == APValue::LValue) {
3155 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3156 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3157 } else {
3158 IsConstant = 1;
3159 }
3160 }
3161 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3162 IsConstant = Arg->isEvaluatable(Info.Ctx);
3163 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3164 LValue LV;
3165 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3166 // during the check.
3167 Expr::EvalStatus Status;
3168 EvalInfo SubInfo(Info.Ctx, Status);
3169 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3170 : EvaluatePointer(Arg, LV, SubInfo)) &&
3171 !Status.HasSideEffects)
3172 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3173 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3174 }
3175
3176 return Success(IsConstant, E);
3177 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003178 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003179 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003180 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003181 return Success(Operand, E);
3182 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003183
3184 case Builtin::BI__builtin_expect:
3185 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003186
3187 case Builtin::BIstrlen:
3188 case Builtin::BI__builtin_strlen:
3189 // As an extension, we support strlen() and __builtin_strlen() as constant
3190 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003191 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003192 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3193 // The string literal may have embedded null characters. Find the first
3194 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003195 StringRef Str = S->getString();
3196 StringRef::size_type Pos = Str.find(0);
3197 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003198 Str = Str.substr(0, Pos);
3199
3200 return Success(Str.size(), E);
3201 }
3202
Richard Smithf57d8cb2011-12-09 22:58:01 +00003203 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003204
3205 case Builtin::BI__atomic_is_lock_free: {
3206 APSInt SizeVal;
3207 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3208 return false;
3209
3210 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3211 // of two less than the maximum inline atomic width, we know it is
3212 // lock-free. If the size isn't a power of two, or greater than the
3213 // maximum alignment where we promote atomics, we know it is not lock-free
3214 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3215 // the answer can only be determined at runtime; for example, 16-byte
3216 // atomics have lock-free implementations on some, but not all,
3217 // x86-64 processors.
3218
3219 // Check power-of-two.
3220 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3221 if (!Size.isPowerOfTwo())
3222#if 0
3223 // FIXME: Suppress this folding until the ABI for the promotion width
3224 // settles.
3225 return Success(0, E);
3226#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003227 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003228#endif
3229
3230#if 0
3231 // Check against promotion width.
3232 // FIXME: Suppress this folding until the ABI for the promotion width
3233 // settles.
3234 unsigned PromoteWidthBits =
3235 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3236 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3237 return Success(0, E);
3238#endif
3239
3240 // Check against inlining width.
3241 unsigned InlineWidthBits =
3242 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3243 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3244 return Success(1, E);
3245
Richard Smithf57d8cb2011-12-09 22:58:01 +00003246 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003247 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003248 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003249}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003250
Richard Smith8b3497e2011-10-31 01:37:14 +00003251static bool HasSameBase(const LValue &A, const LValue &B) {
3252 if (!A.getLValueBase())
3253 return !B.getLValueBase();
3254 if (!B.getLValueBase())
3255 return false;
3256
Richard Smithce40ad62011-11-12 22:28:03 +00003257 if (A.getLValueBase().getOpaqueValue() !=
3258 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003259 const Decl *ADecl = GetLValueBaseDecl(A);
3260 if (!ADecl)
3261 return false;
3262 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003263 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003264 return false;
3265 }
3266
3267 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003268 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003269}
3270
Chris Lattnere13042c2008-07-11 19:10:17 +00003271bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003272 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003273 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003274
John McCalle3027922010-08-25 11:45:40 +00003275 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003276 VisitIgnoredValue(E->getLHS());
3277 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003278 }
3279
3280 if (E->isLogicalOp()) {
3281 // These need to be handled specially because the operands aren't
3282 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003283 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003284
Richard Smith11562c52011-10-28 17:51:58 +00003285 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003286 // We were able to evaluate the LHS, see if we can get away with not
3287 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003288 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003289 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003290
Richard Smith11562c52011-10-28 17:51:58 +00003291 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003292 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003293 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003294 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003295 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003296 }
3297 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003298 // FIXME: If both evaluations fail, we should produce the diagnostic from
3299 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3300 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003301 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003302 // We can't evaluate the LHS; however, sometimes the result
3303 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003304 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003305 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003306 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003307 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003308
3309 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003310 }
3311 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003312 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003313
Eli Friedman5a332ea2008-11-13 06:09:17 +00003314 return false;
3315 }
3316
Anders Carlssonacc79812008-11-16 07:17:21 +00003317 QualType LHSTy = E->getLHS()->getType();
3318 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003319
3320 if (LHSTy->isAnyComplexType()) {
3321 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003322 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003323
3324 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3325 return false;
3326
3327 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3328 return false;
3329
3330 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003331 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003332 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003333 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003334 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3335
John McCalle3027922010-08-25 11:45:40 +00003336 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003337 return Success((CR_r == APFloat::cmpEqual &&
3338 CR_i == APFloat::cmpEqual), E);
3339 else {
John McCalle3027922010-08-25 11:45:40 +00003340 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003341 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003342 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003343 CR_r == APFloat::cmpLessThan ||
3344 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003345 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003346 CR_i == APFloat::cmpLessThan ||
3347 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003348 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003349 } else {
John McCalle3027922010-08-25 11:45:40 +00003350 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003351 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3352 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3353 else {
John McCalle3027922010-08-25 11:45:40 +00003354 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003355 "Invalid compex comparison.");
3356 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3357 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3358 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003359 }
3360 }
Mike Stump11289f42009-09-09 15:08:12 +00003361
Anders Carlssonacc79812008-11-16 07:17:21 +00003362 if (LHSTy->isRealFloatingType() &&
3363 RHSTy->isRealFloatingType()) {
3364 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003365
Anders Carlssonacc79812008-11-16 07:17:21 +00003366 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3367 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003368
Anders Carlssonacc79812008-11-16 07:17:21 +00003369 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3370 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003371
Anders Carlssonacc79812008-11-16 07:17:21 +00003372 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003373
Anders Carlssonacc79812008-11-16 07:17:21 +00003374 switch (E->getOpcode()) {
3375 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003376 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003377 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003378 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003379 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003380 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003381 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003382 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003383 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003384 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003385 E);
John McCalle3027922010-08-25 11:45:40 +00003386 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003387 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003388 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003389 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003390 || CR == APFloat::cmpLessThan
3391 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003392 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003393 }
Mike Stump11289f42009-09-09 15:08:12 +00003394
Eli Friedmana38da572009-04-28 19:17:36 +00003395 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003396 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003397 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003398 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3399 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003400
John McCall45d55e42010-05-07 21:00:08 +00003401 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003402 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3403 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003404
Richard Smith8b3497e2011-10-31 01:37:14 +00003405 // Reject differing bases from the normal codepath; we special-case
3406 // comparisons to null.
3407 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003408 // Inequalities and subtractions between unrelated pointers have
3409 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003410 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003411 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003412 // A constant address may compare equal to the address of a symbol.
3413 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003414 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003415 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3416 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003417 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003418 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003419 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003420 // distinct. However, we do know that the address of a literal will be
3421 // non-null.
3422 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3423 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003424 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003425 // We can't tell whether weak symbols will end up pointing to the same
3426 // object.
3427 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003428 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003429 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003430 // (Note that clang defaults to -fmerge-all-constants, which can
3431 // lead to inconsistent results for comparisons involving the address
3432 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003433 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003434 }
Eli Friedman64004332009-03-23 04:38:34 +00003435
Richard Smithf3e9e432011-11-07 09:22:26 +00003436 // FIXME: Implement the C++11 restrictions:
3437 // - Pointer subtractions must be on elements of the same array.
3438 // - Pointer comparisons must be between members with the same access.
3439
John McCalle3027922010-08-25 11:45:40 +00003440 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003441 QualType Type = E->getLHS()->getType();
3442 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003443
Richard Smithd62306a2011-11-10 06:34:14 +00003444 CharUnits ElementSize;
3445 if (!HandleSizeof(Info, ElementType, ElementSize))
3446 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003447
Richard Smithd62306a2011-11-10 06:34:14 +00003448 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003449 RHSValue.getLValueOffset();
3450 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003451 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003452
3453 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3454 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3455 switch (E->getOpcode()) {
3456 default: llvm_unreachable("missing comparison operator");
3457 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3458 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3459 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3460 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3461 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3462 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003463 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003464 }
3465 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003466 if (!LHSTy->isIntegralOrEnumerationType() ||
3467 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003468 // We can't continue from here for non-integral types.
3469 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003470 }
3471
Anders Carlsson9c181652008-07-08 14:35:21 +00003472 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003473 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003474 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003475 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003476
Richard Smith11562c52011-10-28 17:51:58 +00003477 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003478 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003479 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003480
3481 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003482 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003483 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3484 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003485 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003486 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003487 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003488 LHSVal.getLValueOffset() -= AdditionalOffset;
3489 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003490 return true;
3491 }
3492
3493 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003494 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003495 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003496 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3497 LHSVal.getInt().getZExtValue());
3498 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003499 return true;
3500 }
3501
3502 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003503 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003504 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003505
Richard Smith11562c52011-10-28 17:51:58 +00003506 APSInt &LHS = LHSVal.getInt();
3507 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003508
Anders Carlsson9c181652008-07-08 14:35:21 +00003509 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003510 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003511 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003512 case BO_Mul: return Success(LHS * RHS, E);
3513 case BO_Add: return Success(LHS + RHS, E);
3514 case BO_Sub: return Success(LHS - RHS, E);
3515 case BO_And: return Success(LHS & RHS, E);
3516 case BO_Xor: return Success(LHS ^ RHS, E);
3517 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003518 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003519 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003520 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003521 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003522 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003523 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003524 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003525 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003526 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003527 // During constant-folding, a negative shift is an opposite shift.
3528 if (RHS.isSigned() && RHS.isNegative()) {
3529 RHS = -RHS;
3530 goto shift_right;
3531 }
3532
3533 shift_left:
3534 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003535 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3536 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003537 }
John McCalle3027922010-08-25 11:45:40 +00003538 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003539 // During constant-folding, a negative shift is an opposite shift.
3540 if (RHS.isSigned() && RHS.isNegative()) {
3541 RHS = -RHS;
3542 goto shift_left;
3543 }
3544
3545 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003546 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003547 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3548 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003549 }
Mike Stump11289f42009-09-09 15:08:12 +00003550
Richard Smith11562c52011-10-28 17:51:58 +00003551 case BO_LT: return Success(LHS < RHS, E);
3552 case BO_GT: return Success(LHS > RHS, E);
3553 case BO_LE: return Success(LHS <= RHS, E);
3554 case BO_GE: return Success(LHS >= RHS, E);
3555 case BO_EQ: return Success(LHS == RHS, E);
3556 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003557 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003558}
3559
Ken Dyck160146e2010-01-27 17:10:57 +00003560CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003561 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3562 // the result is the size of the referenced type."
3563 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3564 // result shall be the alignment of the referenced type."
3565 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3566 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003567
3568 // __alignof is defined to return the preferred alignment.
3569 return Info.Ctx.toCharUnitsFromBits(
3570 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003571}
3572
Ken Dyck160146e2010-01-27 17:10:57 +00003573CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003574 E = E->IgnoreParens();
3575
3576 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003577 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003578 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003579 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3580 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003581
Chris Lattner68061312009-01-24 21:53:27 +00003582 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003583 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3584 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003585
Chris Lattner24aeeab2009-01-24 21:09:06 +00003586 return GetAlignOfType(E->getType());
3587}
3588
3589
Peter Collingbournee190dee2011-03-11 19:24:49 +00003590/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3591/// a result as the expression's type.
3592bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3593 const UnaryExprOrTypeTraitExpr *E) {
3594 switch(E->getKind()) {
3595 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003596 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003597 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003598 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003599 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003600 }
Eli Friedman64004332009-03-23 04:38:34 +00003601
Peter Collingbournee190dee2011-03-11 19:24:49 +00003602 case UETT_VecStep: {
3603 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003604
Peter Collingbournee190dee2011-03-11 19:24:49 +00003605 if (Ty->isVectorType()) {
3606 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003607
Peter Collingbournee190dee2011-03-11 19:24:49 +00003608 // The vec_step built-in functions that take a 3-component
3609 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3610 if (n == 3)
3611 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003612
Peter Collingbournee190dee2011-03-11 19:24:49 +00003613 return Success(n, E);
3614 } else
3615 return Success(1, E);
3616 }
3617
3618 case UETT_SizeOf: {
3619 QualType SrcTy = E->getTypeOfArgument();
3620 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3621 // the result is the size of the referenced type."
3622 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3623 // result shall be the alignment of the referenced type."
3624 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3625 SrcTy = Ref->getPointeeType();
3626
Richard Smithd62306a2011-11-10 06:34:14 +00003627 CharUnits Sizeof;
3628 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003629 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003630 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003631 }
3632 }
3633
3634 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003635 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003636}
3637
Peter Collingbournee9200682011-05-13 03:29:01 +00003638bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003639 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003640 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003641 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003642 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003643 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003644 for (unsigned i = 0; i != n; ++i) {
3645 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3646 switch (ON.getKind()) {
3647 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003648 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003649 APSInt IdxResult;
3650 if (!EvaluateInteger(Idx, IdxResult, Info))
3651 return false;
3652 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3653 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003654 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003655 CurrentType = AT->getElementType();
3656 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3657 Result += IdxResult.getSExtValue() * ElementSize;
3658 break;
3659 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003660
Douglas Gregor882211c2010-04-28 22:16:22 +00003661 case OffsetOfExpr::OffsetOfNode::Field: {
3662 FieldDecl *MemberDecl = ON.getField();
3663 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003664 if (!RT)
3665 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003666 RecordDecl *RD = RT->getDecl();
3667 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003668 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003669 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003670 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003671 CurrentType = MemberDecl->getType().getNonReferenceType();
3672 break;
3673 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003674
Douglas Gregor882211c2010-04-28 22:16:22 +00003675 case OffsetOfExpr::OffsetOfNode::Identifier:
3676 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003677 return Error(OOE);
3678
Douglas Gregord1702062010-04-29 00:18:15 +00003679 case OffsetOfExpr::OffsetOfNode::Base: {
3680 CXXBaseSpecifier *BaseSpec = ON.getBase();
3681 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003682 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003683
3684 // Find the layout of the class whose base we are looking into.
3685 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003686 if (!RT)
3687 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003688 RecordDecl *RD = RT->getDecl();
3689 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3690
3691 // Find the base class itself.
3692 CurrentType = BaseSpec->getType();
3693 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3694 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003695 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003696
3697 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003698 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003699 break;
3700 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003701 }
3702 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003703 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003704}
3705
Chris Lattnere13042c2008-07-11 19:10:17 +00003706bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003707 switch (E->getOpcode()) {
3708 default:
3709 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3710 // See C99 6.6p3.
3711 return Error(E);
3712 case UO_Extension:
3713 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3714 // If so, we could clear the diagnostic ID.
3715 return Visit(E->getSubExpr());
3716 case UO_Plus:
3717 // The result is just the value.
3718 return Visit(E->getSubExpr());
3719 case UO_Minus: {
3720 if (!Visit(E->getSubExpr()))
3721 return false;
3722 if (!Result.isInt()) return Error(E);
3723 return Success(-Result.getInt(), E);
3724 }
3725 case UO_Not: {
3726 if (!Visit(E->getSubExpr()))
3727 return false;
3728 if (!Result.isInt()) return Error(E);
3729 return Success(~Result.getInt(), E);
3730 }
3731 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003732 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003733 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003734 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003735 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003736 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003737 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003738}
Mike Stump11289f42009-09-09 15:08:12 +00003739
Chris Lattner477c4be2008-07-12 01:15:53 +00003740/// HandleCast - This is used to evaluate implicit or explicit casts where the
3741/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003742bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3743 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003744 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003745 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003746
Eli Friedmanc757de22011-03-25 00:43:55 +00003747 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003748 case CK_BaseToDerived:
3749 case CK_DerivedToBase:
3750 case CK_UncheckedDerivedToBase:
3751 case CK_Dynamic:
3752 case CK_ToUnion:
3753 case CK_ArrayToPointerDecay:
3754 case CK_FunctionToPointerDecay:
3755 case CK_NullToPointer:
3756 case CK_NullToMemberPointer:
3757 case CK_BaseToDerivedMemberPointer:
3758 case CK_DerivedToBaseMemberPointer:
3759 case CK_ConstructorConversion:
3760 case CK_IntegralToPointer:
3761 case CK_ToVoid:
3762 case CK_VectorSplat:
3763 case CK_IntegralToFloating:
3764 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003765 case CK_CPointerToObjCPointerCast:
3766 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003767 case CK_AnyPointerToBlockPointerCast:
3768 case CK_ObjCObjectLValueCast:
3769 case CK_FloatingRealToComplex:
3770 case CK_FloatingComplexToReal:
3771 case CK_FloatingComplexCast:
3772 case CK_FloatingComplexToIntegralComplex:
3773 case CK_IntegralRealToComplex:
3774 case CK_IntegralComplexCast:
3775 case CK_IntegralComplexToFloatingComplex:
3776 llvm_unreachable("invalid cast kind for integral value");
3777
Eli Friedman9faf2f92011-03-25 19:07:11 +00003778 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003779 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003780 case CK_LValueBitCast:
3781 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00003782 case CK_ARCProduceObject:
3783 case CK_ARCConsumeObject:
3784 case CK_ARCReclaimReturnedObject:
3785 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003786 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003787
3788 case CK_LValueToRValue:
3789 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003790 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003791
3792 case CK_MemberPointerToBoolean:
3793 case CK_PointerToBoolean:
3794 case CK_IntegralToBoolean:
3795 case CK_FloatingToBoolean:
3796 case CK_FloatingComplexToBoolean:
3797 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003798 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00003799 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003800 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003801 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003802 }
3803
Eli Friedmanc757de22011-03-25 00:43:55 +00003804 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00003805 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00003806 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003807
Eli Friedman742421e2009-02-20 01:15:07 +00003808 if (!Result.isInt()) {
3809 // Only allow casts of lvalues if they are lossless.
3810 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3811 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003812
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003813 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003814 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00003815 }
Mike Stump11289f42009-09-09 15:08:12 +00003816
Eli Friedmanc757de22011-03-25 00:43:55 +00003817 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00003818 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00003819 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00003820 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003821
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003822 if (LV.getLValueBase()) {
3823 // Only allow based lvalue casts if they are lossless.
3824 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003825 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003826
Richard Smithcf74da72011-11-16 07:18:12 +00003827 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003828 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003829 return true;
3830 }
3831
Ken Dyck02990832010-01-15 12:37:54 +00003832 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3833 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003834 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003835 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003836
Eli Friedmanc757de22011-03-25 00:43:55 +00003837 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00003838 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003839 if (!EvaluateComplex(SubExpr, C, Info))
3840 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00003841 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003842 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00003843
Eli Friedmanc757de22011-03-25 00:43:55 +00003844 case CK_FloatingToIntegral: {
3845 APFloat F(0.0);
3846 if (!EvaluateFloat(SubExpr, F, Info))
3847 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00003848
Eli Friedmanc757de22011-03-25 00:43:55 +00003849 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3850 }
3851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852
Eli Friedmanc757de22011-03-25 00:43:55 +00003853 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003854 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00003855}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003856
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003857bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3858 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003859 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003860 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3861 return false;
3862 if (!LV.isComplexInt())
3863 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003864 return Success(LV.getComplexIntReal(), E);
3865 }
3866
3867 return Visit(E->getSubExpr());
3868}
3869
Eli Friedman4e7a2412009-02-27 04:45:43 +00003870bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003871 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003872 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003873 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3874 return false;
3875 if (!LV.isComplexInt())
3876 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003877 return Success(LV.getComplexIntImag(), E);
3878 }
3879
Richard Smith4a678122011-10-24 18:44:57 +00003880 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00003881 return Success(0, E);
3882}
3883
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003884bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3885 return Success(E->getPackLength(), E);
3886}
3887
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003888bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3889 return Success(E->getValue(), E);
3890}
3891
Chris Lattner05706e882008-07-11 18:11:29 +00003892//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00003893// Float Evaluation
3894//===----------------------------------------------------------------------===//
3895
3896namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003897class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003898 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00003899 APFloat &Result;
3900public:
3901 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003902 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00003903
Richard Smith0b0a0b62011-10-29 20:57:55 +00003904 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003905 Result = V.getFloat();
3906 return true;
3907 }
Eli Friedman24c01542008-08-22 00:06:13 +00003908
Richard Smith4ce706a2011-10-11 21:43:33 +00003909 bool ValueInitialization(const Expr *E) {
3910 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3911 return true;
3912 }
3913
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003914 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003915
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003916 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003917 bool VisitBinaryOperator(const BinaryOperator *E);
3918 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003919 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00003920
John McCallb1fb0d32010-05-07 22:08:54 +00003921 bool VisitUnaryReal(const UnaryOperator *E);
3922 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00003923
John McCallb1fb0d32010-05-07 22:08:54 +00003924 // FIXME: Missing: array subscript of vector, member of vector,
3925 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00003926};
3927} // end anonymous namespace
3928
3929static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003930 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003931 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00003932}
3933
Jay Foad39c79802011-01-12 09:06:06 +00003934static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00003935 QualType ResultTy,
3936 const Expr *Arg,
3937 bool SNaN,
3938 llvm::APFloat &Result) {
3939 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3940 if (!S) return false;
3941
3942 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3943
3944 llvm::APInt fill;
3945
3946 // Treat empty strings as if they were zero.
3947 if (S->getString().empty())
3948 fill = llvm::APInt(32, 0);
3949 else if (S->getString().getAsInteger(0, fill))
3950 return false;
3951
3952 if (SNaN)
3953 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3954 else
3955 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3956 return true;
3957}
3958
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003959bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003960 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003961 default:
3962 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3963
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003964 case Builtin::BI__builtin_huge_val:
3965 case Builtin::BI__builtin_huge_valf:
3966 case Builtin::BI__builtin_huge_vall:
3967 case Builtin::BI__builtin_inf:
3968 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003969 case Builtin::BI__builtin_infl: {
3970 const llvm::fltSemantics &Sem =
3971 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00003972 Result = llvm::APFloat::getInf(Sem);
3973 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003974 }
Mike Stump11289f42009-09-09 15:08:12 +00003975
John McCall16291492010-02-28 13:00:19 +00003976 case Builtin::BI__builtin_nans:
3977 case Builtin::BI__builtin_nansf:
3978 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003979 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3980 true, Result))
3981 return Error(E);
3982 return true;
John McCall16291492010-02-28 13:00:19 +00003983
Chris Lattner0b7282e2008-10-06 06:31:58 +00003984 case Builtin::BI__builtin_nan:
3985 case Builtin::BI__builtin_nanf:
3986 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00003987 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00003988 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003989 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3990 false, Result))
3991 return Error(E);
3992 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003993
3994 case Builtin::BI__builtin_fabs:
3995 case Builtin::BI__builtin_fabsf:
3996 case Builtin::BI__builtin_fabsl:
3997 if (!EvaluateFloat(E->getArg(0), Result, Info))
3998 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003999
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004000 if (Result.isNegative())
4001 Result.changeSign();
4002 return true;
4003
Mike Stump11289f42009-09-09 15:08:12 +00004004 case Builtin::BI__builtin_copysign:
4005 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004006 case Builtin::BI__builtin_copysignl: {
4007 APFloat RHS(0.);
4008 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4009 !EvaluateFloat(E->getArg(1), RHS, Info))
4010 return false;
4011 Result.copySign(RHS);
4012 return true;
4013 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004014 }
4015}
4016
John McCallb1fb0d32010-05-07 22:08:54 +00004017bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004018 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4019 ComplexValue CV;
4020 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4021 return false;
4022 Result = CV.FloatReal;
4023 return true;
4024 }
4025
4026 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004027}
4028
4029bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004030 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4031 ComplexValue CV;
4032 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4033 return false;
4034 Result = CV.FloatImag;
4035 return true;
4036 }
4037
Richard Smith4a678122011-10-24 18:44:57 +00004038 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004039 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4040 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004041 return true;
4042}
4043
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004044bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004045 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004046 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004047 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004048 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004049 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004050 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4051 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004052 Result.changeSign();
4053 return true;
4054 }
4055}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004056
Eli Friedman24c01542008-08-22 00:06:13 +00004057bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004058 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4059 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004060
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004061 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004062 if (!EvaluateFloat(E->getLHS(), Result, Info))
4063 return false;
4064 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4065 return false;
4066
4067 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004068 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004069 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004070 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4071 return true;
John McCalle3027922010-08-25 11:45:40 +00004072 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004073 Result.add(RHS, APFloat::rmNearestTiesToEven);
4074 return true;
John McCalle3027922010-08-25 11:45:40 +00004075 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004076 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4077 return true;
John McCalle3027922010-08-25 11:45:40 +00004078 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004079 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4080 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004081 }
4082}
4083
4084bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4085 Result = E->getValue();
4086 return true;
4087}
4088
Peter Collingbournee9200682011-05-13 03:29:01 +00004089bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4090 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004091
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004092 switch (E->getCastKind()) {
4093 default:
Richard Smith11562c52011-10-28 17:51:58 +00004094 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004095
4096 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004097 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004098 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004099 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004100 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004101 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004102 return true;
4103 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004104
4105 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004106 if (!Visit(SubExpr))
4107 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004108 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
4109 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004110 return true;
4111 }
John McCalld7646252010-11-14 08:17:51 +00004112
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004113 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004114 ComplexValue V;
4115 if (!EvaluateComplex(SubExpr, V, Info))
4116 return false;
4117 Result = V.getComplexFloatReal();
4118 return true;
4119 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004120 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004121
Richard Smithf57d8cb2011-12-09 22:58:01 +00004122 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004123}
4124
Eli Friedman24c01542008-08-22 00:06:13 +00004125//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004126// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004127//===----------------------------------------------------------------------===//
4128
4129namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004130class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004131 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004132 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004133
Anders Carlsson537969c2008-11-16 20:27:53 +00004134public:
John McCall93d91dc2010-05-07 17:22:02 +00004135 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004136 : ExprEvaluatorBaseTy(info), Result(Result) {}
4137
Richard Smith0b0a0b62011-10-29 20:57:55 +00004138 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004139 Result.setFrom(V);
4140 return true;
4141 }
Mike Stump11289f42009-09-09 15:08:12 +00004142
Anders Carlsson537969c2008-11-16 20:27:53 +00004143 //===--------------------------------------------------------------------===//
4144 // Visitor Methods
4145 //===--------------------------------------------------------------------===//
4146
Peter Collingbournee9200682011-05-13 03:29:01 +00004147 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004148
Peter Collingbournee9200682011-05-13 03:29:01 +00004149 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004150
John McCall93d91dc2010-05-07 17:22:02 +00004151 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004152 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004153 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004154};
4155} // end anonymous namespace
4156
John McCall93d91dc2010-05-07 17:22:02 +00004157static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4158 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004159 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004160 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004161}
4162
Peter Collingbournee9200682011-05-13 03:29:01 +00004163bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4164 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004165
4166 if (SubExpr->getType()->isRealFloatingType()) {
4167 Result.makeComplexFloat();
4168 APFloat &Imag = Result.FloatImag;
4169 if (!EvaluateFloat(SubExpr, Imag, Info))
4170 return false;
4171
4172 Result.FloatReal = APFloat(Imag.getSemantics());
4173 return true;
4174 } else {
4175 assert(SubExpr->getType()->isIntegerType() &&
4176 "Unexpected imaginary literal.");
4177
4178 Result.makeComplexInt();
4179 APSInt &Imag = Result.IntImag;
4180 if (!EvaluateInteger(SubExpr, Imag, Info))
4181 return false;
4182
4183 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4184 return true;
4185 }
4186}
4187
Peter Collingbournee9200682011-05-13 03:29:01 +00004188bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004189
John McCallfcef3cf2010-12-14 17:51:41 +00004190 switch (E->getCastKind()) {
4191 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004192 case CK_BaseToDerived:
4193 case CK_DerivedToBase:
4194 case CK_UncheckedDerivedToBase:
4195 case CK_Dynamic:
4196 case CK_ToUnion:
4197 case CK_ArrayToPointerDecay:
4198 case CK_FunctionToPointerDecay:
4199 case CK_NullToPointer:
4200 case CK_NullToMemberPointer:
4201 case CK_BaseToDerivedMemberPointer:
4202 case CK_DerivedToBaseMemberPointer:
4203 case CK_MemberPointerToBoolean:
4204 case CK_ConstructorConversion:
4205 case CK_IntegralToPointer:
4206 case CK_PointerToIntegral:
4207 case CK_PointerToBoolean:
4208 case CK_ToVoid:
4209 case CK_VectorSplat:
4210 case CK_IntegralCast:
4211 case CK_IntegralToBoolean:
4212 case CK_IntegralToFloating:
4213 case CK_FloatingToIntegral:
4214 case CK_FloatingToBoolean:
4215 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004216 case CK_CPointerToObjCPointerCast:
4217 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004218 case CK_AnyPointerToBlockPointerCast:
4219 case CK_ObjCObjectLValueCast:
4220 case CK_FloatingComplexToReal:
4221 case CK_FloatingComplexToBoolean:
4222 case CK_IntegralComplexToReal:
4223 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004224 case CK_ARCProduceObject:
4225 case CK_ARCConsumeObject:
4226 case CK_ARCReclaimReturnedObject:
4227 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004228 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004229
John McCallfcef3cf2010-12-14 17:51:41 +00004230 case CK_LValueToRValue:
4231 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004232 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004233
4234 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004235 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004236 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004237 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004238
4239 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004240 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004241 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004242 return false;
4243
John McCallfcef3cf2010-12-14 17:51:41 +00004244 Result.makeComplexFloat();
4245 Result.FloatImag = APFloat(Real.getSemantics());
4246 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004247 }
4248
John McCallfcef3cf2010-12-14 17:51:41 +00004249 case CK_FloatingComplexCast: {
4250 if (!Visit(E->getSubExpr()))
4251 return false;
4252
4253 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4254 QualType From
4255 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4256
4257 Result.FloatReal
4258 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
4259 Result.FloatImag
4260 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
4261 return true;
4262 }
4263
4264 case CK_FloatingComplexToIntegralComplex: {
4265 if (!Visit(E->getSubExpr()))
4266 return false;
4267
4268 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4269 QualType From
4270 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4271 Result.makeComplexInt();
4272 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
4273 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
4274 return true;
4275 }
4276
4277 case CK_IntegralRealToComplex: {
4278 APSInt &Real = Result.IntReal;
4279 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4280 return false;
4281
4282 Result.makeComplexInt();
4283 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4284 return true;
4285 }
4286
4287 case CK_IntegralComplexCast: {
4288 if (!Visit(E->getSubExpr()))
4289 return false;
4290
4291 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4292 QualType From
4293 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4294
4295 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4296 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4297 return true;
4298 }
4299
4300 case CK_IntegralComplexToFloatingComplex: {
4301 if (!Visit(E->getSubExpr()))
4302 return false;
4303
4304 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4305 QualType From
4306 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4307 Result.makeComplexFloat();
4308 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
4309 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
4310 return true;
4311 }
4312 }
4313
4314 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004315 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004316}
4317
John McCall93d91dc2010-05-07 17:22:02 +00004318bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004319 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004320 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4321
John McCall93d91dc2010-05-07 17:22:02 +00004322 if (!Visit(E->getLHS()))
4323 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004324
John McCall93d91dc2010-05-07 17:22:02 +00004325 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004326 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004327 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004328
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004329 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4330 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004331 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004332 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004333 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004334 if (Result.isComplexFloat()) {
4335 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4336 APFloat::rmNearestTiesToEven);
4337 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4338 APFloat::rmNearestTiesToEven);
4339 } else {
4340 Result.getComplexIntReal() += RHS.getComplexIntReal();
4341 Result.getComplexIntImag() += RHS.getComplexIntImag();
4342 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004343 break;
John McCalle3027922010-08-25 11:45:40 +00004344 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004345 if (Result.isComplexFloat()) {
4346 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4347 APFloat::rmNearestTiesToEven);
4348 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4349 APFloat::rmNearestTiesToEven);
4350 } else {
4351 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4352 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4353 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004354 break;
John McCalle3027922010-08-25 11:45:40 +00004355 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004356 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004357 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004358 APFloat &LHS_r = LHS.getComplexFloatReal();
4359 APFloat &LHS_i = LHS.getComplexFloatImag();
4360 APFloat &RHS_r = RHS.getComplexFloatReal();
4361 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004362
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004363 APFloat Tmp = LHS_r;
4364 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4365 Result.getComplexFloatReal() = Tmp;
4366 Tmp = LHS_i;
4367 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4368 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4369
4370 Tmp = LHS_r;
4371 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4372 Result.getComplexFloatImag() = Tmp;
4373 Tmp = LHS_i;
4374 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4375 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4376 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004377 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004378 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004379 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4380 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004381 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004382 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4383 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4384 }
4385 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004386 case BO_Div:
4387 if (Result.isComplexFloat()) {
4388 ComplexValue LHS = Result;
4389 APFloat &LHS_r = LHS.getComplexFloatReal();
4390 APFloat &LHS_i = LHS.getComplexFloatImag();
4391 APFloat &RHS_r = RHS.getComplexFloatReal();
4392 APFloat &RHS_i = RHS.getComplexFloatImag();
4393 APFloat &Res_r = Result.getComplexFloatReal();
4394 APFloat &Res_i = Result.getComplexFloatImag();
4395
4396 APFloat Den = RHS_r;
4397 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4398 APFloat Tmp = RHS_i;
4399 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4400 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4401
4402 Res_r = LHS_r;
4403 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4404 Tmp = LHS_i;
4405 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4406 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4407 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4408
4409 Res_i = LHS_i;
4410 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4411 Tmp = LHS_r;
4412 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4413 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4414 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4415 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004416 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4417 return Error(E, diag::note_expr_divide_by_zero);
4418
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004419 ComplexValue LHS = Result;
4420 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4421 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4422 Result.getComplexIntReal() =
4423 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4424 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4425 Result.getComplexIntImag() =
4426 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4427 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4428 }
4429 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004430 }
4431
John McCall93d91dc2010-05-07 17:22:02 +00004432 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004433}
4434
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004435bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4436 // Get the operand value into 'Result'.
4437 if (!Visit(E->getSubExpr()))
4438 return false;
4439
4440 switch (E->getOpcode()) {
4441 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004442 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004443 case UO_Extension:
4444 return true;
4445 case UO_Plus:
4446 // The result is always just the subexpr.
4447 return true;
4448 case UO_Minus:
4449 if (Result.isComplexFloat()) {
4450 Result.getComplexFloatReal().changeSign();
4451 Result.getComplexFloatImag().changeSign();
4452 }
4453 else {
4454 Result.getComplexIntReal() = -Result.getComplexIntReal();
4455 Result.getComplexIntImag() = -Result.getComplexIntImag();
4456 }
4457 return true;
4458 case UO_Not:
4459 if (Result.isComplexFloat())
4460 Result.getComplexFloatImag().changeSign();
4461 else
4462 Result.getComplexIntImag() = -Result.getComplexIntImag();
4463 return true;
4464 }
4465}
4466
Anders Carlsson537969c2008-11-16 20:27:53 +00004467//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004468// Void expression evaluation, primarily for a cast to void on the LHS of a
4469// comma operator
4470//===----------------------------------------------------------------------===//
4471
4472namespace {
4473class VoidExprEvaluator
4474 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4475public:
4476 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4477
4478 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004479
4480 bool VisitCastExpr(const CastExpr *E) {
4481 switch (E->getCastKind()) {
4482 default:
4483 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4484 case CK_ToVoid:
4485 VisitIgnoredValue(E->getSubExpr());
4486 return true;
4487 }
4488 }
4489};
4490} // end anonymous namespace
4491
4492static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4493 assert(E->isRValue() && E->getType()->isVoidType());
4494 return VoidExprEvaluator(Info).Visit(E);
4495}
4496
4497//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004498// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004499//===----------------------------------------------------------------------===//
4500
Richard Smith0b0a0b62011-10-29 20:57:55 +00004501static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004502 // In C, function designators are not lvalues, but we evaluate them as if they
4503 // are.
4504 if (E->isGLValue() || E->getType()->isFunctionType()) {
4505 LValue LV;
4506 if (!EvaluateLValue(E, LV, Info))
4507 return false;
4508 LV.moveInto(Result);
4509 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004510 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004511 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004512 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004513 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004514 return false;
John McCall45d55e42010-05-07 21:00:08 +00004515 } else if (E->getType()->hasPointerRepresentation()) {
4516 LValue LV;
4517 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004518 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004519 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004520 } else if (E->getType()->isRealFloatingType()) {
4521 llvm::APFloat F(0.0);
4522 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004523 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004524 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004525 } else if (E->getType()->isAnyComplexType()) {
4526 ComplexValue C;
4527 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004528 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004529 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004530 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004531 MemberPtr P;
4532 if (!EvaluateMemberPointer(E, P, Info))
4533 return false;
4534 P.moveInto(Result);
4535 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004536 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004537 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004538 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004539 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004540 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004541 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004542 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004543 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004544 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004545 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4546 return false;
4547 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004548 } else if (E->getType()->isVoidType()) {
4549 if (!EvaluateVoid(E, Info))
4550 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004551 } else {
4552 Info.Diag(E, E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004553 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004554 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004555
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004556 return true;
4557}
4558
Richard Smithed5165f2011-11-04 05:33:44 +00004559/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4560/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4561/// since later initializers for an object can indirectly refer to subobjects
4562/// which were initialized earlier.
4563static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00004564 const LValue &This, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004565 if (E->isRValue() && E->getType()->isLiteralType()) {
4566 // Evaluate arrays and record types in-place, so that later initializers can
4567 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004568 if (E->getType()->isArrayType())
4569 return EvaluateArray(E, This, Result, Info);
4570 else if (E->getType()->isRecordType())
4571 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004572 }
4573
4574 // For any other type, in-place evaluation is unimportant.
4575 CCValue CoreConstResult;
4576 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004577 CheckConstantExpression(Info, E, CoreConstResult, Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004578}
4579
Richard Smithf57d8cb2011-12-09 22:58:01 +00004580/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4581/// lvalue-to-rvalue cast if it is an lvalue.
4582static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4583 CCValue Value;
4584 if (!::Evaluate(Value, Info, E))
4585 return false;
4586
4587 if (E->isGLValue()) {
4588 LValue LV;
4589 LV.setFrom(Value);
4590 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4591 return false;
4592 }
4593
4594 // Check this core constant expression is a constant expression, and if so,
4595 // convert it to one.
4596 return CheckConstantExpression(Info, E, Value, Result);
4597}
Richard Smith11562c52011-10-28 17:51:58 +00004598
Richard Smith7b553f12011-10-29 00:50:52 +00004599/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004600/// any crazy technique (that has nothing to do with language standards) that
4601/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004602/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4603/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004604bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004605 // Fast-path evaluations of integer literals, since we sometimes see files
4606 // containing vast quantities of these.
4607 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4608 Result.Val = APValue(APSInt(L->getValue(),
4609 L->getType()->isUnsignedIntegerType()));
4610 return true;
4611 }
4612
Richard Smith5686e752011-11-10 03:30:42 +00004613 // FIXME: Evaluating initializers for large arrays can cause performance
4614 // problems, and we don't use such values yet. Once we have a more efficient
4615 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004616 // The same problem affects large records.
4617 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4618 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004619 return false;
4620
Richard Smithd62306a2011-11-10 06:34:14 +00004621 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 EvalInfo Info(Ctx, Result);
4623 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004624}
4625
Jay Foad39c79802011-01-12 09:06:06 +00004626bool Expr::EvaluateAsBooleanCondition(bool &Result,
4627 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004628 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004629 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004630 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004631 Result);
John McCall1be1c632010-01-05 23:42:56 +00004632}
4633
Richard Smithcaf33902011-10-10 18:28:20 +00004634bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004635 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004636 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004637 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004638 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004639
Richard Smith11562c52011-10-28 17:51:58 +00004640 Result = ExprResult.Val.getInt();
4641 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004642}
4643
Jay Foad39c79802011-01-12 09:06:06 +00004644bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004645 EvalInfo Info(Ctx, Result);
4646
John McCall45d55e42010-05-07 21:00:08 +00004647 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004648 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004649 CheckLValueConstantExpression(Info, this, LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00004650}
4651
Richard Smith7b553f12011-10-29 00:50:52 +00004652/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4653/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004654bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004655 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004656 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004657}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004658
Jay Foad39c79802011-01-12 09:06:06 +00004659bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004660 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004661}
4662
Richard Smithcaf33902011-10-10 18:28:20 +00004663APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004664 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004665 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004666 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004667 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004668 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004669
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004670 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004671}
John McCall864e3962010-05-07 05:32:02 +00004672
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004673 bool Expr::EvalResult::isGlobalLValue() const {
4674 assert(Val.isLValue());
4675 return IsGlobalLValue(Val.getLValueBase());
4676 }
4677
4678
John McCall864e3962010-05-07 05:32:02 +00004679/// isIntegerConstantExpr - this recursive routine will test if an expression is
4680/// an integer constant expression.
4681
4682/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4683/// comma, etc
4684///
4685/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4686/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4687/// cast+dereference.
4688
4689// CheckICE - This function does the fundamental ICE checking: the returned
4690// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4691// Note that to reduce code duplication, this helper does no evaluation
4692// itself; the caller checks whether the expression is evaluatable, and
4693// in the rare cases where CheckICE actually cares about the evaluated
4694// value, it calls into Evalute.
4695//
4696// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004697// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004698// 1: This expression is not an ICE, but if it isn't evaluated, it's
4699// a legal subexpression for an ICE. This return value is used to handle
4700// the comma operator in C99 mode.
4701// 2: This expression is not an ICE, and is not a legal subexpression for one.
4702
Dan Gohman28ade552010-07-26 21:25:24 +00004703namespace {
4704
John McCall864e3962010-05-07 05:32:02 +00004705struct ICEDiag {
4706 unsigned Val;
4707 SourceLocation Loc;
4708
4709 public:
4710 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4711 ICEDiag() : Val(0) {}
4712};
4713
Dan Gohman28ade552010-07-26 21:25:24 +00004714}
4715
4716static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004717
4718static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4719 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004720 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004721 !EVResult.Val.isInt()) {
4722 return ICEDiag(2, E->getLocStart());
4723 }
4724 return NoDiag();
4725}
4726
4727static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4728 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004729 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004730 return ICEDiag(2, E->getLocStart());
4731 }
4732
4733 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004734#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004735#define STMT(Node, Base) case Expr::Node##Class:
4736#define EXPR(Node, Base)
4737#include "clang/AST/StmtNodes.inc"
4738 case Expr::PredefinedExprClass:
4739 case Expr::FloatingLiteralClass:
4740 case Expr::ImaginaryLiteralClass:
4741 case Expr::StringLiteralClass:
4742 case Expr::ArraySubscriptExprClass:
4743 case Expr::MemberExprClass:
4744 case Expr::CompoundAssignOperatorClass:
4745 case Expr::CompoundLiteralExprClass:
4746 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004747 case Expr::DesignatedInitExprClass:
4748 case Expr::ImplicitValueInitExprClass:
4749 case Expr::ParenListExprClass:
4750 case Expr::VAArgExprClass:
4751 case Expr::AddrLabelExprClass:
4752 case Expr::StmtExprClass:
4753 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00004754 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00004755 case Expr::CXXDynamicCastExprClass:
4756 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00004757 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00004758 case Expr::CXXNullPtrLiteralExprClass:
4759 case Expr::CXXThisExprClass:
4760 case Expr::CXXThrowExprClass:
4761 case Expr::CXXNewExprClass:
4762 case Expr::CXXDeleteExprClass:
4763 case Expr::CXXPseudoDestructorExprClass:
4764 case Expr::UnresolvedLookupExprClass:
4765 case Expr::DependentScopeDeclRefExprClass:
4766 case Expr::CXXConstructExprClass:
4767 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00004768 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00004769 case Expr::CXXTemporaryObjectExprClass:
4770 case Expr::CXXUnresolvedConstructExprClass:
4771 case Expr::CXXDependentScopeMemberExprClass:
4772 case Expr::UnresolvedMemberExprClass:
4773 case Expr::ObjCStringLiteralClass:
4774 case Expr::ObjCEncodeExprClass:
4775 case Expr::ObjCMessageExprClass:
4776 case Expr::ObjCSelectorExprClass:
4777 case Expr::ObjCProtocolExprClass:
4778 case Expr::ObjCIvarRefExprClass:
4779 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00004780 case Expr::ObjCIsaExprClass:
4781 case Expr::ShuffleVectorExprClass:
4782 case Expr::BlockExprClass:
4783 case Expr::BlockDeclRefExprClass:
4784 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00004785 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004786 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00004787 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00004788 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00004789 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00004790 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00004791 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004792 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004793 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004794 return ICEDiag(2, E->getLocStart());
4795
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004796 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00004797 case Expr::GNUNullExprClass:
4798 // GCC considers the GNU __null value to be an integral constant expression.
4799 return NoDiag();
4800
John McCall7c454bb2011-07-15 05:09:51 +00004801 case Expr::SubstNonTypeTemplateParmExprClass:
4802 return
4803 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4804
John McCall864e3962010-05-07 05:32:02 +00004805 case Expr::ParenExprClass:
4806 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00004807 case Expr::GenericSelectionExprClass:
4808 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004809 case Expr::IntegerLiteralClass:
4810 case Expr::CharacterLiteralClass:
4811 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00004812 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00004813 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004814 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00004815 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00004816 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004817 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00004818 return NoDiag();
4819 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00004820 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00004821 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4822 // constant expressions, but they can never be ICEs because an ICE cannot
4823 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00004824 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004825 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00004826 return CheckEvalInICE(E, Ctx);
4827 return ICEDiag(2, E->getLocStart());
4828 }
4829 case Expr::DeclRefExprClass:
4830 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4831 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00004832 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00004833 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4834
4835 // Parameter variables are never constants. Without this check,
4836 // getAnyInitializer() can find a default argument, which leads
4837 // to chaos.
4838 if (isa<ParmVarDecl>(D))
4839 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4840
4841 // C++ 7.1.5.1p2
4842 // A variable of non-volatile const-qualified integral or enumeration
4843 // type initialized by an ICE can be used in ICEs.
4844 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00004845 if (!Dcl->getType()->isIntegralOrEnumerationType())
4846 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4847
John McCall864e3962010-05-07 05:32:02 +00004848 // Look for a declaration of this variable that has an initializer.
4849 const VarDecl *ID = 0;
4850 const Expr *Init = Dcl->getAnyInitializer(ID);
4851 if (Init) {
4852 if (ID->isInitKnownICE()) {
4853 // We have already checked whether this subexpression is an
4854 // integral constant expression.
4855 if (ID->isInitICE())
4856 return NoDiag();
4857 else
4858 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4859 }
4860
4861 // It's an ICE whether or not the definition we found is
4862 // out-of-line. See DR 721 and the discussion in Clang PR
4863 // 6206 for details.
4864
4865 if (Dcl->isCheckingICE()) {
4866 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4867 }
4868
4869 Dcl->setCheckingICE();
4870 ICEDiag Result = CheckICE(Init, Ctx);
4871 // Cache the result of the ICE test.
4872 Dcl->setInitKnownICE(Result.Val == 0);
4873 return Result;
4874 }
4875 }
4876 }
4877 return ICEDiag(2, E->getLocStart());
4878 case Expr::UnaryOperatorClass: {
4879 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4880 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004881 case UO_PostInc:
4882 case UO_PostDec:
4883 case UO_PreInc:
4884 case UO_PreDec:
4885 case UO_AddrOf:
4886 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00004887 // C99 6.6/3 allows increment and decrement within unevaluated
4888 // subexpressions of constant expressions, but they can never be ICEs
4889 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004890 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00004891 case UO_Extension:
4892 case UO_LNot:
4893 case UO_Plus:
4894 case UO_Minus:
4895 case UO_Not:
4896 case UO_Real:
4897 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00004898 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004899 }
4900
4901 // OffsetOf falls through here.
4902 }
4903 case Expr::OffsetOfExprClass: {
4904 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00004905 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00004906 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00004907 // compliance: we should warn earlier for offsetof expressions with
4908 // array subscripts that aren't ICEs, and if the array subscripts
4909 // are ICEs, the value of the offsetof must be an integer constant.
4910 return CheckEvalInICE(E, Ctx);
4911 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00004912 case Expr::UnaryExprOrTypeTraitExprClass: {
4913 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4914 if ((Exp->getKind() == UETT_SizeOf) &&
4915 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00004916 return ICEDiag(2, E->getLocStart());
4917 return NoDiag();
4918 }
4919 case Expr::BinaryOperatorClass: {
4920 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4921 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004922 case BO_PtrMemD:
4923 case BO_PtrMemI:
4924 case BO_Assign:
4925 case BO_MulAssign:
4926 case BO_DivAssign:
4927 case BO_RemAssign:
4928 case BO_AddAssign:
4929 case BO_SubAssign:
4930 case BO_ShlAssign:
4931 case BO_ShrAssign:
4932 case BO_AndAssign:
4933 case BO_XorAssign:
4934 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00004935 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4936 // constant expressions, but they can never be ICEs because an ICE cannot
4937 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004938 return ICEDiag(2, E->getLocStart());
4939
John McCalle3027922010-08-25 11:45:40 +00004940 case BO_Mul:
4941 case BO_Div:
4942 case BO_Rem:
4943 case BO_Add:
4944 case BO_Sub:
4945 case BO_Shl:
4946 case BO_Shr:
4947 case BO_LT:
4948 case BO_GT:
4949 case BO_LE:
4950 case BO_GE:
4951 case BO_EQ:
4952 case BO_NE:
4953 case BO_And:
4954 case BO_Xor:
4955 case BO_Or:
4956 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00004957 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4958 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00004959 if (Exp->getOpcode() == BO_Div ||
4960 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00004961 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00004962 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00004963 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00004964 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004965 if (REval == 0)
4966 return ICEDiag(1, E->getLocStart());
4967 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00004968 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004969 if (LEval.isMinSignedValue())
4970 return ICEDiag(1, E->getLocStart());
4971 }
4972 }
4973 }
John McCalle3027922010-08-25 11:45:40 +00004974 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00004975 if (Ctx.getLangOptions().C99) {
4976 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4977 // if it isn't evaluated.
4978 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4979 return ICEDiag(1, E->getLocStart());
4980 } else {
4981 // In both C89 and C++, commas in ICEs are illegal.
4982 return ICEDiag(2, E->getLocStart());
4983 }
4984 }
4985 if (LHSResult.Val >= RHSResult.Val)
4986 return LHSResult;
4987 return RHSResult;
4988 }
John McCalle3027922010-08-25 11:45:40 +00004989 case BO_LAnd:
4990 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00004991 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4992 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4993 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4994 // Rare case where the RHS has a comma "side-effect"; we need
4995 // to actually check the condition to see whether the side
4996 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00004997 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00004998 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00004999 return RHSResult;
5000 return NoDiag();
5001 }
5002
5003 if (LHSResult.Val >= RHSResult.Val)
5004 return LHSResult;
5005 return RHSResult;
5006 }
5007 }
5008 }
5009 case Expr::ImplicitCastExprClass:
5010 case Expr::CStyleCastExprClass:
5011 case Expr::CXXFunctionalCastExprClass:
5012 case Expr::CXXStaticCastExprClass:
5013 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005014 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005015 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005016 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00005017 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00005018 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5019 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00005020 switch (cast<CastExpr>(E)->getCastKind()) {
5021 case CK_LValueToRValue:
5022 case CK_NoOp:
5023 case CK_IntegralToBoolean:
5024 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005025 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005026 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005027 return ICEDiag(2, E->getLocStart());
5028 }
John McCall864e3962010-05-07 05:32:02 +00005029 }
John McCallc07a0c72011-02-17 10:25:35 +00005030 case Expr::BinaryConditionalOperatorClass: {
5031 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5032 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5033 if (CommonResult.Val == 2) return CommonResult;
5034 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5035 if (FalseResult.Val == 2) return FalseResult;
5036 if (CommonResult.Val == 1) return CommonResult;
5037 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005038 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005039 return FalseResult;
5040 }
John McCall864e3962010-05-07 05:32:02 +00005041 case Expr::ConditionalOperatorClass: {
5042 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5043 // If the condition (ignoring parens) is a __builtin_constant_p call,
5044 // then only the true side is actually considered in an integer constant
5045 // expression, and it is fully evaluated. This is an important GNU
5046 // extension. See GCC PR38377 for discussion.
5047 if (const CallExpr *CallCE
5048 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005049 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005050 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005051 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005052 !EVResult.Val.isInt()) {
5053 return ICEDiag(2, E->getLocStart());
5054 }
5055 return NoDiag();
5056 }
5057 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005058 if (CondResult.Val == 2)
5059 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005060
Richard Smithf57d8cb2011-12-09 22:58:01 +00005061 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5062 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005063
John McCall864e3962010-05-07 05:32:02 +00005064 if (TrueResult.Val == 2)
5065 return TrueResult;
5066 if (FalseResult.Val == 2)
5067 return FalseResult;
5068 if (CondResult.Val == 1)
5069 return CondResult;
5070 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5071 return NoDiag();
5072 // Rare case where the diagnostics depend on which side is evaluated
5073 // Note that if we get here, CondResult is 0, and at least one of
5074 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005075 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005076 return FalseResult;
5077 }
5078 return TrueResult;
5079 }
5080 case Expr::CXXDefaultArgExprClass:
5081 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5082 case Expr::ChooseExprClass: {
5083 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5084 }
5085 }
5086
5087 // Silence a GCC warning
5088 return ICEDiag(2, E->getLocStart());
5089}
5090
Richard Smithf57d8cb2011-12-09 22:58:01 +00005091/// Evaluate an expression as a C++11 constant expression.
5092static bool EvaluateCPlusPlus11ConstantExpression(ASTContext &Ctx,
5093 const Expr *E,
5094 Expr::EvalResult &Result) {
5095 EvalInfo Info(Ctx, Result);
5096 return EvaluateAsRValue(Info, E, Result.Val) && !Result.Diag;
5097}
5098
5099/// Evaluate an expression as a C++11 integral constant expression.
5100static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5101 const Expr *E,
5102 llvm::APSInt *Value,
5103 SourceLocation *Loc) {
5104 if (!E->getType()->isIntegralOrEnumerationType()) {
5105 if (Loc) *Loc = E->getExprLoc();
5106 return false;
5107 }
5108
5109 Expr::EvalResult Result;
5110 if (EvaluateCPlusPlus11ConstantExpression(Ctx, E, Result)) {
5111 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5112 if (Value) *Value = Result.Val.getInt();
5113 return true;
5114 } else {
5115 if (Loc) *Loc = Result.DiagLoc.isValid() ? Result.DiagLoc : E->getExprLoc();
5116 return false;
5117 }
5118}
5119
5120bool Expr::isIntegerConstantExpr(ASTContext &Ctx,
5121 SourceLocation *Loc) const {
5122 if (Ctx.getLangOptions().CPlusPlus0x)
5123 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5124
John McCall864e3962010-05-07 05:32:02 +00005125 ICEDiag d = CheckICE(this, Ctx);
5126 if (d.Val != 0) {
5127 if (Loc) *Loc = d.Loc;
5128 return false;
5129 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005130 return true;
5131}
5132
5133bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5134 SourceLocation *Loc, bool isEvaluated) const {
5135 if (Ctx.getLangOptions().CPlusPlus0x)
5136 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5137
5138 if (!isIntegerConstantExpr(Ctx, Loc))
5139 return false;
5140 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005141 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005142 return true;
5143}