blob: 1bf1693b222e665d8ad4299814c41cf5655bfdf0 [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 Smith92b1ce02011-12-12 09:28:41 +0000251 /// A partial diagnostic which we might know in advance that we are not going
252 /// to emit.
253 class OptionalDiagnostic {
254 PartialDiagnostic *Diag;
255
256 public:
257 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
258
259 template<typename T>
260 OptionalDiagnostic &operator<<(const T &v) {
261 if (Diag)
262 *Diag << v;
263 return *this;
264 }
265 };
266
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000267 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000268 ASTContext &Ctx;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000269
270 /// EvalStatus - Contains information about the evaluation.
271 Expr::EvalStatus &EvalStatus;
272
273 /// CurrentCall - The top of the constexpr call stack.
274 CallStackFrame *CurrentCall;
275
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000276 /// CallStackDepth - The number of calls in the call stack right now.
277 unsigned CallStackDepth;
278
279 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
280 /// OpaqueValues - Values used as the common expression in a
281 /// BinaryConditionalOperator.
282 MapTy OpaqueValues;
283
284 /// BottomFrame - The frame in which evaluation started. This must be
285 /// initialized last.
286 CallStackFrame BottomFrame;
287
Richard Smithd62306a2011-11-10 06:34:14 +0000288 /// EvaluatingDecl - This is the declaration whose initializer is being
289 /// evaluated, if any.
290 const VarDecl *EvaluatingDecl;
291
292 /// EvaluatingDeclValue - This is the value being constructed for the
293 /// declaration whose initializer is being evaluated, if any.
294 APValue *EvaluatingDeclValue;
295
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000296
297 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smith92b1ce02011-12-12 09:28:41 +0000298 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
299 CallStackDepth(0), BottomFrame(*this, 0, 0), EvaluatingDecl(0),
300 EvaluatingDeclValue(0) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000302 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
303 MapTy::const_iterator i = OpaqueValues.find(e);
304 if (i == OpaqueValues.end()) return 0;
305 return &i->second;
306 }
307
Richard Smithd62306a2011-11-10 06:34:14 +0000308 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
309 EvaluatingDecl = VD;
310 EvaluatingDeclValue = &Value;
311 }
312
Richard Smith9a568822011-11-21 19:36:32 +0000313 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
314
315 bool atCallLimit() const {
316 return CallStackDepth > getLangOpts().ConstexprCallDepth;
317 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000318
Richard Smithf57d8cb2011-12-09 22:58:01 +0000319 /// Diagnose that the evaluation cannot be folded.
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000321 // If we have a prior diagnostic, it will be noting that the expression
322 // isn't a constant expression. This diagnostic is more important.
323 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000324 if (EvalStatus.Diag) {
325 EvalStatus.Diag->clear();
326 EvalStatus.Diag->reserve(1);
327 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
328 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
329 // FIXME: Add a call stack for constexpr evaluation.
330 return OptionalDiagnostic(&EvalStatus.Diag->back().second);
331 }
332 return OptionalDiagnostic();
333 }
334
335 /// Diagnose that the evaluation does not produce a C++11 core constant
336 /// expression.
337 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId) {
338 // Don't override a previous diagnostic.
339 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
340 return OptionalDiagnostic();
341 return Diag(Loc, DiagId);
Richard Smithf57d8cb2011-12-09 22:58:01 +0000342 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000343 };
344
Richard Smithd62306a2011-11-10 06:34:14 +0000345 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
346 const CCValue *Arguments)
347 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000348 Info.CurrentCall = this;
349 ++Info.CallStackDepth;
350 }
351
352 CallStackFrame::~CallStackFrame() {
353 assert(Info.CurrentCall == this && "calls retired out of order");
354 --Info.CallStackDepth;
355 Info.CurrentCall = Caller;
356 }
357
John McCall93d91dc2010-05-07 17:22:02 +0000358 struct ComplexValue {
359 private:
360 bool IsInt;
361
362 public:
363 APSInt IntReal, IntImag;
364 APFloat FloatReal, FloatImag;
365
366 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
367
368 void makeComplexFloat() { IsInt = false; }
369 bool isComplexFloat() const { return !IsInt; }
370 APFloat &getComplexFloatReal() { return FloatReal; }
371 APFloat &getComplexFloatImag() { return FloatImag; }
372
373 void makeComplexInt() { IsInt = true; }
374 bool isComplexInt() const { return IsInt; }
375 APSInt &getComplexIntReal() { return IntReal; }
376 APSInt &getComplexIntImag() { return IntImag; }
377
Richard Smith0b0a0b62011-10-29 20:57:55 +0000378 void moveInto(CCValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000379 if (isComplexFloat())
Richard Smith0b0a0b62011-10-29 20:57:55 +0000380 v = CCValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000381 else
Richard Smith0b0a0b62011-10-29 20:57:55 +0000382 v = CCValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000383 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000384 void setFrom(const CCValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000385 assert(v.isComplexFloat() || v.isComplexInt());
386 if (v.isComplexFloat()) {
387 makeComplexFloat();
388 FloatReal = v.getComplexFloatReal();
389 FloatImag = v.getComplexFloatImag();
390 } else {
391 makeComplexInt();
392 IntReal = v.getComplexIntReal();
393 IntImag = v.getComplexIntImag();
394 }
395 }
John McCall93d91dc2010-05-07 17:22:02 +0000396 };
John McCall45d55e42010-05-07 21:00:08 +0000397
398 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000399 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000400 CharUnits Offset;
Richard Smithfec09922011-11-01 16:57:24 +0000401 CallStackFrame *Frame;
Richard Smith96e0c102011-11-04 02:25:55 +0000402 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000403
Richard Smithce40ad62011-11-12 22:28:03 +0000404 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000405 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000406 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithfec09922011-11-01 16:57:24 +0000407 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith96e0c102011-11-04 02:25:55 +0000408 SubobjectDesignator &getLValueDesignator() { return Designator; }
409 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000410
Richard Smith0b0a0b62011-10-29 20:57:55 +0000411 void moveInto(CCValue &V) const {
Richard Smith96e0c102011-11-04 02:25:55 +0000412 V = CCValue(Base, Offset, Frame, Designator);
John McCall45d55e42010-05-07 21:00:08 +0000413 }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000414 void setFrom(const CCValue &V) {
415 assert(V.isLValue());
416 Base = V.getLValueBase();
417 Offset = V.getLValueOffset();
Richard Smithfec09922011-11-01 16:57:24 +0000418 Frame = V.getLValueFrame();
Richard Smith96e0c102011-11-04 02:25:55 +0000419 Designator = V.getLValueDesignator();
420 }
421
Richard Smithce40ad62011-11-12 22:28:03 +0000422 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
423 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000424 Offset = CharUnits::Zero();
425 Frame = F;
426 Designator = SubobjectDesignator();
John McCallc07a0c72011-02-17 10:25:35 +0000427 }
John McCall45d55e42010-05-07 21:00:08 +0000428 };
Richard Smith027bf112011-11-17 22:56:20 +0000429
430 struct MemberPtr {
431 MemberPtr() {}
432 explicit MemberPtr(const ValueDecl *Decl) :
433 DeclAndIsDerivedMember(Decl, false), Path() {}
434
435 /// The member or (direct or indirect) field referred to by this member
436 /// pointer, or 0 if this is a null member pointer.
437 const ValueDecl *getDecl() const {
438 return DeclAndIsDerivedMember.getPointer();
439 }
440 /// Is this actually a member of some type derived from the relevant class?
441 bool isDerivedMember() const {
442 return DeclAndIsDerivedMember.getInt();
443 }
444 /// Get the class which the declaration actually lives in.
445 const CXXRecordDecl *getContainingRecord() const {
446 return cast<CXXRecordDecl>(
447 DeclAndIsDerivedMember.getPointer()->getDeclContext());
448 }
449
450 void moveInto(CCValue &V) const {
451 V = CCValue(getDecl(), isDerivedMember(), Path);
452 }
453 void setFrom(const CCValue &V) {
454 assert(V.isMemberPointer());
455 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
456 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
457 Path.clear();
458 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
459 Path.insert(Path.end(), P.begin(), P.end());
460 }
461
462 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
463 /// whether the member is a member of some class derived from the class type
464 /// of the member pointer.
465 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
466 /// Path - The path of base/derived classes from the member declaration's
467 /// class (exclusive) to the class type of the member pointer (inclusive).
468 SmallVector<const CXXRecordDecl*, 4> Path;
469
470 /// Perform a cast towards the class of the Decl (either up or down the
471 /// hierarchy).
472 bool castBack(const CXXRecordDecl *Class) {
473 assert(!Path.empty());
474 const CXXRecordDecl *Expected;
475 if (Path.size() >= 2)
476 Expected = Path[Path.size() - 2];
477 else
478 Expected = getContainingRecord();
479 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
480 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
481 // if B does not contain the original member and is not a base or
482 // derived class of the class containing the original member, the result
483 // of the cast is undefined.
484 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
485 // (D::*). We consider that to be a language defect.
486 return false;
487 }
488 Path.pop_back();
489 return true;
490 }
491 /// Perform a base-to-derived member pointer cast.
492 bool castToDerived(const CXXRecordDecl *Derived) {
493 if (!getDecl())
494 return true;
495 if (!isDerivedMember()) {
496 Path.push_back(Derived);
497 return true;
498 }
499 if (!castBack(Derived))
500 return false;
501 if (Path.empty())
502 DeclAndIsDerivedMember.setInt(false);
503 return true;
504 }
505 /// Perform a derived-to-base member pointer cast.
506 bool castToBase(const CXXRecordDecl *Base) {
507 if (!getDecl())
508 return true;
509 if (Path.empty())
510 DeclAndIsDerivedMember.setInt(true);
511 if (isDerivedMember()) {
512 Path.push_back(Base);
513 return true;
514 }
515 return castBack(Base);
516 }
517 };
John McCall93d91dc2010-05-07 17:22:02 +0000518}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000519
Richard Smith0b0a0b62011-10-29 20:57:55 +0000520static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithed5165f2011-11-04 05:33:44 +0000521static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +0000522 const LValue &This, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000523static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
524static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000525static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
526 EvalInfo &Info);
527static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000528static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000529static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000530 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000531static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000532static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000533
534//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000535// Misc utilities
536//===----------------------------------------------------------------------===//
537
Richard Smithd62306a2011-11-10 06:34:14 +0000538/// Should this call expression be treated as a string literal?
539static bool IsStringLiteralCall(const CallExpr *E) {
540 unsigned Builtin = E->isBuiltinCall();
541 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
542 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
543}
544
Richard Smithce40ad62011-11-12 22:28:03 +0000545static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000546 // C++11 [expr.const]p3 An address constant expression is a prvalue core
547 // constant expression of pointer type that evaluates to...
548
549 // ... a null pointer value, or a prvalue core constant expression of type
550 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000551 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000552
Richard Smithce40ad62011-11-12 22:28:03 +0000553 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
554 // ... the address of an object with static storage duration,
555 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
556 return VD->hasGlobalStorage();
557 // ... the address of a function,
558 return isa<FunctionDecl>(D);
559 }
560
561 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000562 switch (E->getStmtClass()) {
563 default:
564 return false;
Richard Smithd62306a2011-11-10 06:34:14 +0000565 case Expr::CompoundLiteralExprClass:
566 return cast<CompoundLiteralExpr>(E)->isFileScope();
567 // A string literal has static storage duration.
568 case Expr::StringLiteralClass:
569 case Expr::PredefinedExprClass:
570 case Expr::ObjCStringLiteralClass:
571 case Expr::ObjCEncodeExprClass:
572 return true;
573 case Expr::CallExprClass:
574 return IsStringLiteralCall(cast<CallExpr>(E));
575 // For GCC compatibility, &&label has static storage duration.
576 case Expr::AddrLabelExprClass:
577 return true;
578 // A Block literal expression may be used as the initialization value for
579 // Block variables at global or local static scope.
580 case Expr::BlockExprClass:
581 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
582 }
John McCall95007602010-05-10 23:27:23 +0000583}
584
Richard Smith80815602011-11-07 05:07:52 +0000585/// Check that this reference or pointer core constant expression is a valid
586/// value for a constant expression. Type T should be either LValue or CCValue.
587template<typename T>
Richard Smithf57d8cb2011-12-09 22:58:01 +0000588static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
589 const T &LVal, APValue &Value) {
590 if (!IsGlobalLValue(LVal.getLValueBase())) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000591 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith80815602011-11-07 05:07:52 +0000592 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000593 }
Richard Smith80815602011-11-07 05:07:52 +0000594
595 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
596 // A constant expression must refer to an object or be a null pointer.
Richard Smith027bf112011-11-17 22:56:20 +0000597 if (Designator.Invalid ||
Richard Smith80815602011-11-07 05:07:52 +0000598 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smith80815602011-11-07 05:07:52 +0000599 // FIXME: This is not a constant expression.
600 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
601 APValue::NoLValuePath());
602 return true;
603 }
604
605 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smith027bf112011-11-17 22:56:20 +0000606 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith80815602011-11-07 05:07:52 +0000607 return true;
608}
609
Richard Smith0b0a0b62011-10-29 20:57:55 +0000610/// Check that this core constant expression value is a valid value for a
Richard Smithed5165f2011-11-04 05:33:44 +0000611/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000612/// If not, report an appropriate diagnostic.
613static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
614 const CCValue &CCValue, APValue &Value) {
Richard Smith80815602011-11-07 05:07:52 +0000615 if (!CCValue.isLValue()) {
616 Value = CCValue;
617 return true;
618 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000619 return CheckLValueConstantExpression(Info, E, CCValue, Value);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000620}
621
Richard Smith83c68212011-10-31 05:11:32 +0000622const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +0000623 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +0000624}
625
626static bool IsLiteralLValue(const LValue &Value) {
Richard Smithce40ad62011-11-12 22:28:03 +0000627 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith83c68212011-10-31 05:11:32 +0000628}
629
Richard Smithcecf1842011-11-01 21:06:14 +0000630static bool IsWeakLValue(const LValue &Value) {
631 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +0000632 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +0000633}
634
Richard Smith027bf112011-11-17 22:56:20 +0000635static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +0000636 // A null base expression indicates a null pointer. These are always
637 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +0000638 if (!Value.getLValueBase()) {
639 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +0000640 return true;
641 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000642
John McCall95007602010-05-10 23:27:23 +0000643 // Require the base expression to be a global l-value.
Richard Smith0b0a0b62011-10-29 20:57:55 +0000644 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smith027bf112011-11-17 22:56:20 +0000645 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall95007602010-05-10 23:27:23 +0000646
Richard Smith027bf112011-11-17 22:56:20 +0000647 // We have a non-null base. These are generally known to be true, but if it's
648 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000649 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +0000650 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +0000651 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +0000652}
653
Richard Smith0b0a0b62011-10-29 20:57:55 +0000654static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +0000655 switch (Val.getKind()) {
656 case APValue::Uninitialized:
657 return false;
658 case APValue::Int:
659 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000660 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000661 case APValue::Float:
662 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000663 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000664 case APValue::ComplexInt:
665 Result = Val.getComplexIntReal().getBoolValue() ||
666 Val.getComplexIntImag().getBoolValue();
667 return true;
668 case APValue::ComplexFloat:
669 Result = !Val.getComplexFloatReal().isZero() ||
670 !Val.getComplexFloatImag().isZero();
671 return true;
Richard Smith027bf112011-11-17 22:56:20 +0000672 case APValue::LValue:
673 return EvalPointerValueAsBool(Val, Result);
674 case APValue::MemberPointer:
675 Result = Val.getMemberPointerDecl();
676 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000677 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +0000678 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +0000679 case APValue::Struct:
680 case APValue::Union:
Richard Smith11562c52011-10-28 17:51:58 +0000681 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000682 }
683
Richard Smith11562c52011-10-28 17:51:58 +0000684 llvm_unreachable("unknown APValue kind");
685}
686
687static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
688 EvalInfo &Info) {
689 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith0b0a0b62011-10-29 20:57:55 +0000690 CCValue Val;
Richard Smith11562c52011-10-28 17:51:58 +0000691 if (!Evaluate(Val, Info, E))
692 return false;
693 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000694}
695
Mike Stump11289f42009-09-09 15:08:12 +0000696static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000697 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000698 unsigned DestWidth = Ctx.getIntWidth(DestType);
699 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000700 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000701
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000702 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000703 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000704 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000705 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
706 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000707}
708
Mike Stump11289f42009-09-09 15:08:12 +0000709static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000710 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000711 bool ignored;
712 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000713 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000714 APFloat::rmNearestTiesToEven, &ignored);
715 return Result;
716}
717
Mike Stump11289f42009-09-09 15:08:12 +0000718static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000719 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000720 unsigned DestWidth = Ctx.getIntWidth(DestType);
721 APSInt Result = Value;
722 // Figure out if this is a truncate, extend or noop cast.
723 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000724 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000725 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000726 return Result;
727}
728
Mike Stump11289f42009-09-09 15:08:12 +0000729static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000730 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000731
732 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
733 Result.convertFromAPInt(Value, Value.isSigned(),
734 APFloat::rmNearestTiesToEven);
735 return Result;
736}
737
Richard Smith027bf112011-11-17 22:56:20 +0000738static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
739 const CXXRecordDecl *&MostDerivedType,
740 unsigned &MostDerivedPathLength,
741 bool &MostDerivedIsArrayElement) {
742 const SubobjectDesignator &D = LVal.Designator;
743 if (D.Invalid || !LVal.Base)
Richard Smithd62306a2011-11-10 06:34:14 +0000744 return false;
745
Richard Smith027bf112011-11-17 22:56:20 +0000746 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smithd62306a2011-11-10 06:34:14 +0000747
748 // Find path prefix which leads to the most-derived subobject.
Richard Smithd62306a2011-11-10 06:34:14 +0000749 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smith027bf112011-11-17 22:56:20 +0000750 MostDerivedPathLength = 0;
751 MostDerivedIsArrayElement = false;
Richard Smithd62306a2011-11-10 06:34:14 +0000752
753 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
754 bool IsArray = T && T->isArrayType();
755 if (IsArray)
756 T = T->getBaseElementTypeUnsafe();
757 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
758 T = FD->getType().getTypePtr();
759 else
760 T = 0;
761
762 if (T) {
763 MostDerivedType = T->getAsCXXRecordDecl();
764 MostDerivedPathLength = I + 1;
765 MostDerivedIsArrayElement = IsArray;
766 }
767 }
768
Richard Smithd62306a2011-11-10 06:34:14 +0000769 // (B*)&d + 1 has no most-derived object.
770 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
771 return false;
772
Richard Smith027bf112011-11-17 22:56:20 +0000773 return MostDerivedType != 0;
774}
775
776static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
777 const RecordDecl *TruncatedType,
778 unsigned TruncatedElements,
779 bool IsArrayElement) {
780 SubobjectDesignator &D = Result.Designator;
781 const RecordDecl *RD = TruncatedType;
782 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smithd62306a2011-11-10 06:34:14 +0000783 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
784 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +0000785 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +0000786 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +0000787 else
Richard Smithd62306a2011-11-10 06:34:14 +0000788 Result.Offset -= Layout.getBaseClassOffset(Base);
789 RD = Base;
790 }
Richard Smith027bf112011-11-17 22:56:20 +0000791 D.Entries.resize(TruncatedElements);
792 D.ArrayElement = IsArrayElement;
793}
794
795/// If the given LValue refers to a base subobject of some object, find the most
796/// derived object and the corresponding complete record type. This is necessary
797/// in order to find the offset of a virtual base class.
798static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
799 const CXXRecordDecl *&MostDerivedType) {
800 unsigned MostDerivedPathLength;
801 bool MostDerivedIsArrayElement;
802 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
803 MostDerivedPathLength, MostDerivedIsArrayElement))
804 return false;
805
806 // Remove the trailing base class path entries and their offsets.
807 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
808 MostDerivedIsArrayElement);
Richard Smithd62306a2011-11-10 06:34:14 +0000809 return true;
810}
811
812static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
813 const CXXRecordDecl *Derived,
814 const CXXRecordDecl *Base,
815 const ASTRecordLayout *RL = 0) {
816 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
817 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
818 Obj.Designator.addDecl(Base, /*Virtual*/ false);
819}
820
821static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
822 const CXXRecordDecl *DerivedDecl,
823 const CXXBaseSpecifier *Base) {
824 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
825
826 if (!Base->isVirtual()) {
827 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
828 return true;
829 }
830
831 // Extract most-derived object and corresponding type.
832 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
833 return false;
834
835 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
836 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
837 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
838 return true;
839}
840
841/// Update LVal to refer to the given field, which must be a member of the type
842/// currently described by LVal.
843static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
844 const FieldDecl *FD,
845 const ASTRecordLayout *RL = 0) {
846 if (!RL)
847 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
848
849 unsigned I = FD->getFieldIndex();
850 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
851 LVal.Designator.addDecl(FD);
852}
853
854/// Get the size of the given type in char units.
855static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
856 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
857 // extension.
858 if (Type->isVoidType() || Type->isFunctionType()) {
859 Size = CharUnits::One();
860 return true;
861 }
862
863 if (!Type->isConstantSizeType()) {
864 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
865 return false;
866 }
867
868 Size = Info.Ctx.getTypeSizeInChars(Type);
869 return true;
870}
871
872/// Update a pointer value to model pointer arithmetic.
873/// \param Info - Information about the ongoing evaluation.
874/// \param LVal - The pointer value to be updated.
875/// \param EltTy - The pointee type represented by LVal.
876/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
877static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
878 QualType EltTy, int64_t Adjustment) {
879 CharUnits SizeOfPointee;
880 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
881 return false;
882
883 // Compute the new offset in the appropriate width.
884 LVal.Offset += Adjustment * SizeOfPointee;
885 LVal.Designator.adjustIndex(Adjustment);
886 return true;
887}
888
Richard Smith27908702011-10-24 17:54:18 +0000889/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000890static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
891 const VarDecl *VD,
Richard Smithfec09922011-11-01 16:57:24 +0000892 CallStackFrame *Frame, CCValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +0000893 // If this is a parameter to an active constexpr function call, perform
894 // argument substitution.
895 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000896 if (!Frame || !Frame->Arguments) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000897 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +0000898 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000899 }
Richard Smithfec09922011-11-01 16:57:24 +0000900 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
901 return true;
Richard Smith254a73d2011-10-28 22:34:42 +0000902 }
Richard Smith27908702011-10-24 17:54:18 +0000903
Richard Smithd62306a2011-11-10 06:34:14 +0000904 // If we're currently evaluating the initializer of this declaration, use that
905 // in-flight value.
906 if (Info.EvaluatingDecl == VD) {
907 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
908 return !Result.isUninit();
909 }
910
Richard Smithcecf1842011-11-01 21:06:14 +0000911 // Never evaluate the initializer of a weak variable. We can't be sure that
912 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000913 if (VD->isWeak()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000914 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +0000915 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000916 }
Richard Smithcecf1842011-11-01 21:06:14 +0000917
Richard Smith27908702011-10-24 17:54:18 +0000918 const Expr *Init = VD->getAnyInitializer();
Richard Smithf57d8cb2011-12-09 22:58:01 +0000919 if (!Init || Init->isValueDependent()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000920 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000921 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000922 }
Richard Smith27908702011-10-24 17:54:18 +0000923
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smithfec09922011-11-01 16:57:24 +0000925 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000926 return !Result.isUninit();
927 }
Richard Smith27908702011-10-24 17:54:18 +0000928
Richard Smithf57d8cb2011-12-09 22:58:01 +0000929 if (VD->isEvaluatingValue()) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000930 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000931 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000932 }
Richard Smith27908702011-10-24 17:54:18 +0000933
934 VD->setEvaluatingValue();
935
Richard Smith0b0a0b62011-10-29 20:57:55 +0000936 Expr::EvalStatus EStatus;
937 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smithd62306a2011-11-10 06:34:14 +0000938 APValue EvalResult;
939 InitInfo.setEvaluatingDecl(VD, EvalResult);
940 LValue LVal;
Richard Smithce40ad62011-11-12 22:28:03 +0000941 LVal.set(VD);
Richard Smith11562c52011-10-28 17:51:58 +0000942 // FIXME: The caller will need to know whether the value was a constant
943 // expression. If not, we should propagate up a diagnostic.
Richard Smithd62306a2011-11-10 06:34:14 +0000944 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000945 // FIXME: If the evaluation failure was not permanent (for instance, if we
946 // hit a variable with no declaration yet, or a constexpr function with no
947 // definition yet), the standard is unclear as to how we should behave.
948 //
949 // Either the initializer should be evaluated when the variable is defined,
950 // or a failed evaluation of the initializer should be reattempted each time
951 // it is used.
Richard Smith27908702011-10-24 17:54:18 +0000952 VD->setEvaluatedValue(APValue());
Richard Smith92b1ce02011-12-12 09:28:41 +0000953 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0b0a0b62011-10-29 20:57:55 +0000954 return false;
955 }
Richard Smith27908702011-10-24 17:54:18 +0000956
Richard Smithed5165f2011-11-04 05:33:44 +0000957 VD->setEvaluatedValue(EvalResult);
958 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith0b0a0b62011-10-29 20:57:55 +0000959 return true;
Richard Smith27908702011-10-24 17:54:18 +0000960}
961
Richard Smith11562c52011-10-28 17:51:58 +0000962static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000963 Qualifiers Quals = T.getQualifiers();
964 return Quals.hasConst() && !Quals.hasVolatile();
965}
966
Richard Smithe97cbd72011-11-11 04:05:33 +0000967/// Get the base index of the given base class within an APValue representing
968/// the given derived class.
969static unsigned getBaseIndex(const CXXRecordDecl *Derived,
970 const CXXRecordDecl *Base) {
971 Base = Base->getCanonicalDecl();
972 unsigned Index = 0;
973 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
974 E = Derived->bases_end(); I != E; ++I, ++Index) {
975 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
976 return Index;
977 }
978
979 llvm_unreachable("base class missing from derived class's bases list");
980}
981
Richard Smithf3e9e432011-11-07 09:22:26 +0000982/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +0000983static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
984 CCValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +0000985 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000986 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000987 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +0000988 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000989 }
Richard Smith6804be52011-11-11 08:28:03 +0000990 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +0000991 return true;
Richard Smithf3e9e432011-11-07 09:22:26 +0000992
993 assert(!Obj.isLValue() && "extracting subobject of lvalue");
994 const APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +0000995 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +0000996 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +0000997 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +0000998 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +0000999 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001000 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001001 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001002 if (CAT->getSize().ule(Index)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001003 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001004 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001005 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001006 if (O->getArrayInitializedElts() > Index)
1007 O = &O->getArrayInitializedElt(Index);
1008 else
1009 O = &O->getArrayFiller();
1010 ObjType = CAT->getElementType();
Richard Smithd62306a2011-11-10 06:34:14 +00001011 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1012 // Next subobject is a class, struct or union field.
1013 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1014 if (RD->isUnion()) {
1015 const FieldDecl *UnionField = O->getUnionField();
1016 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001017 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001018 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001019 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001020 }
Richard Smithd62306a2011-11-10 06:34:14 +00001021 O = &O->getUnionValue();
1022 } else
1023 O = &O->getStructField(Field->getFieldIndex());
1024 ObjType = Field->getType();
Richard Smithf3e9e432011-11-07 09:22:26 +00001025 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001026 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001027 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1028 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1029 O = &O->getStructBase(getBaseIndex(Derived, Base));
1030 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001031 }
Richard Smithd62306a2011-11-10 06:34:14 +00001032
Richard Smithf57d8cb2011-12-09 22:58:01 +00001033 if (O->isUninit()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001034 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001035 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001036 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001037 }
1038
Richard Smithf3e9e432011-11-07 09:22:26 +00001039 Obj = CCValue(*O, CCValue::GlobalValue());
1040 return true;
1041}
1042
Richard Smithd62306a2011-11-10 06:34:14 +00001043/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1044/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1045/// for looking up the glvalue referred to by an entity of reference type.
1046///
1047/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001048/// \param Conv - The expression for which we are performing the conversion.
1049/// Used for diagnostics.
Richard Smithd62306a2011-11-10 06:34:14 +00001050/// \param Type - The type we expect this conversion to produce.
1051/// \param LVal - The glvalue on which we are attempting to perform this action.
1052/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001053static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1054 QualType Type,
Richard Smithf3e9e432011-11-07 09:22:26 +00001055 const LValue &LVal, CCValue &RVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001056 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001057 CallStackFrame *Frame = LVal.Frame;
Richard Smith11562c52011-10-28 17:51:58 +00001058
Richard Smithf57d8cb2011-12-09 22:58:01 +00001059 if (!LVal.Base) {
1060 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith92b1ce02011-12-12 09:28:41 +00001061 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith11562c52011-10-28 17:51:58 +00001062 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001063 }
Richard Smith11562c52011-10-28 17:51:58 +00001064
Richard Smithce40ad62011-11-12 22:28:03 +00001065 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001066 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1067 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001068 // expressions are constant expressions too. Inside constexpr functions,
1069 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001070 // In C, such things can also be folded, although they are not ICEs.
1071 //
Richard Smith254a73d2011-10-28 22:34:42 +00001072 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1073 // interpretation of C++11 suggests that volatile parameters are OK if
1074 // they're never read (there's no prohibition against constructing volatile
1075 // objects in constant expressions), but lvalue-to-rvalue conversions on
1076 // them are not permitted.
Richard Smith11562c52011-10-28 17:51:58 +00001077 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001078 if (!VD || VD->isInvalidDecl()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001079 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001080 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001081 }
1082
Richard Smithce40ad62011-11-12 22:28:03 +00001083 QualType VT = VD->getType();
Richard Smith96e0c102011-11-04 02:25:55 +00001084 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001085 if (!IsConstNonVolatile(VT)) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001086 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001087 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001088 }
Richard Smitha08acd82011-11-07 03:22:51 +00001089 // FIXME: Allow folding of values of any literal type in all languages.
1090 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00001091 !VD->isConstexpr()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001092 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001093 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001094 }
Richard Smith96e0c102011-11-04 02:25:55 +00001095 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001096 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001097 return false;
1098
Richard Smith0b0a0b62011-10-29 20:57:55 +00001099 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001100 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001101
1102 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1103 // conversion. This happens when the declaration and the lvalue should be
1104 // considered synonymous, for instance when initializing an array of char
1105 // from a string literal. Continue as if the initializer lvalue was the
1106 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001107 assert(RVal.getLValueOffset().isZero() &&
1108 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001109 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithfec09922011-11-01 16:57:24 +00001110 Frame = RVal.getLValueFrame();
Richard Smith11562c52011-10-28 17:51:58 +00001111 }
1112
Richard Smith96e0c102011-11-04 02:25:55 +00001113 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1114 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1115 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001116 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001117 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001118 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001119 }
Richard Smith96e0c102011-11-04 02:25:55 +00001120
1121 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith80815602011-11-07 05:07:52 +00001122 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001123 if (Index > S->getLength()) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001124 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001125 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001126 }
Richard Smith96e0c102011-11-04 02:25:55 +00001127 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1128 Type->isUnsignedIntegerType());
1129 if (Index < S->getLength())
1130 Value = S->getCodeUnit(Index);
1131 RVal = CCValue(Value);
1132 return true;
1133 }
1134
Richard Smithf3e9e432011-11-07 09:22:26 +00001135 if (Frame) {
1136 // If this is a temporary expression with a nontrivial initializer, grab the
1137 // value from the relevant stack frame.
1138 RVal = Frame->Temporaries[Base];
1139 } else if (const CompoundLiteralExpr *CLE
1140 = dyn_cast<CompoundLiteralExpr>(Base)) {
1141 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1142 // initializer until now for such expressions. Such an expression can't be
1143 // an ICE in C, so this only matters for fold.
1144 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1145 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1146 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001147 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00001148 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001149 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001150 }
Richard Smith96e0c102011-11-04 02:25:55 +00001151
Richard Smithf57d8cb2011-12-09 22:58:01 +00001152 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1153 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001154}
1155
Richard Smithe97cbd72011-11-11 04:05:33 +00001156/// Build an lvalue for the object argument of a member function call.
1157static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1158 LValue &This) {
1159 if (Object->getType()->isPointerType())
1160 return EvaluatePointer(Object, This, Info);
1161
1162 if (Object->isGLValue())
1163 return EvaluateLValue(Object, This, Info);
1164
Richard Smith027bf112011-11-17 22:56:20 +00001165 if (Object->getType()->isLiteralType())
1166 return EvaluateTemporary(Object, This, Info);
1167
1168 return false;
1169}
1170
1171/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1172/// lvalue referring to the result.
1173///
1174/// \param Info - Information about the ongoing evaluation.
1175/// \param BO - The member pointer access operation.
1176/// \param LV - Filled in with a reference to the resulting object.
1177/// \param IncludeMember - Specifies whether the member itself is included in
1178/// the resulting LValue subobject designator. This is not possible when
1179/// creating a bound member function.
1180/// \return The field or method declaration to which the member pointer refers,
1181/// or 0 if evaluation fails.
1182static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1183 const BinaryOperator *BO,
1184 LValue &LV,
1185 bool IncludeMember = true) {
1186 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1187
1188 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1189 return 0;
1190
1191 MemberPtr MemPtr;
1192 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1193 return 0;
1194
1195 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1196 // member value, the behavior is undefined.
1197 if (!MemPtr.getDecl())
1198 return 0;
1199
1200 if (MemPtr.isDerivedMember()) {
1201 // This is a member of some derived class. Truncate LV appropriately.
1202 const CXXRecordDecl *MostDerivedType;
1203 unsigned MostDerivedPathLength;
1204 bool MostDerivedIsArrayElement;
1205 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1206 MostDerivedIsArrayElement))
1207 return 0;
1208
1209 // The end of the derived-to-base path for the base object must match the
1210 // derived-to-base path for the member pointer.
1211 if (MostDerivedPathLength + MemPtr.Path.size() >
1212 LV.Designator.Entries.size())
1213 return 0;
1214 unsigned PathLengthToMember =
1215 LV.Designator.Entries.size() - MemPtr.Path.size();
1216 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1217 const CXXRecordDecl *LVDecl = getAsBaseClass(
1218 LV.Designator.Entries[PathLengthToMember + I]);
1219 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1220 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1221 return 0;
1222 }
1223
1224 // Truncate the lvalue to the appropriate derived class.
1225 bool ResultIsArray = false;
1226 if (PathLengthToMember == MostDerivedPathLength)
1227 ResultIsArray = MostDerivedIsArrayElement;
1228 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1229 PathLengthToMember, ResultIsArray);
1230 } else if (!MemPtr.Path.empty()) {
1231 // Extend the LValue path with the member pointer's path.
1232 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1233 MemPtr.Path.size() + IncludeMember);
1234
1235 // Walk down to the appropriate base class.
1236 QualType LVType = BO->getLHS()->getType();
1237 if (const PointerType *PT = LVType->getAs<PointerType>())
1238 LVType = PT->getPointeeType();
1239 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1240 assert(RD && "member pointer access on non-class-type expression");
1241 // The first class in the path is that of the lvalue.
1242 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1243 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1244 HandleLValueDirectBase(Info, LV, RD, Base);
1245 RD = Base;
1246 }
1247 // Finally cast to the class containing the member.
1248 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1249 }
1250
1251 // Add the member. Note that we cannot build bound member functions here.
1252 if (IncludeMember) {
1253 // FIXME: Deal with IndirectFieldDecls.
1254 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1255 if (!FD) return 0;
1256 HandleLValueMember(Info, LV, FD);
1257 }
1258
1259 return MemPtr.getDecl();
1260}
1261
1262/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1263/// the provided lvalue, which currently refers to the base object.
1264static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1265 LValue &Result) {
1266 const CXXRecordDecl *MostDerivedType;
1267 unsigned MostDerivedPathLength;
1268 bool MostDerivedIsArrayElement;
1269
1270 // Check this cast doesn't take us outside the object.
1271 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1272 MostDerivedPathLength,
1273 MostDerivedIsArrayElement))
1274 return false;
1275 SubobjectDesignator &D = Result.Designator;
1276 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1277 return false;
1278
1279 // Check the type of the final cast. We don't need to check the path,
1280 // since a cast can only be formed if the path is unique.
1281 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1282 bool ResultIsArray = false;
1283 QualType TargetQT = E->getType();
1284 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1285 TargetQT = PT->getPointeeType();
1286 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1287 const CXXRecordDecl *FinalType;
1288 if (NewEntriesSize == MostDerivedPathLength) {
1289 ResultIsArray = MostDerivedIsArrayElement;
1290 FinalType = MostDerivedType;
1291 } else
1292 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1293 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1294 return false;
1295
1296 // Truncate the lvalue to the appropriate derived class.
1297 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1298 ResultIsArray);
1299 return true;
Richard Smithe97cbd72011-11-11 04:05:33 +00001300}
1301
Mike Stump876387b2009-10-27 22:09:17 +00001302namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00001303enum EvalStmtResult {
1304 /// Evaluation failed.
1305 ESR_Failed,
1306 /// Hit a 'return' statement.
1307 ESR_Returned,
1308 /// Evaluation succeeded.
1309 ESR_Succeeded
1310};
1311}
1312
1313// Evaluate a statement.
Richard Smith0b0a0b62011-10-29 20:57:55 +00001314static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00001315 const Stmt *S) {
1316 switch (S->getStmtClass()) {
1317 default:
1318 return ESR_Failed;
1319
1320 case Stmt::NullStmtClass:
1321 case Stmt::DeclStmtClass:
1322 return ESR_Succeeded;
1323
1324 case Stmt::ReturnStmtClass:
1325 if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1326 return ESR_Returned;
1327 return ESR_Failed;
1328
1329 case Stmt::CompoundStmtClass: {
1330 const CompoundStmt *CS = cast<CompoundStmt>(S);
1331 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1332 BE = CS->body_end(); BI != BE; ++BI) {
1333 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1334 if (ESR != ESR_Succeeded)
1335 return ESR;
1336 }
1337 return ESR_Succeeded;
1338 }
1339 }
1340}
1341
Richard Smithd62306a2011-11-10 06:34:14 +00001342namespace {
Richard Smith60494462011-11-11 05:48:57 +00001343typedef SmallVector<CCValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00001344}
1345
1346/// EvaluateArgs - Evaluate the arguments to a function call.
1347static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1348 EvalInfo &Info) {
1349 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1350 I != E; ++I)
1351 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1352 return false;
1353 return true;
1354}
1355
Richard Smith254a73d2011-10-28 22:34:42 +00001356/// Evaluate a function call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001357static bool HandleFunctionCall(const Expr *CallExpr, const LValue *This,
1358 ArrayRef<const Expr*> Args, const Stmt *Body,
1359 EvalInfo &Info, CCValue &Result) {
1360 if (Info.atCallLimit()) {
1361 // FIXME: Add a specific proper diagnostic for this.
Richard Smith92b1ce02011-12-12 09:28:41 +00001362 Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith254a73d2011-10-28 22:34:42 +00001363 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001364 }
Richard Smith254a73d2011-10-28 22:34:42 +00001365
Richard Smithd62306a2011-11-10 06:34:14 +00001366 ArgVector ArgValues(Args.size());
1367 if (!EvaluateArgs(Args, ArgValues, Info))
1368 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00001369
Richard Smithd62306a2011-11-10 06:34:14 +00001370 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00001371 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1372}
1373
Richard Smithd62306a2011-11-10 06:34:14 +00001374/// Evaluate a constructor call.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001375static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00001376 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00001377 const CXXConstructorDecl *Definition,
Richard Smithe97cbd72011-11-11 04:05:33 +00001378 EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00001379 APValue &Result) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001380 if (Info.atCallLimit()) {
1381 // FIXME: Add a specific diagnostic for this.
Richard Smith92b1ce02011-12-12 09:28:41 +00001382 Info.Diag(CallExpr->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001383 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001384 }
Richard Smithd62306a2011-11-10 06:34:14 +00001385
1386 ArgVector ArgValues(Args.size());
1387 if (!EvaluateArgs(Args, ArgValues, Info))
1388 return false;
1389
1390 CallStackFrame Frame(Info, &This, ArgValues.data());
1391
1392 // If it's a delegating constructor, just delegate.
1393 if (Definition->isDelegatingConstructor()) {
1394 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1395 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1396 }
1397
1398 // Reserve space for the struct members.
1399 const CXXRecordDecl *RD = Definition->getParent();
1400 if (!RD->isUnion())
1401 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1402 std::distance(RD->field_begin(), RD->field_end()));
1403
1404 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1405
1406 unsigned BasesSeen = 0;
1407#ifndef NDEBUG
1408 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1409#endif
1410 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1411 E = Definition->init_end(); I != E; ++I) {
1412 if ((*I)->isBaseInitializer()) {
1413 QualType BaseType((*I)->getBaseClass(), 0);
1414#ifndef NDEBUG
1415 // Non-virtual base classes are initialized in the order in the class
1416 // definition. We cannot have a virtual base class for a literal type.
1417 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1418 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1419 "base class initializers not in expected order");
1420 ++BaseIt;
1421#endif
1422 LValue Subobject = This;
1423 HandleLValueDirectBase(Info, Subobject, RD,
1424 BaseType->getAsCXXRecordDecl(), &Layout);
1425 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1426 Subobject, (*I)->getInit()))
1427 return false;
1428 } else if (FieldDecl *FD = (*I)->getMember()) {
1429 LValue Subobject = This;
1430 HandleLValueMember(Info, Subobject, FD, &Layout);
1431 if (RD->isUnion()) {
1432 Result = APValue(FD);
1433 if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1434 Subobject, (*I)->getInit()))
1435 return false;
1436 } else if (!EvaluateConstantExpression(
1437 Result.getStructField(FD->getFieldIndex()),
1438 Info, Subobject, (*I)->getInit()))
1439 return false;
1440 } else {
1441 // FIXME: handle indirect field initializers
Richard Smith92b1ce02011-12-12 09:28:41 +00001442 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf57d8cb2011-12-09 22:58:01 +00001443 diag::note_invalid_subexpr_in_const_expr);
Richard Smithd62306a2011-11-10 06:34:14 +00001444 return false;
1445 }
1446 }
1447
1448 return true;
1449}
1450
Richard Smith254a73d2011-10-28 22:34:42 +00001451namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001452class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +00001453 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +00001454 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +00001455public:
1456
Richard Smith725810a2011-10-16 21:26:27 +00001457 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +00001458
1459 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +00001460 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +00001461 return true;
1462 }
1463
Peter Collingbournee9200682011-05-13 03:29:01 +00001464 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1465 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001466 return Visit(E->getResultExpr());
1467 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001468 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001469 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001470 return true;
1471 return false;
1472 }
John McCall31168b02011-06-15 23:02:42 +00001473 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001474 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001475 return true;
1476 return false;
1477 }
1478 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001479 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +00001480 return true;
1481 return false;
1482 }
1483
Mike Stump876387b2009-10-27 22:09:17 +00001484 // We don't want to evaluate BlockExprs multiple times, as they generate
1485 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +00001486 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1487 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1488 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +00001489 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001490 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1491 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1492 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1493 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1494 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1495 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +00001496 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +00001497 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001498 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001499 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +00001500 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001501 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1502 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1503 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1504 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +00001505 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001506 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1507 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1508 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1509 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1510 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001511 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +00001512 return true;
Mike Stumpfa502902009-10-29 20:48:09 +00001513 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +00001514 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001515 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +00001516
1517 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +00001518 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +00001519 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1520 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00001521 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +00001522 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +00001523 return false;
1524 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001525
Peter Collingbournee9200682011-05-13 03:29:01 +00001526 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +00001527};
1528
John McCallc07a0c72011-02-17 10:25:35 +00001529class OpaqueValueEvaluation {
1530 EvalInfo &info;
1531 OpaqueValueExpr *opaqueValue;
1532
1533public:
1534 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1535 Expr *value)
1536 : info(info), opaqueValue(opaqueValue) {
1537
1538 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +00001539 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +00001540 this->opaqueValue = 0;
1541 return;
1542 }
John McCallc07a0c72011-02-17 10:25:35 +00001543 }
1544
1545 bool hasError() const { return opaqueValue == 0; }
1546
1547 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +00001548 // FIXME: This will not work for recursive constexpr functions using opaque
1549 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +00001550 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1551 }
1552};
1553
Mike Stump876387b2009-10-27 22:09:17 +00001554} // end anonymous namespace
1555
Eli Friedman9a156e52008-11-12 09:44:48 +00001556//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00001557// Generic Evaluation
1558//===----------------------------------------------------------------------===//
1559namespace {
1560
Richard Smithf57d8cb2011-12-09 22:58:01 +00001561// FIXME: RetTy is always bool. Remove it.
1562template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00001563class ExprEvaluatorBase
1564 : public ConstStmtVisitor<Derived, RetTy> {
1565private:
Richard Smith0b0a0b62011-10-29 20:57:55 +00001566 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001567 return static_cast<Derived*>(this)->Success(V, E);
1568 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001569 RetTy DerivedValueInitialization(const Expr *E) {
1570 return static_cast<Derived*>(this)->ValueInitialization(E);
1571 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001572
1573protected:
1574 EvalInfo &Info;
1575 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1576 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1577
Richard Smith92b1ce02011-12-12 09:28:41 +00001578 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith187ef012011-12-12 09:41:58 +00001579 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001580 }
1581
1582 /// Report an evaluation error. This should only be called when an error is
1583 /// first discovered. When propagating an error, just return false.
1584 bool Error(const Expr *E, diag::kind D) {
Richard Smith92b1ce02011-12-12 09:28:41 +00001585 Info.Diag(E->getExprLoc(), D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001586 return false;
1587 }
1588 bool Error(const Expr *E) {
1589 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1590 }
1591
1592 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00001593
Peter Collingbournee9200682011-05-13 03:29:01 +00001594public:
1595 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1596
1597 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00001598 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00001599 }
1600 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001601 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001602 }
1603
1604 RetTy VisitParenExpr(const ParenExpr *E)
1605 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1606 RetTy VisitUnaryExtension(const UnaryOperator *E)
1607 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1608 RetTy VisitUnaryPlus(const UnaryOperator *E)
1609 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1610 RetTy VisitChooseExpr(const ChooseExpr *E)
1611 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1612 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1613 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00001614 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1615 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00001616 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1617 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00001618
Richard Smith027bf112011-11-17 22:56:20 +00001619 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1620 switch (E->getOpcode()) {
1621 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00001622 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001623
1624 case BO_Comma:
1625 VisitIgnoredValue(E->getLHS());
1626 return StmtVisitorTy::Visit(E->getRHS());
1627
1628 case BO_PtrMemD:
1629 case BO_PtrMemI: {
1630 LValue Obj;
1631 if (!HandleMemberPointerAccess(Info, E, Obj))
1632 return false;
1633 CCValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001634 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00001635 return false;
1636 return DerivedSuccess(Result, E);
1637 }
1638 }
1639 }
1640
Peter Collingbournee9200682011-05-13 03:29:01 +00001641 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1642 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1643 if (opaque.hasError())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001644 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001645
1646 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +00001647 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001648 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001649
1650 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1651 }
1652
1653 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1654 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00001655 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001656 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001657
Richard Smith11562c52011-10-28 17:51:58 +00001658 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +00001659 return StmtVisitorTy::Visit(EvalExpr);
1660 }
1661
1662 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001663 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001664 if (!Value) {
1665 const Expr *Source = E->getSourceExpr();
1666 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001667 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001668 if (Source == E) { // sanity checking.
1669 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00001670 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00001671 }
1672 return StmtVisitorTy::Visit(Source);
1673 }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001674 return DerivedSuccess(*Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001675 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001676
Richard Smith254a73d2011-10-28 22:34:42 +00001677 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00001678 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00001679 QualType CalleeType = Callee->getType();
1680
Richard Smith254a73d2011-10-28 22:34:42 +00001681 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00001682 LValue *This = 0, ThisVal;
1683 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith656d49d2011-11-10 09:31:24 +00001684
Richard Smithe97cbd72011-11-11 04:05:33 +00001685 // Extract function decl and 'this' pointer from the callee.
1686 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001687 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00001688 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1689 // Explicit bound member calls, such as x.f() or p->g();
1690 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001691 return false;
1692 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00001693 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001694 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1695 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00001696 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1697 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00001698 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00001699 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001700 return Error(Callee);
1701
1702 FD = dyn_cast<FunctionDecl>(Member);
1703 if (!FD)
1704 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001705 } else if (CalleeType->isFunctionPointerType()) {
1706 CCValue Call;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001707 if (!Evaluate(Call, Info, Callee))
1708 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00001709
Richard Smithf57d8cb2011-12-09 22:58:01 +00001710 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1711 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00001712 FD = dyn_cast_or_null<FunctionDecl>(
1713 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00001714 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00001715 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00001716
1717 // Overloaded operator calls to member functions are represented as normal
1718 // calls with '*this' as the first argument.
1719 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1720 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00001721 // FIXME: When selecting an implicit conversion for an overloaded
1722 // operator delete, we sometimes try to evaluate calls to conversion
1723 // operators without a 'this' parameter!
1724 if (Args.empty())
1725 return Error(E);
1726
Richard Smithe97cbd72011-11-11 04:05:33 +00001727 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1728 return false;
1729 This = &ThisVal;
1730 Args = Args.slice(1);
1731 }
1732
1733 // Don't call function pointers which have been cast to some other type.
1734 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00001735 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00001736 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00001737 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001738
1739 const FunctionDecl *Definition;
1740 Stmt *Body = FD->getBody(Definition);
Richard Smithed5165f2011-11-04 05:33:44 +00001741 CCValue CCResult;
1742 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00001743
Richard Smithf57d8cb2011-12-09 22:58:01 +00001744 if (!Body || !Definition->isConstexpr() || Definition->isInvalidDecl())
1745 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00001746
Richard Smithf57d8cb2011-12-09 22:58:01 +00001747 if (!HandleFunctionCall(E, This, Args, Body, Info, CCResult) ||
1748 !CheckConstantExpression(Info, E, CCResult, Result))
1749 return false;
1750
1751 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smith254a73d2011-10-28 22:34:42 +00001752 }
1753
Richard Smith11562c52011-10-28 17:51:58 +00001754 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1755 return StmtVisitorTy::Visit(E->getInitializer());
1756 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001757 RetTy VisitInitListExpr(const InitListExpr *E) {
1758 if (Info.getLangOpts().CPlusPlus0x) {
1759 if (E->getNumInits() == 0)
1760 return DerivedValueInitialization(E);
1761 if (E->getNumInits() == 1)
1762 return StmtVisitorTy::Visit(E->getInit(0));
1763 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001764 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00001765 }
1766 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1767 return DerivedValueInitialization(E);
1768 }
1769 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1770 return DerivedValueInitialization(E);
1771 }
Richard Smith027bf112011-11-17 22:56:20 +00001772 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1773 return DerivedValueInitialization(E);
1774 }
Richard Smith4ce706a2011-10-11 21:43:33 +00001775
Richard Smithd62306a2011-11-10 06:34:14 +00001776 /// A member expression where the object is a prvalue is itself a prvalue.
1777 RetTy VisitMemberExpr(const MemberExpr *E) {
1778 assert(!E->isArrow() && "missing call to bound member function?");
1779
1780 CCValue Val;
1781 if (!Evaluate(Val, Info, E->getBase()))
1782 return false;
1783
1784 QualType BaseTy = E->getBase()->getType();
1785
1786 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00001787 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00001788 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1789 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1790 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1791
1792 SubobjectDesignator Designator;
1793 Designator.addDecl(FD);
1794
Richard Smithf57d8cb2011-12-09 22:58:01 +00001795 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00001796 DerivedSuccess(Val, E);
1797 }
1798
Richard Smith11562c52011-10-28 17:51:58 +00001799 RetTy VisitCastExpr(const CastExpr *E) {
1800 switch (E->getCastKind()) {
1801 default:
1802 break;
1803
1804 case CK_NoOp:
1805 return StmtVisitorTy::Visit(E->getSubExpr());
1806
1807 case CK_LValueToRValue: {
1808 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001809 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1810 return false;
1811 CCValue RVal;
1812 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
1813 return false;
1814 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00001815 }
1816 }
1817
Richard Smithf57d8cb2011-12-09 22:58:01 +00001818 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00001819 }
1820
Richard Smith4a678122011-10-24 18:44:57 +00001821 /// Visit a value which is evaluated, but whose value is ignored.
1822 void VisitIgnoredValue(const Expr *E) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001823 CCValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00001824 if (!Evaluate(Scratch, Info, E))
1825 Info.EvalStatus.HasSideEffects = true;
1826 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001827};
1828
1829}
1830
1831//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00001832// Common base class for lvalue and temporary evaluation.
1833//===----------------------------------------------------------------------===//
1834namespace {
1835template<class Derived>
1836class LValueExprEvaluatorBase
1837 : public ExprEvaluatorBase<Derived, bool> {
1838protected:
1839 LValue &Result;
1840 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1841 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1842
1843 bool Success(APValue::LValueBase B) {
1844 Result.set(B);
1845 return true;
1846 }
1847
1848public:
1849 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1850 ExprEvaluatorBaseTy(Info), Result(Result) {}
1851
1852 bool Success(const CCValue &V, const Expr *E) {
1853 Result.setFrom(V);
1854 return true;
1855 }
Richard Smith027bf112011-11-17 22:56:20 +00001856
1857 bool CheckValidLValue() {
1858 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1859 // there are no null references, nor once-past-the-end references.
1860 // FIXME: Check for one-past-the-end array indices
1861 return Result.Base && !Result.Designator.Invalid &&
1862 !Result.Designator.OnePastTheEnd;
1863 }
1864
1865 bool VisitMemberExpr(const MemberExpr *E) {
1866 // Handle non-static data members.
1867 QualType BaseTy;
1868 if (E->isArrow()) {
1869 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1870 return false;
1871 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1872 } else {
1873 if (!this->Visit(E->getBase()))
1874 return false;
1875 BaseTy = E->getBase()->getType();
1876 }
1877 // FIXME: In C++11, require the result to be a valid lvalue.
1878
1879 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1880 // FIXME: Handle IndirectFieldDecls
Richard Smithf57d8cb2011-12-09 22:58:01 +00001881 if (!FD) return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00001882 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1883 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1884 (void)BaseTy;
1885
1886 HandleLValueMember(this->Info, Result, FD);
1887
1888 if (FD->getType()->isReferenceType()) {
1889 CCValue RefValue;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001890 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00001891 RefValue))
1892 return false;
1893 return Success(RefValue, E);
1894 }
1895 return true;
1896 }
1897
1898 bool VisitBinaryOperator(const BinaryOperator *E) {
1899 switch (E->getOpcode()) {
1900 default:
1901 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
1902
1903 case BO_PtrMemD:
1904 case BO_PtrMemI:
1905 return HandleMemberPointerAccess(this->Info, E, Result);
1906 }
1907 }
1908
1909 bool VisitCastExpr(const CastExpr *E) {
1910 switch (E->getCastKind()) {
1911 default:
1912 return ExprEvaluatorBaseTy::VisitCastExpr(E);
1913
1914 case CK_DerivedToBase:
1915 case CK_UncheckedDerivedToBase: {
1916 if (!this->Visit(E->getSubExpr()))
1917 return false;
1918 if (!CheckValidLValue())
1919 return false;
1920
1921 // Now figure out the necessary offset to add to the base LV to get from
1922 // the derived class to the base class.
1923 QualType Type = E->getSubExpr()->getType();
1924
1925 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1926 PathE = E->path_end(); PathI != PathE; ++PathI) {
1927 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
1928 *PathI))
1929 return false;
1930 Type = (*PathI)->getType();
1931 }
1932
1933 return true;
1934 }
1935 }
1936 }
1937};
1938}
1939
1940//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001941// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001942//
1943// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1944// function designators (in C), decl references to void objects (in C), and
1945// temporaries (if building with -Wno-address-of-temporary).
1946//
1947// LValue evaluation produces values comprising a base expression of one of the
1948// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00001949// - Declarations
1950// * VarDecl
1951// * FunctionDecl
1952// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00001953// * CompoundLiteralExpr in C
1954// * StringLiteral
1955// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00001956// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00001957// * ObjCEncodeExpr
1958// * AddrLabelExpr
1959// * BlockExpr
1960// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00001961// - Locals and temporaries
1962// * Any Expr, with a Frame indicating the function in which the temporary was
1963// evaluated.
1964// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00001965//===----------------------------------------------------------------------===//
1966namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001967class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00001968 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00001969public:
Richard Smith027bf112011-11-17 22:56:20 +00001970 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
1971 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00001972
Richard Smith11562c52011-10-28 17:51:58 +00001973 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1974
Peter Collingbournee9200682011-05-13 03:29:01 +00001975 bool VisitDeclRefExpr(const DeclRefExpr *E);
1976 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001977 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001978 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1979 bool VisitMemberExpr(const MemberExpr *E);
1980 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1981 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1982 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1983 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001984
Peter Collingbournee9200682011-05-13 03:29:01 +00001985 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00001986 switch (E->getCastKind()) {
1987 default:
Richard Smith027bf112011-11-17 22:56:20 +00001988 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00001989
Eli Friedmance3e02a2011-10-11 00:13:24 +00001990 case CK_LValueBitCast:
Richard Smith96e0c102011-11-04 02:25:55 +00001991 if (!Visit(E->getSubExpr()))
1992 return false;
1993 Result.Designator.setInvalid();
1994 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00001995
Richard Smith027bf112011-11-17 22:56:20 +00001996 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00001997 if (!Visit(E->getSubExpr()))
1998 return false;
Richard Smith027bf112011-11-17 22:56:20 +00001999 if (!CheckValidLValue())
2000 return false;
2001 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002002 }
2003 }
Sebastian Redl12757ab2011-09-24 17:48:14 +00002004
Eli Friedman449fe542009-03-23 04:56:01 +00002005 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +00002006
Eli Friedman9a156e52008-11-12 09:44:48 +00002007};
2008} // end anonymous namespace
2009
Richard Smith11562c52011-10-28 17:51:58 +00002010/// Evaluate an expression as an lvalue. This can be legitimately called on
2011/// expressions which are not glvalues, in a few cases:
2012/// * function designators in C,
2013/// * "extern void" objects,
2014/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002015static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002016 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2017 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2018 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002019 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002020}
2021
Peter Collingbournee9200682011-05-13 03:29:01 +00002022bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2024 return Success(FD);
2025 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002026 return VisitVarDecl(E, VD);
2027 return Error(E);
2028}
Richard Smith733237d2011-10-24 23:14:33 +00002029
Richard Smith11562c52011-10-28 17:51:58 +00002030bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002031 if (!VD->getType()->isReferenceType()) {
2032 if (isa<ParmVarDecl>(VD)) {
Richard Smithce40ad62011-11-12 22:28:03 +00002033 Result.set(VD, Info.CurrentCall);
Richard Smithfec09922011-11-01 16:57:24 +00002034 return true;
2035 }
Richard Smithce40ad62011-11-12 22:28:03 +00002036 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002037 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002038
Richard Smith0b0a0b62011-10-29 20:57:55 +00002039 CCValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002040 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2041 return false;
2042 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002043}
2044
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002045bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2046 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002047 if (E->GetTemporaryExpr()->isRValue()) {
2048 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2049 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2050
2051 Result.set(E, Info.CurrentCall);
2052 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2053 Result, E->GetTemporaryExpr());
2054 }
2055
2056 // Materialization of an lvalue temporary occurs when we need to force a copy
2057 // (for instance, if it's a bitfield).
2058 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2059 if (!Visit(E->GetTemporaryExpr()))
2060 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002061 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002062 Info.CurrentCall->Temporaries[E]))
2063 return false;
Richard Smithce40ad62011-11-12 22:28:03 +00002064 Result.set(E, Info.CurrentCall);
Richard Smith027bf112011-11-17 22:56:20 +00002065 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002066}
2067
Peter Collingbournee9200682011-05-13 03:29:01 +00002068bool
2069LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002070 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2071 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2072 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002073 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002074}
2075
Peter Collingbournee9200682011-05-13 03:29:01 +00002076bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002077 // Handle static data members.
2078 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2079 VisitIgnoredValue(E->getBase());
2080 return VisitVarDecl(E, VD);
2081 }
2082
Richard Smith254a73d2011-10-28 22:34:42 +00002083 // Handle static member functions.
2084 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2085 if (MD->isStatic()) {
2086 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002087 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002088 }
2089 }
2090
Richard Smithd62306a2011-11-10 06:34:14 +00002091 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002092 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002093}
2094
Peter Collingbournee9200682011-05-13 03:29:01 +00002095bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002096 // FIXME: Deal with vectors as array subscript bases.
2097 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002098 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002099
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002100 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002101 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002102
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002103 APSInt Index;
2104 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002105 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002106 int64_t IndexValue
2107 = Index.isSigned() ? Index.getSExtValue()
2108 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002109
Richard Smith027bf112011-11-17 22:56:20 +00002110 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002111 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002112}
Eli Friedman9a156e52008-11-12 09:44:48 +00002113
Peter Collingbournee9200682011-05-13 03:29:01 +00002114bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002115 // FIXME: In C++11, require the result to be a valid lvalue.
John McCall45d55e42010-05-07 21:00:08 +00002116 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002117}
2118
Eli Friedman9a156e52008-11-12 09:44:48 +00002119//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002120// Pointer Evaluation
2121//===----------------------------------------------------------------------===//
2122
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002123namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002124class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002125 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002126 LValue &Result;
2127
Peter Collingbournee9200682011-05-13 03:29:01 +00002128 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002129 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002130 return true;
2131 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002132public:
Mike Stump11289f42009-09-09 15:08:12 +00002133
John McCall45d55e42010-05-07 21:00:08 +00002134 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002135 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002136
Richard Smith0b0a0b62011-10-29 20:57:55 +00002137 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002138 Result.setFrom(V);
2139 return true;
2140 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002141 bool ValueInitialization(const Expr *E) {
2142 return Success((Expr*)0);
2143 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002144
John McCall45d55e42010-05-07 21:00:08 +00002145 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002146 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002147 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002148 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00002149 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002150 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00002151 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002152 bool VisitCallExpr(const CallExpr *E);
2153 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00002154 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00002155 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002156 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00002157 }
Richard Smithd62306a2011-11-10 06:34:14 +00002158 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2159 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002160 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002161 Result = *Info.CurrentCall->This;
2162 return true;
2163 }
John McCallc07a0c72011-02-17 10:25:35 +00002164
Eli Friedman449fe542009-03-23 04:56:01 +00002165 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002166};
Chris Lattner05706e882008-07-11 18:11:29 +00002167} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002168
John McCall45d55e42010-05-07 21:00:08 +00002169static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002170 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00002171 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00002172}
2173
John McCall45d55e42010-05-07 21:00:08 +00002174bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002175 if (E->getOpcode() != BO_Add &&
2176 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00002177 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Chris Lattner05706e882008-07-11 18:11:29 +00002179 const Expr *PExp = E->getLHS();
2180 const Expr *IExp = E->getRHS();
2181 if (IExp->getType()->isPointerType())
2182 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00002183
John McCall45d55e42010-05-07 21:00:08 +00002184 if (!EvaluatePointer(PExp, Result, Info))
2185 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002186
John McCall45d55e42010-05-07 21:00:08 +00002187 llvm::APSInt Offset;
2188 if (!EvaluateInteger(IExp, Offset, Info))
2189 return false;
2190 int64_t AdditionalOffset
2191 = Offset.isSigned() ? Offset.getSExtValue()
2192 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00002193 if (E->getOpcode() == BO_Sub)
2194 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00002195
Richard Smithd62306a2011-11-10 06:34:14 +00002196 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smith027bf112011-11-17 22:56:20 +00002197 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smithd62306a2011-11-10 06:34:14 +00002198 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00002199}
Eli Friedman9a156e52008-11-12 09:44:48 +00002200
John McCall45d55e42010-05-07 21:00:08 +00002201bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2202 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002203}
Mike Stump11289f42009-09-09 15:08:12 +00002204
Peter Collingbournee9200682011-05-13 03:29:01 +00002205bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2206 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00002207
Eli Friedman847a2bc2009-12-27 05:43:15 +00002208 switch (E->getCastKind()) {
2209 default:
2210 break;
2211
John McCalle3027922010-08-25 11:45:40 +00002212 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002213 case CK_CPointerToObjCPointerCast:
2214 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002215 case CK_AnyPointerToBlockPointerCast:
Richard Smith96e0c102011-11-04 02:25:55 +00002216 if (!Visit(SubExpr))
2217 return false;
2218 Result.Designator.setInvalid();
2219 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00002220
Anders Carlsson18275092010-10-31 20:41:46 +00002221 case CK_DerivedToBase:
2222 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002223 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00002224 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002225 if (!Result.Base && Result.Offset.isZero())
2226 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00002227
Richard Smithd62306a2011-11-10 06:34:14 +00002228 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00002229 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00002230 QualType Type =
2231 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00002232
Richard Smithd62306a2011-11-10 06:34:14 +00002233 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00002234 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithd62306a2011-11-10 06:34:14 +00002235 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00002236 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002237 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00002238 }
2239
Anders Carlsson18275092010-10-31 20:41:46 +00002240 return true;
2241 }
2242
Richard Smith027bf112011-11-17 22:56:20 +00002243 case CK_BaseToDerived:
2244 if (!Visit(E->getSubExpr()))
2245 return false;
2246 if (!Result.Base && Result.Offset.isZero())
2247 return true;
2248 return HandleBaseToDerivedCast(Info, E, Result);
2249
Richard Smith0b0a0b62011-10-29 20:57:55 +00002250 case CK_NullToPointer:
2251 return ValueInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00002252
John McCalle3027922010-08-25 11:45:40 +00002253 case CK_IntegralToPointer: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002254 CCValue Value;
John McCall45d55e42010-05-07 21:00:08 +00002255 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00002256 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00002257
John McCall45d55e42010-05-07 21:00:08 +00002258 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002259 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2260 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00002261 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00002262 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithfec09922011-11-01 16:57:24 +00002263 Result.Frame = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00002264 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00002265 return true;
2266 } else {
2267 // Cast is of an lvalue, no need to change value.
Richard Smith0b0a0b62011-10-29 20:57:55 +00002268 Result.setFrom(Value);
John McCall45d55e42010-05-07 21:00:08 +00002269 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00002270 }
2271 }
John McCalle3027922010-08-25 11:45:40 +00002272 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00002273 if (SubExpr->isGLValue()) {
2274 if (!EvaluateLValue(SubExpr, Result, Info))
2275 return false;
2276 } else {
2277 Result.set(SubExpr, Info.CurrentCall);
2278 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2279 Info, Result, SubExpr))
2280 return false;
2281 }
Richard Smith96e0c102011-11-04 02:25:55 +00002282 // The result is a pointer to the first element of the array.
2283 Result.Designator.addIndex(0);
2284 return true;
Richard Smithdd785442011-10-31 20:57:44 +00002285
John McCalle3027922010-08-25 11:45:40 +00002286 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00002287 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00002288 }
2289
Richard Smith11562c52011-10-28 17:51:58 +00002290 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00002291}
Chris Lattner05706e882008-07-11 18:11:29 +00002292
Peter Collingbournee9200682011-05-13 03:29:01 +00002293bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00002294 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00002295 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00002296
Peter Collingbournee9200682011-05-13 03:29:01 +00002297 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002298}
Chris Lattner05706e882008-07-11 18:11:29 +00002299
2300//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002301// Member Pointer Evaluation
2302//===----------------------------------------------------------------------===//
2303
2304namespace {
2305class MemberPointerExprEvaluator
2306 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2307 MemberPtr &Result;
2308
2309 bool Success(const ValueDecl *D) {
2310 Result = MemberPtr(D);
2311 return true;
2312 }
2313public:
2314
2315 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2316 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2317
2318 bool Success(const CCValue &V, const Expr *E) {
2319 Result.setFrom(V);
2320 return true;
2321 }
Richard Smith027bf112011-11-17 22:56:20 +00002322 bool ValueInitialization(const Expr *E) {
2323 return Success((const ValueDecl*)0);
2324 }
2325
2326 bool VisitCastExpr(const CastExpr *E);
2327 bool VisitUnaryAddrOf(const UnaryOperator *E);
2328};
2329} // end anonymous namespace
2330
2331static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2332 EvalInfo &Info) {
2333 assert(E->isRValue() && E->getType()->isMemberPointerType());
2334 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2335}
2336
2337bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2338 switch (E->getCastKind()) {
2339 default:
2340 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2341
2342 case CK_NullToMemberPointer:
2343 return ValueInitialization(E);
2344
2345 case CK_BaseToDerivedMemberPointer: {
2346 if (!Visit(E->getSubExpr()))
2347 return false;
2348 if (E->path_empty())
2349 return true;
2350 // Base-to-derived member pointer casts store the path in derived-to-base
2351 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2352 // the wrong end of the derived->base arc, so stagger the path by one class.
2353 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2354 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2355 PathI != PathE; ++PathI) {
2356 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2357 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2358 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002359 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002360 }
2361 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2362 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002363 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002364 return true;
2365 }
2366
2367 case CK_DerivedToBaseMemberPointer:
2368 if (!Visit(E->getSubExpr()))
2369 return false;
2370 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2371 PathE = E->path_end(); PathI != PathE; ++PathI) {
2372 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2373 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2374 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002375 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002376 }
2377 return true;
2378 }
2379}
2380
2381bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2382 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2383 // member can be formed.
2384 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2385}
2386
2387//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00002388// Record Evaluation
2389//===----------------------------------------------------------------------===//
2390
2391namespace {
2392 class RecordExprEvaluator
2393 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2394 const LValue &This;
2395 APValue &Result;
2396 public:
2397
2398 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2399 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2400
2401 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002402 return CheckConstantExpression(Info, E, V, Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002403 }
Richard Smithd62306a2011-11-10 06:34:14 +00002404
Richard Smithe97cbd72011-11-11 04:05:33 +00002405 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00002406 bool VisitInitListExpr(const InitListExpr *E);
2407 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2408 };
2409}
2410
Richard Smithe97cbd72011-11-11 04:05:33 +00002411bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2412 switch (E->getCastKind()) {
2413 default:
2414 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2415
2416 case CK_ConstructorConversion:
2417 return Visit(E->getSubExpr());
2418
2419 case CK_DerivedToBase:
2420 case CK_UncheckedDerivedToBase: {
2421 CCValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002422 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00002423 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002424 if (!DerivedObject.isStruct())
2425 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00002426
2427 // Derived-to-base rvalue conversion: just slice off the derived part.
2428 APValue *Value = &DerivedObject;
2429 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2430 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2431 PathE = E->path_end(); PathI != PathE; ++PathI) {
2432 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2433 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2434 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2435 RD = Base;
2436 }
2437 Result = *Value;
2438 return true;
2439 }
2440 }
2441}
2442
Richard Smithd62306a2011-11-10 06:34:14 +00002443bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2444 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2445 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2446
2447 if (RD->isUnion()) {
2448 Result = APValue(E->getInitializedFieldInUnion());
2449 if (!E->getNumInits())
2450 return true;
2451 LValue Subobject = This;
2452 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2453 &Layout);
2454 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2455 Subobject, E->getInit(0));
2456 }
2457
2458 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2459 "initializer list for class with base classes");
2460 Result = APValue(APValue::UninitStruct(), 0,
2461 std::distance(RD->field_begin(), RD->field_end()));
2462 unsigned ElementNo = 0;
2463 for (RecordDecl::field_iterator Field = RD->field_begin(),
2464 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2465 // Anonymous bit-fields are not considered members of the class for
2466 // purposes of aggregate initialization.
2467 if (Field->isUnnamedBitfield())
2468 continue;
2469
2470 LValue Subobject = This;
2471 HandleLValueMember(Info, Subobject, *Field, &Layout);
2472
2473 if (ElementNo < E->getNumInits()) {
2474 if (!EvaluateConstantExpression(
2475 Result.getStructField((*Field)->getFieldIndex()),
2476 Info, Subobject, E->getInit(ElementNo++)))
2477 return false;
2478 } else {
2479 // Perform an implicit value-initialization for members beyond the end of
2480 // the initializer list.
2481 ImplicitValueInitExpr VIE(Field->getType());
2482 if (!EvaluateConstantExpression(
2483 Result.getStructField((*Field)->getFieldIndex()),
2484 Info, Subobject, &VIE))
2485 return false;
2486 }
2487 }
2488
2489 return true;
2490}
2491
2492bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2493 const CXXConstructorDecl *FD = E->getConstructor();
2494 const FunctionDecl *Definition = 0;
2495 FD->getBody(Definition);
2496
2497 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002498 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002499
2500 // FIXME: Elide the copy/move construction wherever we can.
2501 if (E->isElidable())
2502 if (const MaterializeTemporaryExpr *ME
2503 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2504 return Visit(ME->GetTemporaryExpr());
2505
2506 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002507 return HandleConstructorCall(E, This, Args,
2508 cast<CXXConstructorDecl>(Definition), Info,
2509 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00002510}
2511
2512static bool EvaluateRecord(const Expr *E, const LValue &This,
2513 APValue &Result, EvalInfo &Info) {
2514 assert(E->isRValue() && E->getType()->isRecordType() &&
2515 E->getType()->isLiteralType() &&
2516 "can't evaluate expression as a record rvalue");
2517 return RecordExprEvaluator(Info, This, Result).Visit(E);
2518}
2519
2520//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002521// Temporary Evaluation
2522//
2523// Temporaries are represented in the AST as rvalues, but generally behave like
2524// lvalues. The full-object of which the temporary is a subobject is implicitly
2525// materialized so that a reference can bind to it.
2526//===----------------------------------------------------------------------===//
2527namespace {
2528class TemporaryExprEvaluator
2529 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2530public:
2531 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2532 LValueExprEvaluatorBaseTy(Info, Result) {}
2533
2534 /// Visit an expression which constructs the value of this temporary.
2535 bool VisitConstructExpr(const Expr *E) {
2536 Result.set(E, Info.CurrentCall);
2537 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2538 Result, E);
2539 }
2540
2541 bool VisitCastExpr(const CastExpr *E) {
2542 switch (E->getCastKind()) {
2543 default:
2544 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2545
2546 case CK_ConstructorConversion:
2547 return VisitConstructExpr(E->getSubExpr());
2548 }
2549 }
2550 bool VisitInitListExpr(const InitListExpr *E) {
2551 return VisitConstructExpr(E);
2552 }
2553 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2554 return VisitConstructExpr(E);
2555 }
2556 bool VisitCallExpr(const CallExpr *E) {
2557 return VisitConstructExpr(E);
2558 }
2559};
2560} // end anonymous namespace
2561
2562/// Evaluate an expression of record type as a temporary.
2563static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2564 assert(E->isRValue() && E->getType()->isRecordType() &&
2565 E->getType()->isLiteralType());
2566 return TemporaryExprEvaluator(Info, Result).Visit(E);
2567}
2568
2569//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002570// Vector Evaluation
2571//===----------------------------------------------------------------------===//
2572
2573namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002574 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00002575 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2576 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002577 public:
Mike Stump11289f42009-09-09 15:08:12 +00002578
Richard Smith2d406342011-10-22 21:10:00 +00002579 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2580 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002581
Richard Smith2d406342011-10-22 21:10:00 +00002582 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2583 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2584 // FIXME: remove this APValue copy.
2585 Result = APValue(V.data(), V.size());
2586 return true;
2587 }
Richard Smithed5165f2011-11-04 05:33:44 +00002588 bool Success(const CCValue &V, const Expr *E) {
2589 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00002590 Result = V;
2591 return true;
2592 }
Richard Smith2d406342011-10-22 21:10:00 +00002593 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002594
Richard Smith2d406342011-10-22 21:10:00 +00002595 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00002596 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00002597 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00002598 bool VisitInitListExpr(const InitListExpr *E);
2599 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002600 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00002601 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00002602 // shufflevector, ExtVectorElementExpr
2603 // (Note that these require implementing conversions
2604 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002605 };
2606} // end anonymous namespace
2607
2608static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002609 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00002610 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002611}
2612
Richard Smith2d406342011-10-22 21:10:00 +00002613bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2614 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002615 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002616
Richard Smith161f09a2011-12-06 22:44:34 +00002617 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00002618 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002619
Eli Friedmanc757de22011-03-25 00:43:55 +00002620 switch (E->getCastKind()) {
2621 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00002622 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00002623 if (SETy->isIntegerType()) {
2624 APSInt IntResult;
2625 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002626 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002627 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00002628 } else if (SETy->isRealFloatingType()) {
2629 APFloat F(0.0);
2630 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002631 return false;
Richard Smith2d406342011-10-22 21:10:00 +00002632 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00002633 } else {
Richard Smith2d406342011-10-22 21:10:00 +00002634 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002635 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00002636
2637 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00002638 SmallVector<APValue, 4> Elts(NElts, Val);
2639 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00002640 }
Eli Friedmanc757de22011-03-25 00:43:55 +00002641 default:
Richard Smith11562c52011-10-28 17:51:58 +00002642 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002643 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002644}
2645
Richard Smith2d406342011-10-22 21:10:00 +00002646bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002647VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00002648 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002649 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00002650 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00002651
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002652 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002653 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002654
John McCall875679e2010-06-11 17:54:15 +00002655 // If a vector is initialized with a single element, that value
2656 // becomes every element of the vector, not just the first.
2657 // This is the behavior described in the IBM AltiVec documentation.
2658 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00002659
2660 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00002661 // vector (OpenCL 6.1.6).
2662 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00002663 return Visit(E->getInit(0));
2664
John McCall875679e2010-06-11 17:54:15 +00002665 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002666 if (EltTy->isIntegerType()) {
2667 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00002668 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002669 return false;
John McCall875679e2010-06-11 17:54:15 +00002670 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002671 } else {
2672 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00002673 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002674 return false;
John McCall875679e2010-06-11 17:54:15 +00002675 InitValue = APValue(f);
2676 }
2677 for (unsigned i = 0; i < NumElements; i++) {
2678 Elements.push_back(InitValue);
2679 }
2680 } else {
2681 for (unsigned i = 0; i < NumElements; i++) {
2682 if (EltTy->isIntegerType()) {
2683 llvm::APSInt sInt(32);
2684 if (i < NumInits) {
2685 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002686 return false;
John McCall875679e2010-06-11 17:54:15 +00002687 } else {
2688 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2689 }
2690 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00002691 } else {
John McCall875679e2010-06-11 17:54:15 +00002692 llvm::APFloat f(0.0);
2693 if (i < NumInits) {
2694 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002695 return false;
John McCall875679e2010-06-11 17:54:15 +00002696 } else {
2697 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2698 }
2699 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00002700 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002701 }
2702 }
Richard Smith2d406342011-10-22 21:10:00 +00002703 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002704}
2705
Richard Smith2d406342011-10-22 21:10:00 +00002706bool
2707VectorExprEvaluator::ValueInitialization(const Expr *E) {
2708 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00002709 QualType EltTy = VT->getElementType();
2710 APValue ZeroElement;
2711 if (EltTy->isIntegerType())
2712 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2713 else
2714 ZeroElement =
2715 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2716
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002717 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00002718 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002719}
2720
Richard Smith2d406342011-10-22 21:10:00 +00002721bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00002722 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00002723 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00002724}
2725
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002726//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00002727// Array Evaluation
2728//===----------------------------------------------------------------------===//
2729
2730namespace {
2731 class ArrayExprEvaluator
2732 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00002733 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00002734 APValue &Result;
2735 public:
2736
Richard Smithd62306a2011-11-10 06:34:14 +00002737 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2738 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00002739
2740 bool Success(const APValue &V, const Expr *E) {
2741 assert(V.isArray() && "Expected array type");
2742 Result = V;
2743 return true;
2744 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002745
Richard Smithd62306a2011-11-10 06:34:14 +00002746 bool ValueInitialization(const Expr *E) {
2747 const ConstantArrayType *CAT =
2748 Info.Ctx.getAsConstantArrayType(E->getType());
2749 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002750 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002751
2752 Result = APValue(APValue::UninitArray(), 0,
2753 CAT->getSize().getZExtValue());
2754 if (!Result.hasArrayFiller()) return true;
2755
2756 // Value-initialize all elements.
2757 LValue Subobject = This;
2758 Subobject.Designator.addIndex(0);
2759 ImplicitValueInitExpr VIE(CAT->getElementType());
2760 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2761 Subobject, &VIE);
2762 }
2763
Richard Smithf3e9e432011-11-07 09:22:26 +00002764 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00002765 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002766 };
2767} // end anonymous namespace
2768
Richard Smithd62306a2011-11-10 06:34:14 +00002769static bool EvaluateArray(const Expr *E, const LValue &This,
2770 APValue &Result, EvalInfo &Info) {
Richard Smithf3e9e432011-11-07 09:22:26 +00002771 assert(E->isRValue() && E->getType()->isArrayType() &&
2772 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00002773 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002774}
2775
2776bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2777 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2778 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002779 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00002780
2781 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2782 CAT->getSize().getZExtValue());
Richard Smithd62306a2011-11-10 06:34:14 +00002783 LValue Subobject = This;
2784 Subobject.Designator.addIndex(0);
2785 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00002786 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00002787 I != End; ++I, ++Index) {
2788 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2789 Info, Subobject, cast<Expr>(*I)))
Richard Smithf3e9e432011-11-07 09:22:26 +00002790 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002791 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2792 return false;
2793 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002794
2795 if (!Result.hasArrayFiller()) return true;
2796 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00002797 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2798 // but sometimes does:
2799 // struct S { constexpr S() : p(&p) {} void *p; };
2800 // S s[10] = {};
Richard Smithf3e9e432011-11-07 09:22:26 +00002801 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smithd62306a2011-11-10 06:34:14 +00002802 Subobject, E->getArrayFiller());
Richard Smithf3e9e432011-11-07 09:22:26 +00002803}
2804
Richard Smith027bf112011-11-17 22:56:20 +00002805bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2806 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2807 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002808 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002809
2810 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2811 if (!Result.hasArrayFiller())
2812 return true;
2813
2814 const CXXConstructorDecl *FD = E->getConstructor();
2815 const FunctionDecl *Definition = 0;
2816 FD->getBody(Definition);
2817
2818 if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002819 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002820
2821 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2822 // but sometimes does:
2823 // struct S { constexpr S() : p(&p) {} void *p; };
2824 // S s[10];
2825 LValue Subobject = This;
2826 Subobject.Designator.addIndex(0);
2827 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002828 return HandleConstructorCall(E, Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00002829 cast<CXXConstructorDecl>(Definition),
2830 Info, Result.getArrayFiller());
2831}
2832
Richard Smithf3e9e432011-11-07 09:22:26 +00002833//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002834// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002835//
2836// As a GNU extension, we support casting pointers to sufficiently-wide integer
2837// types and back in constant folding. Integer values are thus represented
2838// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00002839//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002840
2841namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002842class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002843 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002844 CCValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002845public:
Richard Smith0b0a0b62011-10-29 20:57:55 +00002846 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002847 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002848
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002849 bool Success(const llvm::APSInt &SI, const Expr *E) {
2850 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00002851 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002852 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002853 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00002854 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002855 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002856 Result = CCValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002857 return true;
2858 }
2859
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002860 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002861 assert(E->getType()->isIntegralOrEnumerationType() &&
2862 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002863 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002864 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002865 Result = CCValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002866 Result.getInt().setIsUnsigned(
2867 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002868 return true;
2869 }
2870
2871 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00002872 assert(E->getType()->isIntegralOrEnumerationType() &&
2873 "Invalid evaluation result.");
Richard Smith0b0a0b62011-10-29 20:57:55 +00002874 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002875 return true;
2876 }
2877
Ken Dyckdbc01912011-03-11 02:13:43 +00002878 bool Success(CharUnits Size, const Expr *E) {
2879 return Success(Size.getQuantity(), E);
2880 }
2881
Richard Smith0b0a0b62011-10-29 20:57:55 +00002882 bool Success(const CCValue &V, const Expr *E) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00002883 if (V.isLValue()) {
2884 Result = V;
2885 return true;
2886 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002887 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00002888 }
Mike Stump11289f42009-09-09 15:08:12 +00002889
Richard Smith4ce706a2011-10-11 21:43:33 +00002890 bool ValueInitialization(const Expr *E) { return Success(0, E); }
2891
Peter Collingbournee9200682011-05-13 03:29:01 +00002892 //===--------------------------------------------------------------------===//
2893 // Visitor Methods
2894 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002895
Chris Lattner7174bf32008-07-12 00:38:25 +00002896 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002897 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002898 }
2899 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002900 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00002901 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002902
2903 bool CheckReferencedDecl(const Expr *E, const Decl *D);
2904 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002905 if (CheckReferencedDecl(E, E->getDecl()))
2906 return true;
2907
2908 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002909 }
2910 bool VisitMemberExpr(const MemberExpr *E) {
2911 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00002912 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002913 return true;
2914 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002915
2916 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002917 }
2918
Peter Collingbournee9200682011-05-13 03:29:01 +00002919 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002920 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00002921 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00002922 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00002923
Peter Collingbournee9200682011-05-13 03:29:01 +00002924 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002925 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00002926
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002927 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002928 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Richard Smith4ce706a2011-10-11 21:43:33 +00002931 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00002932 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002933 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002934 }
2935
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002936 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002937 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002938 }
2939
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002940 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2941 return Success(E->getValue(), E);
2942 }
2943
John Wiegley6242b6a2011-04-28 00:16:57 +00002944 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2945 return Success(E->getValue(), E);
2946 }
2947
John Wiegleyf9f65842011-04-25 06:54:41 +00002948 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2949 return Success(E->getValue(), E);
2950 }
2951
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002952 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002953 bool VisitUnaryImag(const UnaryOperator *E);
2954
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002955 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002956 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002957
Chris Lattnerf8d7f722008-07-11 21:24:13 +00002958private:
Ken Dyck160146e2010-01-27 17:10:57 +00002959 CharUnits GetAlignOfExpr(const Expr *E);
2960 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00002961 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00002962 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00002963 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00002964};
Chris Lattner05706e882008-07-11 18:11:29 +00002965} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002966
Richard Smith11562c52011-10-28 17:51:58 +00002967/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2968/// produce either the integer value or a pointer.
2969///
2970/// GCC has a heinous extension which folds casts between pointer types and
2971/// pointer-sized integral types. We support this by allowing the evaluation of
2972/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2973/// Some simple arithmetic on such values is supported (they are treated much
2974/// like char*).
Richard Smithf57d8cb2011-12-09 22:58:01 +00002975static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00002976 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002977 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002978 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00002979}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002980
Richard Smithf57d8cb2011-12-09 22:58:01 +00002981static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00002982 CCValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002983 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00002984 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002985 if (!Val.isInt()) {
2986 // FIXME: It would be better to produce the diagnostic for casting
2987 // a pointer to an integer.
Richard Smith92b1ce02011-12-12 09:28:41 +00002988 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002989 return false;
2990 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002991 Result = Val.getInt();
2992 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002993}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00002994
Richard Smithf57d8cb2011-12-09 22:58:01 +00002995/// Check whether the given declaration can be directly converted to an integral
2996/// rvalue. If not, no diagnostic is produced; there are other things we can
2997/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00002998bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00002999 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003000 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003001 // Check for signedness/width mismatches between E type and ECD value.
3002 bool SameSign = (ECD->getInitVal().isSigned()
3003 == E->getType()->isSignedIntegerOrEnumerationType());
3004 bool SameWidth = (ECD->getInitVal().getBitWidth()
3005 == Info.Ctx.getIntWidth(E->getType()));
3006 if (SameSign && SameWidth)
3007 return Success(ECD->getInitVal(), E);
3008 else {
3009 // Get rid of mismatch (otherwise Success assertions will fail)
3010 // by computing a new value matching the type of E.
3011 llvm::APSInt Val = ECD->getInitVal();
3012 if (!SameSign)
3013 Val.setIsSigned(!ECD->getInitVal().isSigned());
3014 if (!SameWidth)
3015 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3016 return Success(Val, E);
3017 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00003018 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003019 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00003020}
3021
Chris Lattner86ee2862008-10-06 06:40:35 +00003022/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3023/// as GCC.
3024static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3025 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003026 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00003027 enum gcc_type_class {
3028 no_type_class = -1,
3029 void_type_class, integer_type_class, char_type_class,
3030 enumeral_type_class, boolean_type_class,
3031 pointer_type_class, reference_type_class, offset_type_class,
3032 real_type_class, complex_type_class,
3033 function_type_class, method_type_class,
3034 record_type_class, union_type_class,
3035 array_type_class, string_type_class,
3036 lang_type_class
3037 };
Mike Stump11289f42009-09-09 15:08:12 +00003038
3039 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00003040 // ideal, however it is what gcc does.
3041 if (E->getNumArgs() == 0)
3042 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00003043
Chris Lattner86ee2862008-10-06 06:40:35 +00003044 QualType ArgTy = E->getArg(0)->getType();
3045 if (ArgTy->isVoidType())
3046 return void_type_class;
3047 else if (ArgTy->isEnumeralType())
3048 return enumeral_type_class;
3049 else if (ArgTy->isBooleanType())
3050 return boolean_type_class;
3051 else if (ArgTy->isCharType())
3052 return string_type_class; // gcc doesn't appear to use char_type_class
3053 else if (ArgTy->isIntegerType())
3054 return integer_type_class;
3055 else if (ArgTy->isPointerType())
3056 return pointer_type_class;
3057 else if (ArgTy->isReferenceType())
3058 return reference_type_class;
3059 else if (ArgTy->isRealType())
3060 return real_type_class;
3061 else if (ArgTy->isComplexType())
3062 return complex_type_class;
3063 else if (ArgTy->isFunctionType())
3064 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00003065 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00003066 return record_type_class;
3067 else if (ArgTy->isUnionType())
3068 return union_type_class;
3069 else if (ArgTy->isArrayType())
3070 return array_type_class;
3071 else if (ArgTy->isUnionType())
3072 return union_type_class;
3073 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00003074 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00003075 return -1;
3076}
3077
John McCall95007602010-05-10 23:27:23 +00003078/// Retrieves the "underlying object type" of the given expression,
3079/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00003080QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3081 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3082 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00003083 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00003084 } else if (const Expr *E = B.get<const Expr*>()) {
3085 if (isa<CompoundLiteralExpr>(E))
3086 return E->getType();
John McCall95007602010-05-10 23:27:23 +00003087 }
3088
3089 return QualType();
3090}
3091
Peter Collingbournee9200682011-05-13 03:29:01 +00003092bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00003093 // TODO: Perhaps we should let LLVM lower this?
3094 LValue Base;
3095 if (!EvaluatePointer(E->getArg(0), Base, Info))
3096 return false;
3097
3098 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00003099 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00003100
Richard Smithce40ad62011-11-12 22:28:03 +00003101 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00003102 if (T.isNull() ||
3103 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00003104 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00003105 T->isVariablyModifiedType() ||
3106 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003107 return Error(E);
John McCall95007602010-05-10 23:27:23 +00003108
3109 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3110 CharUnits Offset = Base.getLValueOffset();
3111
3112 if (!Offset.isNegative() && Offset <= Size)
3113 Size -= Offset;
3114 else
3115 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00003116 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00003117}
3118
Peter Collingbournee9200682011-05-13 03:29:01 +00003119bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003120 switch (E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003121 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00003122 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003123
3124 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00003125 if (TryEvaluateBuiltinObjectSize(E))
3126 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00003127
Eric Christopher99469702010-01-19 22:58:35 +00003128 // If evaluating the argument has side-effects we can't determine
3129 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00003130 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00003131 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00003132 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00003133 return Success(0, E);
3134 }
Mike Stump876387b2009-10-27 22:09:17 +00003135
Richard Smithf57d8cb2011-12-09 22:58:01 +00003136 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00003137 }
3138
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003139 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003140 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00003141
Richard Smith10c7c902011-12-09 02:04:48 +00003142 case Builtin::BI__builtin_constant_p: {
3143 const Expr *Arg = E->getArg(0);
3144 QualType ArgType = Arg->getType();
3145 // __builtin_constant_p always has one operand. The rules which gcc follows
3146 // are not precisely documented, but are as follows:
3147 //
3148 // - If the operand is of integral, floating, complex or enumeration type,
3149 // and can be folded to a known value of that type, it returns 1.
3150 // - If the operand and can be folded to a pointer to the first character
3151 // of a string literal (or such a pointer cast to an integral type), it
3152 // returns 1.
3153 //
3154 // Otherwise, it returns 0.
3155 //
3156 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3157 // its support for this does not currently work.
3158 int IsConstant = 0;
3159 if (ArgType->isIntegralOrEnumerationType()) {
3160 // Note, a pointer cast to an integral type is only a constant if it is
3161 // a pointer to the first character of a string literal.
3162 Expr::EvalResult Result;
3163 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3164 APValue &V = Result.Val;
3165 if (V.getKind() == APValue::LValue) {
3166 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3167 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3168 } else {
3169 IsConstant = 1;
3170 }
3171 }
3172 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3173 IsConstant = Arg->isEvaluatable(Info.Ctx);
3174 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3175 LValue LV;
3176 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3177 // during the check.
3178 Expr::EvalStatus Status;
3179 EvalInfo SubInfo(Info.Ctx, Status);
3180 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3181 : EvaluatePointer(Arg, LV, SubInfo)) &&
3182 !Status.HasSideEffects)
3183 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3184 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3185 }
3186
3187 return Success(IsConstant, E);
3188 }
Chris Lattnerd545ad12009-09-23 06:06:36 +00003189 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00003190 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00003191 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00003192 return Success(Operand, E);
3193 }
Eli Friedmand5c93992010-02-13 00:10:10 +00003194
3195 case Builtin::BI__builtin_expect:
3196 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003197
3198 case Builtin::BIstrlen:
3199 case Builtin::BI__builtin_strlen:
3200 // As an extension, we support strlen() and __builtin_strlen() as constant
3201 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00003202 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003203 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3204 // The string literal may have embedded null characters. Find the first
3205 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003206 StringRef Str = S->getString();
3207 StringRef::size_type Pos = Str.find(0);
3208 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00003209 Str = Str.substr(0, Pos);
3210
3211 return Success(Str.size(), E);
3212 }
3213
Richard Smithf57d8cb2011-12-09 22:58:01 +00003214 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003215
3216 case Builtin::BI__atomic_is_lock_free: {
3217 APSInt SizeVal;
3218 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3219 return false;
3220
3221 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3222 // of two less than the maximum inline atomic width, we know it is
3223 // lock-free. If the size isn't a power of two, or greater than the
3224 // maximum alignment where we promote atomics, we know it is not lock-free
3225 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3226 // the answer can only be determined at runtime; for example, 16-byte
3227 // atomics have lock-free implementations on some, but not all,
3228 // x86-64 processors.
3229
3230 // Check power-of-two.
3231 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3232 if (!Size.isPowerOfTwo())
3233#if 0
3234 // FIXME: Suppress this folding until the ABI for the promotion width
3235 // settles.
3236 return Success(0, E);
3237#else
Richard Smithf57d8cb2011-12-09 22:58:01 +00003238 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003239#endif
3240
3241#if 0
3242 // Check against promotion width.
3243 // FIXME: Suppress this folding until the ABI for the promotion width
3244 // settles.
3245 unsigned PromoteWidthBits =
3246 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3247 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3248 return Success(0, E);
3249#endif
3250
3251 // Check against inlining width.
3252 unsigned InlineWidthBits =
3253 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3254 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3255 return Success(1, E);
3256
Richard Smithf57d8cb2011-12-09 22:58:01 +00003257 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00003258 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003259 }
Chris Lattner7174bf32008-07-12 00:38:25 +00003260}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003261
Richard Smith8b3497e2011-10-31 01:37:14 +00003262static bool HasSameBase(const LValue &A, const LValue &B) {
3263 if (!A.getLValueBase())
3264 return !B.getLValueBase();
3265 if (!B.getLValueBase())
3266 return false;
3267
Richard Smithce40ad62011-11-12 22:28:03 +00003268 if (A.getLValueBase().getOpaqueValue() !=
3269 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003270 const Decl *ADecl = GetLValueBaseDecl(A);
3271 if (!ADecl)
3272 return false;
3273 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00003274 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00003275 return false;
3276 }
3277
3278 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithfec09922011-11-01 16:57:24 +00003279 A.getLValueFrame() == B.getLValueFrame();
Richard Smith8b3497e2011-10-31 01:37:14 +00003280}
3281
Chris Lattnere13042c2008-07-11 19:10:17 +00003282bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00003283 if (E->isAssignmentOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003284 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003285
John McCalle3027922010-08-25 11:45:40 +00003286 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00003287 VisitIgnoredValue(E->getLHS());
3288 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00003289 }
3290
3291 if (E->isLogicalOp()) {
3292 // These need to be handled specially because the operands aren't
3293 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003294 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00003295
Richard Smith11562c52011-10-28 17:51:58 +00003296 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00003297 // We were able to evaluate the LHS, see if we can get away with not
3298 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00003299 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003300 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003301
Richard Smith11562c52011-10-28 17:51:58 +00003302 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00003303 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003304 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003305 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003306 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003307 }
3308 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003309 // FIXME: If both evaluations fail, we should produce the diagnostic from
3310 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3311 // less clear how to diagnose this.
Richard Smith11562c52011-10-28 17:51:58 +00003312 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00003313 // We can't evaluate the LHS; however, sometimes the result
3314 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003315 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003316 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00003317 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00003318 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003319
3320 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00003321 }
3322 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00003323 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00003324
Eli Friedman5a332ea2008-11-13 06:09:17 +00003325 return false;
3326 }
3327
Anders Carlssonacc79812008-11-16 07:17:21 +00003328 QualType LHSTy = E->getLHS()->getType();
3329 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003330
3331 if (LHSTy->isAnyComplexType()) {
3332 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00003333 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003334
3335 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3336 return false;
3337
3338 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3339 return false;
3340
3341 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00003342 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003343 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00003344 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003345 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3346
John McCalle3027922010-08-25 11:45:40 +00003347 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003348 return Success((CR_r == APFloat::cmpEqual &&
3349 CR_i == APFloat::cmpEqual), E);
3350 else {
John McCalle3027922010-08-25 11:45:40 +00003351 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003352 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00003353 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003354 CR_r == APFloat::cmpLessThan ||
3355 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00003356 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00003357 CR_i == APFloat::cmpLessThan ||
3358 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003359 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003360 } else {
John McCalle3027922010-08-25 11:45:40 +00003361 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003362 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3363 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3364 else {
John McCalle3027922010-08-25 11:45:40 +00003365 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003366 "Invalid compex comparison.");
3367 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3368 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3369 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00003370 }
3371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
Anders Carlssonacc79812008-11-16 07:17:21 +00003373 if (LHSTy->isRealFloatingType() &&
3374 RHSTy->isRealFloatingType()) {
3375 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00003376
Anders Carlssonacc79812008-11-16 07:17:21 +00003377 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3378 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003379
Anders Carlssonacc79812008-11-16 07:17:21 +00003380 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3381 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003382
Anders Carlssonacc79812008-11-16 07:17:21 +00003383 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00003384
Anders Carlssonacc79812008-11-16 07:17:21 +00003385 switch (E->getOpcode()) {
3386 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003387 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00003388 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003389 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00003390 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003391 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00003392 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003393 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003394 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00003395 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003396 E);
John McCalle3027922010-08-25 11:45:40 +00003397 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003398 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00003399 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00003400 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00003401 || CR == APFloat::cmpLessThan
3402 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00003403 }
Anders Carlssonacc79812008-11-16 07:17:21 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Eli Friedmana38da572009-04-28 19:17:36 +00003406 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00003407 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCall45d55e42010-05-07 21:00:08 +00003408 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003409 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3410 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003411
John McCall45d55e42010-05-07 21:00:08 +00003412 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003413 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3414 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003415
Richard Smith8b3497e2011-10-31 01:37:14 +00003416 // Reject differing bases from the normal codepath; we special-case
3417 // comparisons to null.
3418 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith83c68212011-10-31 05:11:32 +00003419 // Inequalities and subtractions between unrelated pointers have
3420 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00003421 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003422 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003423 // A constant address may compare equal to the address of a symbol.
3424 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00003425 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00003426 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3427 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003428 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003429 // It's implementation-defined whether distinct literals will have
Eli Friedman42fbd622011-10-31 22:54:30 +00003430 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smithe9e20dd32011-11-04 01:10:57 +00003431 // distinct. However, we do know that the address of a literal will be
3432 // non-null.
3433 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3434 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003435 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003436 // We can't tell whether weak symbols will end up pointing to the same
3437 // object.
3438 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003439 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00003440 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00003441 // (Note that clang defaults to -fmerge-all-constants, which can
3442 // lead to inconsistent results for comparisons involving the address
3443 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00003444 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00003445 }
Eli Friedman64004332009-03-23 04:38:34 +00003446
Richard Smithf3e9e432011-11-07 09:22:26 +00003447 // FIXME: Implement the C++11 restrictions:
3448 // - Pointer subtractions must be on elements of the same array.
3449 // - Pointer comparisons must be between members with the same access.
3450
John McCalle3027922010-08-25 11:45:40 +00003451 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00003452 QualType Type = E->getLHS()->getType();
3453 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003454
Richard Smithd62306a2011-11-10 06:34:14 +00003455 CharUnits ElementSize;
3456 if (!HandleSizeof(Info, ElementType, ElementSize))
3457 return false;
Eli Friedman64004332009-03-23 04:38:34 +00003458
Richard Smithd62306a2011-11-10 06:34:14 +00003459 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dyck02990832010-01-15 12:37:54 +00003460 RHSValue.getLValueOffset();
3461 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003462 }
Richard Smith8b3497e2011-10-31 01:37:14 +00003463
3464 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3465 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3466 switch (E->getOpcode()) {
3467 default: llvm_unreachable("missing comparison operator");
3468 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3469 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3470 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3471 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3472 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3473 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmana38da572009-04-28 19:17:36 +00003474 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00003475 }
3476 }
Douglas Gregorb90df602010-06-16 00:17:44 +00003477 if (!LHSTy->isIntegralOrEnumerationType() ||
3478 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smith027bf112011-11-17 22:56:20 +00003479 // We can't continue from here for non-integral types.
3480 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003481 }
3482
Anders Carlsson9c181652008-07-08 14:35:21 +00003483 // The LHS of a constant expr is always evaluated and needed.
Richard Smith0b0a0b62011-10-29 20:57:55 +00003484 CCValue LHSVal;
Richard Smith11562c52011-10-28 17:51:58 +00003485 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003486 return false;
Eli Friedmanbd840592008-07-27 05:46:18 +00003487
Richard Smith11562c52011-10-28 17:51:58 +00003488 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003489 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003490 CCValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00003491
3492 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00003493 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00003494 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3495 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00003496 if (E->getOpcode() == BO_Add)
Richard Smith0b0a0b62011-10-29 20:57:55 +00003497 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00003498 else
Richard Smith0b0a0b62011-10-29 20:57:55 +00003499 LHSVal.getLValueOffset() -= AdditionalOffset;
3500 Result = LHSVal;
Eli Friedman94c25c62009-03-24 01:14:50 +00003501 return true;
3502 }
3503
3504 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00003505 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00003506 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003507 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3508 LHSVal.getInt().getZExtValue());
3509 // Note that RHSVal is Result.
Eli Friedman94c25c62009-03-24 01:14:50 +00003510 return true;
3511 }
3512
3513 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00003514 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003515 return Error(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003516
Richard Smith11562c52011-10-28 17:51:58 +00003517 APSInt &LHS = LHSVal.getInt();
3518 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00003519
Anders Carlsson9c181652008-07-08 14:35:21 +00003520 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003521 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003522 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00003523 case BO_Mul: return Success(LHS * RHS, E);
3524 case BO_Add: return Success(LHS + RHS, E);
3525 case BO_Sub: return Success(LHS - RHS, E);
3526 case BO_And: return Success(LHS & RHS, E);
3527 case BO_Xor: return Success(LHS ^ RHS, E);
3528 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003529 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00003530 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003531 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003532 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003533 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00003534 if (RHS == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003535 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith11562c52011-10-28 17:51:58 +00003536 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00003537 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00003538 // During constant-folding, a negative shift is an opposite shift.
3539 if (RHS.isSigned() && RHS.isNegative()) {
3540 RHS = -RHS;
3541 goto shift_right;
3542 }
3543
3544 shift_left:
3545 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00003546 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3547 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003548 }
John McCalle3027922010-08-25 11:45:40 +00003549 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00003550 // During constant-folding, a negative shift is an opposite shift.
3551 if (RHS.isSigned() && RHS.isNegative()) {
3552 RHS = -RHS;
3553 goto shift_left;
3554 }
3555
3556 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00003557 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00003558 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3559 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003560 }
Mike Stump11289f42009-09-09 15:08:12 +00003561
Richard Smith11562c52011-10-28 17:51:58 +00003562 case BO_LT: return Success(LHS < RHS, E);
3563 case BO_GT: return Success(LHS > RHS, E);
3564 case BO_LE: return Success(LHS <= RHS, E);
3565 case BO_GE: return Success(LHS >= RHS, E);
3566 case BO_EQ: return Success(LHS == RHS, E);
3567 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00003568 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003569}
3570
Ken Dyck160146e2010-01-27 17:10:57 +00003571CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00003572 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3573 // the result is the size of the referenced type."
3574 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3575 // result shall be the alignment of the referenced type."
3576 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3577 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00003578
3579 // __alignof is defined to return the preferred alignment.
3580 return Info.Ctx.toCharUnitsFromBits(
3581 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00003582}
3583
Ken Dyck160146e2010-01-27 17:10:57 +00003584CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00003585 E = E->IgnoreParens();
3586
3587 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00003588 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00003589 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003590 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3591 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00003592
Chris Lattner68061312009-01-24 21:53:27 +00003593 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00003594 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3595 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00003596
Chris Lattner24aeeab2009-01-24 21:09:06 +00003597 return GetAlignOfType(E->getType());
3598}
3599
3600
Peter Collingbournee190dee2011-03-11 19:24:49 +00003601/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3602/// a result as the expression's type.
3603bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3604 const UnaryExprOrTypeTraitExpr *E) {
3605 switch(E->getKind()) {
3606 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00003607 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00003608 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003609 else
Ken Dyckdbc01912011-03-11 02:13:43 +00003610 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00003611 }
Eli Friedman64004332009-03-23 04:38:34 +00003612
Peter Collingbournee190dee2011-03-11 19:24:49 +00003613 case UETT_VecStep: {
3614 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00003615
Peter Collingbournee190dee2011-03-11 19:24:49 +00003616 if (Ty->isVectorType()) {
3617 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00003618
Peter Collingbournee190dee2011-03-11 19:24:49 +00003619 // The vec_step built-in functions that take a 3-component
3620 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3621 if (n == 3)
3622 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00003623
Peter Collingbournee190dee2011-03-11 19:24:49 +00003624 return Success(n, E);
3625 } else
3626 return Success(1, E);
3627 }
3628
3629 case UETT_SizeOf: {
3630 QualType SrcTy = E->getTypeOfArgument();
3631 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3632 // the result is the size of the referenced type."
3633 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3634 // result shall be the alignment of the referenced type."
3635 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3636 SrcTy = Ref->getPointeeType();
3637
Richard Smithd62306a2011-11-10 06:34:14 +00003638 CharUnits Sizeof;
3639 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00003640 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003641 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003642 }
3643 }
3644
3645 llvm_unreachable("unknown expr/type trait");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003646 return Error(E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00003647}
3648
Peter Collingbournee9200682011-05-13 03:29:01 +00003649bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00003650 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00003651 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00003652 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003653 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00003654 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00003655 for (unsigned i = 0; i != n; ++i) {
3656 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3657 switch (ON.getKind()) {
3658 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00003659 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00003660 APSInt IdxResult;
3661 if (!EvaluateInteger(Idx, IdxResult, Info))
3662 return false;
3663 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3664 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003665 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003666 CurrentType = AT->getElementType();
3667 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3668 Result += IdxResult.getSExtValue() * ElementSize;
3669 break;
3670 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003671
Douglas Gregor882211c2010-04-28 22:16:22 +00003672 case OffsetOfExpr::OffsetOfNode::Field: {
3673 FieldDecl *MemberDecl = ON.getField();
3674 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003675 if (!RT)
3676 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003677 RecordDecl *RD = RT->getDecl();
3678 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00003679 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00003680 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003681 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00003682 CurrentType = MemberDecl->getType().getNonReferenceType();
3683 break;
3684 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00003685
Douglas Gregor882211c2010-04-28 22:16:22 +00003686 case OffsetOfExpr::OffsetOfNode::Identifier:
3687 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003688 return Error(OOE);
3689
Douglas Gregord1702062010-04-29 00:18:15 +00003690 case OffsetOfExpr::OffsetOfNode::Base: {
3691 CXXBaseSpecifier *BaseSpec = ON.getBase();
3692 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00003693 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003694
3695 // Find the layout of the class whose base we are looking into.
3696 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00003697 if (!RT)
3698 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003699 RecordDecl *RD = RT->getDecl();
3700 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3701
3702 // Find the base class itself.
3703 CurrentType = BaseSpec->getType();
3704 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3705 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003706 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00003707
3708 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00003709 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00003710 break;
3711 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003712 }
3713 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003714 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00003715}
3716
Chris Lattnere13042c2008-07-11 19:10:17 +00003717bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003718 switch (E->getOpcode()) {
3719 default:
3720 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3721 // See C99 6.6p3.
3722 return Error(E);
3723 case UO_Extension:
3724 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3725 // If so, we could clear the diagnostic ID.
3726 return Visit(E->getSubExpr());
3727 case UO_Plus:
3728 // The result is just the value.
3729 return Visit(E->getSubExpr());
3730 case UO_Minus: {
3731 if (!Visit(E->getSubExpr()))
3732 return false;
3733 if (!Result.isInt()) return Error(E);
3734 return Success(-Result.getInt(), E);
3735 }
3736 case UO_Not: {
3737 if (!Visit(E->getSubExpr()))
3738 return false;
3739 if (!Result.isInt()) return Error(E);
3740 return Success(~Result.getInt(), E);
3741 }
3742 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00003743 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00003744 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00003745 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003746 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00003747 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003748 }
Anders Carlsson9c181652008-07-08 14:35:21 +00003749}
Mike Stump11289f42009-09-09 15:08:12 +00003750
Chris Lattner477c4be2008-07-12 01:15:53 +00003751/// HandleCast - This is used to evaluate implicit or explicit casts where the
3752/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00003753bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3754 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003755 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00003756 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00003757
Eli Friedmanc757de22011-03-25 00:43:55 +00003758 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00003759 case CK_BaseToDerived:
3760 case CK_DerivedToBase:
3761 case CK_UncheckedDerivedToBase:
3762 case CK_Dynamic:
3763 case CK_ToUnion:
3764 case CK_ArrayToPointerDecay:
3765 case CK_FunctionToPointerDecay:
3766 case CK_NullToPointer:
3767 case CK_NullToMemberPointer:
3768 case CK_BaseToDerivedMemberPointer:
3769 case CK_DerivedToBaseMemberPointer:
3770 case CK_ConstructorConversion:
3771 case CK_IntegralToPointer:
3772 case CK_ToVoid:
3773 case CK_VectorSplat:
3774 case CK_IntegralToFloating:
3775 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00003776 case CK_CPointerToObjCPointerCast:
3777 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003778 case CK_AnyPointerToBlockPointerCast:
3779 case CK_ObjCObjectLValueCast:
3780 case CK_FloatingRealToComplex:
3781 case CK_FloatingComplexToReal:
3782 case CK_FloatingComplexCast:
3783 case CK_FloatingComplexToIntegralComplex:
3784 case CK_IntegralRealToComplex:
3785 case CK_IntegralComplexCast:
3786 case CK_IntegralComplexToFloatingComplex:
3787 llvm_unreachable("invalid cast kind for integral value");
3788
Eli Friedman9faf2f92011-03-25 19:07:11 +00003789 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00003790 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00003791 case CK_LValueBitCast:
3792 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00003793 case CK_ARCProduceObject:
3794 case CK_ARCConsumeObject:
3795 case CK_ARCReclaimReturnedObject:
3796 case CK_ARCExtendBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003797 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003798
3799 case CK_LValueToRValue:
3800 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00003801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003802
3803 case CK_MemberPointerToBoolean:
3804 case CK_PointerToBoolean:
3805 case CK_IntegralToBoolean:
3806 case CK_FloatingToBoolean:
3807 case CK_FloatingComplexToBoolean:
3808 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00003809 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00003810 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00003811 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003812 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003813 }
3814
Eli Friedmanc757de22011-03-25 00:43:55 +00003815 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00003816 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00003817 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00003818
Eli Friedman742421e2009-02-20 01:15:07 +00003819 if (!Result.isInt()) {
3820 // Only allow casts of lvalues if they are lossless.
3821 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3822 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003823
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003824 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003825 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00003826 }
Mike Stump11289f42009-09-09 15:08:12 +00003827
Eli Friedmanc757de22011-03-25 00:43:55 +00003828 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00003829 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00003830 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00003831 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00003832
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003833 if (LV.getLValueBase()) {
3834 // Only allow based lvalue casts if they are lossless.
3835 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003836 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003837
Richard Smithcf74da72011-11-16 07:18:12 +00003838 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003839 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003840 return true;
3841 }
3842
Ken Dyck02990832010-01-15 12:37:54 +00003843 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3844 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00003845 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003846 }
Eli Friedman9a156e52008-11-12 09:44:48 +00003847
Eli Friedmanc757de22011-03-25 00:43:55 +00003848 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00003849 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003850 if (!EvaluateComplex(SubExpr, C, Info))
3851 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00003852 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00003853 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00003854
Eli Friedmanc757de22011-03-25 00:43:55 +00003855 case CK_FloatingToIntegral: {
3856 APFloat F(0.0);
3857 if (!EvaluateFloat(SubExpr, F, Info))
3858 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00003859
Eli Friedmanc757de22011-03-25 00:43:55 +00003860 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3861 }
3862 }
Mike Stump11289f42009-09-09 15:08:12 +00003863
Eli Friedmanc757de22011-03-25 00:43:55 +00003864 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00003865 return Error(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00003866}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003867
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003868bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3869 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003870 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003871 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3872 return false;
3873 if (!LV.isComplexInt())
3874 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003875 return Success(LV.getComplexIntReal(), E);
3876 }
3877
3878 return Visit(E->getSubExpr());
3879}
3880
Eli Friedman4e7a2412009-02-27 04:45:43 +00003881bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003882 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00003883 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003884 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
3885 return false;
3886 if (!LV.isComplexInt())
3887 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00003888 return Success(LV.getComplexIntImag(), E);
3889 }
3890
Richard Smith4a678122011-10-24 18:44:57 +00003891 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00003892 return Success(0, E);
3893}
3894
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003895bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3896 return Success(E->getPackLength(), E);
3897}
3898
Sebastian Redl5f0180d2010-09-10 20:55:47 +00003899bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3900 return Success(E->getValue(), E);
3901}
3902
Chris Lattner05706e882008-07-11 18:11:29 +00003903//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00003904// Float Evaluation
3905//===----------------------------------------------------------------------===//
3906
3907namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003908class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003909 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00003910 APFloat &Result;
3911public:
3912 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003913 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00003914
Richard Smith0b0a0b62011-10-29 20:57:55 +00003915 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003916 Result = V.getFloat();
3917 return true;
3918 }
Eli Friedman24c01542008-08-22 00:06:13 +00003919
Richard Smith4ce706a2011-10-11 21:43:33 +00003920 bool ValueInitialization(const Expr *E) {
3921 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3922 return true;
3923 }
3924
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003925 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003926
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00003927 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00003928 bool VisitBinaryOperator(const BinaryOperator *E);
3929 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003930 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00003931
John McCallb1fb0d32010-05-07 22:08:54 +00003932 bool VisitUnaryReal(const UnaryOperator *E);
3933 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00003934
John McCallb1fb0d32010-05-07 22:08:54 +00003935 // FIXME: Missing: array subscript of vector, member of vector,
3936 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00003937};
3938} // end anonymous namespace
3939
3940static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003941 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00003942 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00003943}
3944
Jay Foad39c79802011-01-12 09:06:06 +00003945static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00003946 QualType ResultTy,
3947 const Expr *Arg,
3948 bool SNaN,
3949 llvm::APFloat &Result) {
3950 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3951 if (!S) return false;
3952
3953 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3954
3955 llvm::APInt fill;
3956
3957 // Treat empty strings as if they were zero.
3958 if (S->getString().empty())
3959 fill = llvm::APInt(32, 0);
3960 else if (S->getString().getAsInteger(0, fill))
3961 return false;
3962
3963 if (SNaN)
3964 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3965 else
3966 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3967 return true;
3968}
3969
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003970bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003971 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003972 default:
3973 return ExprEvaluatorBaseTy::VisitCallExpr(E);
3974
Chris Lattner4deaa4e2008-10-06 05:28:25 +00003975 case Builtin::BI__builtin_huge_val:
3976 case Builtin::BI__builtin_huge_valf:
3977 case Builtin::BI__builtin_huge_vall:
3978 case Builtin::BI__builtin_inf:
3979 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003980 case Builtin::BI__builtin_infl: {
3981 const llvm::fltSemantics &Sem =
3982 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00003983 Result = llvm::APFloat::getInf(Sem);
3984 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00003985 }
Mike Stump11289f42009-09-09 15:08:12 +00003986
John McCall16291492010-02-28 13:00:19 +00003987 case Builtin::BI__builtin_nans:
3988 case Builtin::BI__builtin_nansf:
3989 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003990 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3991 true, Result))
3992 return Error(E);
3993 return true;
John McCall16291492010-02-28 13:00:19 +00003994
Chris Lattner0b7282e2008-10-06 06:31:58 +00003995 case Builtin::BI__builtin_nan:
3996 case Builtin::BI__builtin_nanf:
3997 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00003998 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00003999 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004000 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4001 false, Result))
4002 return Error(E);
4003 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004004
4005 case Builtin::BI__builtin_fabs:
4006 case Builtin::BI__builtin_fabsf:
4007 case Builtin::BI__builtin_fabsl:
4008 if (!EvaluateFloat(E->getArg(0), Result, Info))
4009 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004010
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004011 if (Result.isNegative())
4012 Result.changeSign();
4013 return true;
4014
Mike Stump11289f42009-09-09 15:08:12 +00004015 case Builtin::BI__builtin_copysign:
4016 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004017 case Builtin::BI__builtin_copysignl: {
4018 APFloat RHS(0.);
4019 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4020 !EvaluateFloat(E->getArg(1), RHS, Info))
4021 return false;
4022 Result.copySign(RHS);
4023 return true;
4024 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004025 }
4026}
4027
John McCallb1fb0d32010-05-07 22:08:54 +00004028bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004029 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4030 ComplexValue CV;
4031 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4032 return false;
4033 Result = CV.FloatReal;
4034 return true;
4035 }
4036
4037 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00004038}
4039
4040bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00004041 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4042 ComplexValue CV;
4043 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4044 return false;
4045 Result = CV.FloatImag;
4046 return true;
4047 }
4048
Richard Smith4a678122011-10-24 18:44:57 +00004049 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00004050 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4051 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00004052 return true;
4053}
4054
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004055bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004056 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004057 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004058 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00004059 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00004060 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00004061 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4062 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004063 Result.changeSign();
4064 return true;
4065 }
4066}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004067
Eli Friedman24c01542008-08-22 00:06:13 +00004068bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004069 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4070 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00004071
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00004072 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00004073 if (!EvaluateFloat(E->getLHS(), Result, Info))
4074 return false;
4075 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4076 return false;
4077
4078 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004079 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004080 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00004081 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4082 return true;
John McCalle3027922010-08-25 11:45:40 +00004083 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00004084 Result.add(RHS, APFloat::rmNearestTiesToEven);
4085 return true;
John McCalle3027922010-08-25 11:45:40 +00004086 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00004087 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4088 return true;
John McCalle3027922010-08-25 11:45:40 +00004089 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00004090 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4091 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00004092 }
4093}
4094
4095bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4096 Result = E->getValue();
4097 return true;
4098}
4099
Peter Collingbournee9200682011-05-13 03:29:01 +00004100bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4101 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00004102
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004103 switch (E->getCastKind()) {
4104 default:
Richard Smith11562c52011-10-28 17:51:58 +00004105 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004106
4107 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004108 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00004109 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00004110 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004111 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004112 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004113 return true;
4114 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004115
4116 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00004117 if (!Visit(SubExpr))
4118 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00004119 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
4120 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00004121 return true;
4122 }
John McCalld7646252010-11-14 08:17:51 +00004123
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004124 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00004125 ComplexValue V;
4126 if (!EvaluateComplex(SubExpr, V, Info))
4127 return false;
4128 Result = V.getComplexFloatReal();
4129 return true;
4130 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00004131 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004132
Richard Smithf57d8cb2011-12-09 22:58:01 +00004133 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004134}
4135
Eli Friedman24c01542008-08-22 00:06:13 +00004136//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004137// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00004138//===----------------------------------------------------------------------===//
4139
4140namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004141class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00004142 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00004143 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00004144
Anders Carlsson537969c2008-11-16 20:27:53 +00004145public:
John McCall93d91dc2010-05-07 17:22:02 +00004146 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004147 : ExprEvaluatorBaseTy(info), Result(Result) {}
4148
Richard Smith0b0a0b62011-10-29 20:57:55 +00004149 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004150 Result.setFrom(V);
4151 return true;
4152 }
Mike Stump11289f42009-09-09 15:08:12 +00004153
Anders Carlsson537969c2008-11-16 20:27:53 +00004154 //===--------------------------------------------------------------------===//
4155 // Visitor Methods
4156 //===--------------------------------------------------------------------===//
4157
Peter Collingbournee9200682011-05-13 03:29:01 +00004158 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00004159
Peter Collingbournee9200682011-05-13 03:29:01 +00004160 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00004161
John McCall93d91dc2010-05-07 17:22:02 +00004162 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004163 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004164 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00004165};
4166} // end anonymous namespace
4167
John McCall93d91dc2010-05-07 17:22:02 +00004168static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4169 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004170 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004171 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00004172}
4173
Peter Collingbournee9200682011-05-13 03:29:01 +00004174bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4175 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004176
4177 if (SubExpr->getType()->isRealFloatingType()) {
4178 Result.makeComplexFloat();
4179 APFloat &Imag = Result.FloatImag;
4180 if (!EvaluateFloat(SubExpr, Imag, Info))
4181 return false;
4182
4183 Result.FloatReal = APFloat(Imag.getSemantics());
4184 return true;
4185 } else {
4186 assert(SubExpr->getType()->isIntegerType() &&
4187 "Unexpected imaginary literal.");
4188
4189 Result.makeComplexInt();
4190 APSInt &Imag = Result.IntImag;
4191 if (!EvaluateInteger(SubExpr, Imag, Info))
4192 return false;
4193
4194 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4195 return true;
4196 }
4197}
4198
Peter Collingbournee9200682011-05-13 03:29:01 +00004199bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004200
John McCallfcef3cf2010-12-14 17:51:41 +00004201 switch (E->getCastKind()) {
4202 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004203 case CK_BaseToDerived:
4204 case CK_DerivedToBase:
4205 case CK_UncheckedDerivedToBase:
4206 case CK_Dynamic:
4207 case CK_ToUnion:
4208 case CK_ArrayToPointerDecay:
4209 case CK_FunctionToPointerDecay:
4210 case CK_NullToPointer:
4211 case CK_NullToMemberPointer:
4212 case CK_BaseToDerivedMemberPointer:
4213 case CK_DerivedToBaseMemberPointer:
4214 case CK_MemberPointerToBoolean:
4215 case CK_ConstructorConversion:
4216 case CK_IntegralToPointer:
4217 case CK_PointerToIntegral:
4218 case CK_PointerToBoolean:
4219 case CK_ToVoid:
4220 case CK_VectorSplat:
4221 case CK_IntegralCast:
4222 case CK_IntegralToBoolean:
4223 case CK_IntegralToFloating:
4224 case CK_FloatingToIntegral:
4225 case CK_FloatingToBoolean:
4226 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00004227 case CK_CPointerToObjCPointerCast:
4228 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004229 case CK_AnyPointerToBlockPointerCast:
4230 case CK_ObjCObjectLValueCast:
4231 case CK_FloatingComplexToReal:
4232 case CK_FloatingComplexToBoolean:
4233 case CK_IntegralComplexToReal:
4234 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00004235 case CK_ARCProduceObject:
4236 case CK_ARCConsumeObject:
4237 case CK_ARCReclaimReturnedObject:
4238 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00004239 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00004240
John McCallfcef3cf2010-12-14 17:51:41 +00004241 case CK_LValueToRValue:
4242 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00004243 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004244
4245 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00004246 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00004247 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004248 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00004249
4250 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004251 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00004252 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004253 return false;
4254
John McCallfcef3cf2010-12-14 17:51:41 +00004255 Result.makeComplexFloat();
4256 Result.FloatImag = APFloat(Real.getSemantics());
4257 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004258 }
4259
John McCallfcef3cf2010-12-14 17:51:41 +00004260 case CK_FloatingComplexCast: {
4261 if (!Visit(E->getSubExpr()))
4262 return false;
4263
4264 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4265 QualType From
4266 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4267
4268 Result.FloatReal
4269 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
4270 Result.FloatImag
4271 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
4272 return true;
4273 }
4274
4275 case CK_FloatingComplexToIntegralComplex: {
4276 if (!Visit(E->getSubExpr()))
4277 return false;
4278
4279 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4280 QualType From
4281 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4282 Result.makeComplexInt();
4283 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
4284 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
4285 return true;
4286 }
4287
4288 case CK_IntegralRealToComplex: {
4289 APSInt &Real = Result.IntReal;
4290 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4291 return false;
4292
4293 Result.makeComplexInt();
4294 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4295 return true;
4296 }
4297
4298 case CK_IntegralComplexCast: {
4299 if (!Visit(E->getSubExpr()))
4300 return false;
4301
4302 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4303 QualType From
4304 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4305
4306 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4307 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4308 return true;
4309 }
4310
4311 case CK_IntegralComplexToFloatingComplex: {
4312 if (!Visit(E->getSubExpr()))
4313 return false;
4314
4315 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4316 QualType From
4317 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4318 Result.makeComplexFloat();
4319 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
4320 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
4321 return true;
4322 }
4323 }
4324
4325 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf57d8cb2011-12-09 22:58:01 +00004326 return Error(E);
Eli Friedmanc3e9df32010-08-16 23:27:44 +00004327}
4328
John McCall93d91dc2010-05-07 17:22:02 +00004329bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004330 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00004331 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4332
John McCall93d91dc2010-05-07 17:22:02 +00004333 if (!Visit(E->getLHS()))
4334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004335
John McCall93d91dc2010-05-07 17:22:02 +00004336 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004337 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00004338 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004339
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004340 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4341 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004342 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004343 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00004344 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004345 if (Result.isComplexFloat()) {
4346 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4347 APFloat::rmNearestTiesToEven);
4348 Result.getComplexFloatImag().add(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_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00004356 if (Result.isComplexFloat()) {
4357 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4358 APFloat::rmNearestTiesToEven);
4359 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4360 APFloat::rmNearestTiesToEven);
4361 } else {
4362 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4363 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4364 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004365 break;
John McCalle3027922010-08-25 11:45:40 +00004366 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004367 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00004368 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004369 APFloat &LHS_r = LHS.getComplexFloatReal();
4370 APFloat &LHS_i = LHS.getComplexFloatImag();
4371 APFloat &RHS_r = RHS.getComplexFloatReal();
4372 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00004373
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004374 APFloat Tmp = LHS_r;
4375 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4376 Result.getComplexFloatReal() = Tmp;
4377 Tmp = LHS_i;
4378 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4379 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4380
4381 Tmp = LHS_r;
4382 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4383 Result.getComplexFloatImag() = Tmp;
4384 Tmp = LHS_i;
4385 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4386 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4387 } else {
John McCall93d91dc2010-05-07 17:22:02 +00004388 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00004389 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004390 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4391 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00004392 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00004393 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4394 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4395 }
4396 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004397 case BO_Div:
4398 if (Result.isComplexFloat()) {
4399 ComplexValue LHS = Result;
4400 APFloat &LHS_r = LHS.getComplexFloatReal();
4401 APFloat &LHS_i = LHS.getComplexFloatImag();
4402 APFloat &RHS_r = RHS.getComplexFloatReal();
4403 APFloat &RHS_i = RHS.getComplexFloatImag();
4404 APFloat &Res_r = Result.getComplexFloatReal();
4405 APFloat &Res_i = Result.getComplexFloatImag();
4406
4407 APFloat Den = RHS_r;
4408 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4409 APFloat Tmp = RHS_i;
4410 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4411 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4412
4413 Res_r = LHS_r;
4414 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4415 Tmp = LHS_i;
4416 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4417 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4418 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4419
4420 Res_i = LHS_i;
4421 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4422 Tmp = LHS_r;
4423 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4424 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4425 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4426 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004427 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4428 return Error(E, diag::note_expr_divide_by_zero);
4429
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004430 ComplexValue LHS = Result;
4431 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4432 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4433 Result.getComplexIntReal() =
4434 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4435 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4436 Result.getComplexIntImag() =
4437 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4438 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4439 }
4440 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004441 }
4442
John McCall93d91dc2010-05-07 17:22:02 +00004443 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00004444}
4445
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004446bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4447 // Get the operand value into 'Result'.
4448 if (!Visit(E->getSubExpr()))
4449 return false;
4450
4451 switch (E->getOpcode()) {
4452 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004453 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00004454 case UO_Extension:
4455 return true;
4456 case UO_Plus:
4457 // The result is always just the subexpr.
4458 return true;
4459 case UO_Minus:
4460 if (Result.isComplexFloat()) {
4461 Result.getComplexFloatReal().changeSign();
4462 Result.getComplexFloatImag().changeSign();
4463 }
4464 else {
4465 Result.getComplexIntReal() = -Result.getComplexIntReal();
4466 Result.getComplexIntImag() = -Result.getComplexIntImag();
4467 }
4468 return true;
4469 case UO_Not:
4470 if (Result.isComplexFloat())
4471 Result.getComplexFloatImag().changeSign();
4472 else
4473 Result.getComplexIntImag() = -Result.getComplexIntImag();
4474 return true;
4475 }
4476}
4477
Anders Carlsson537969c2008-11-16 20:27:53 +00004478//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00004479// Void expression evaluation, primarily for a cast to void on the LHS of a
4480// comma operator
4481//===----------------------------------------------------------------------===//
4482
4483namespace {
4484class VoidExprEvaluator
4485 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4486public:
4487 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4488
4489 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00004490
4491 bool VisitCastExpr(const CastExpr *E) {
4492 switch (E->getCastKind()) {
4493 default:
4494 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4495 case CK_ToVoid:
4496 VisitIgnoredValue(E->getSubExpr());
4497 return true;
4498 }
4499 }
4500};
4501} // end anonymous namespace
4502
4503static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4504 assert(E->isRValue() && E->getType()->isVoidType());
4505 return VoidExprEvaluator(Info).Visit(E);
4506}
4507
4508//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00004509// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00004510//===----------------------------------------------------------------------===//
4511
Richard Smith0b0a0b62011-10-29 20:57:55 +00004512static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004513 // In C, function designators are not lvalues, but we evaluate them as if they
4514 // are.
4515 if (E->isGLValue() || E->getType()->isFunctionType()) {
4516 LValue LV;
4517 if (!EvaluateLValue(E, LV, Info))
4518 return false;
4519 LV.moveInto(Result);
4520 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004521 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004522 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00004523 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00004524 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004525 return false;
John McCall45d55e42010-05-07 21:00:08 +00004526 } else if (E->getType()->hasPointerRepresentation()) {
4527 LValue LV;
4528 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004529 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004530 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00004531 } else if (E->getType()->isRealFloatingType()) {
4532 llvm::APFloat F(0.0);
4533 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004534 return false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004535 Result = CCValue(F);
John McCall45d55e42010-05-07 21:00:08 +00004536 } else if (E->getType()->isAnyComplexType()) {
4537 ComplexValue C;
4538 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004539 return false;
Richard Smith725810a2011-10-16 21:26:27 +00004540 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004541 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00004542 MemberPtr P;
4543 if (!EvaluateMemberPointer(E, P, Info))
4544 return false;
4545 P.moveInto(Result);
4546 return true;
Richard Smithed5165f2011-11-04 05:33:44 +00004547 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004548 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004549 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004550 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00004551 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004552 Result = Info.CurrentCall->Temporaries[E];
Richard Smithed5165f2011-11-04 05:33:44 +00004553 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00004554 LValue LV;
Richard Smithce40ad62011-11-12 22:28:03 +00004555 LV.set(E, Info.CurrentCall);
Richard Smithd62306a2011-11-10 06:34:14 +00004556 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4557 return false;
4558 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00004559 } else if (E->getType()->isVoidType()) {
4560 if (!EvaluateVoid(E, Info))
4561 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004562 } else {
Richard Smith92b1ce02011-12-12 09:28:41 +00004563 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00004564 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004565 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00004566
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00004567 return true;
4568}
4569
Richard Smithed5165f2011-11-04 05:33:44 +00004570/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4571/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4572/// since later initializers for an object can indirectly refer to subobjects
4573/// which were initialized earlier.
4574static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithd62306a2011-11-10 06:34:14 +00004575 const LValue &This, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00004576 if (E->isRValue() && E->getType()->isLiteralType()) {
4577 // Evaluate arrays and record types in-place, so that later initializers can
4578 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00004579 if (E->getType()->isArrayType())
4580 return EvaluateArray(E, This, Result, Info);
4581 else if (E->getType()->isRecordType())
4582 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00004583 }
4584
4585 // For any other type, in-place evaluation is unimportant.
4586 CCValue CoreConstResult;
4587 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004588 CheckConstantExpression(Info, E, CoreConstResult, Result);
Richard Smithed5165f2011-11-04 05:33:44 +00004589}
4590
Richard Smithf57d8cb2011-12-09 22:58:01 +00004591/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4592/// lvalue-to-rvalue cast if it is an lvalue.
4593static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4594 CCValue Value;
4595 if (!::Evaluate(Value, Info, E))
4596 return false;
4597
4598 if (E->isGLValue()) {
4599 LValue LV;
4600 LV.setFrom(Value);
4601 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4602 return false;
4603 }
4604
4605 // Check this core constant expression is a constant expression, and if so,
4606 // convert it to one.
4607 return CheckConstantExpression(Info, E, Value, Result);
4608}
Richard Smith11562c52011-10-28 17:51:58 +00004609
Richard Smith7b553f12011-10-29 00:50:52 +00004610/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00004611/// any crazy technique (that has nothing to do with language standards) that
4612/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00004613/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4614/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00004615bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith036e2bd2011-12-10 01:10:13 +00004616 // Fast-path evaluations of integer literals, since we sometimes see files
4617 // containing vast quantities of these.
4618 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4619 Result.Val = APValue(APSInt(L->getValue(),
4620 L->getType()->isUnsignedIntegerType()));
4621 return true;
4622 }
4623
Richard Smith5686e752011-11-10 03:30:42 +00004624 // FIXME: Evaluating initializers for large arrays can cause performance
4625 // problems, and we don't use such values yet. Once we have a more efficient
4626 // array representation, this should be reinstated, and used by CodeGen.
Richard Smith027bf112011-11-17 22:56:20 +00004627 // The same problem affects large records.
4628 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4629 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith5686e752011-11-10 03:30:42 +00004630 return false;
4631
Richard Smithd62306a2011-11-10 06:34:14 +00004632 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004633 EvalInfo Info(Ctx, Result);
4634 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00004635}
4636
Jay Foad39c79802011-01-12 09:06:06 +00004637bool Expr::EvaluateAsBooleanCondition(bool &Result,
4638 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004639 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00004640 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithfec09922011-11-01 16:57:24 +00004641 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith0b0a0b62011-10-29 20:57:55 +00004642 Result);
John McCall1be1c632010-01-05 23:42:56 +00004643}
4644
Richard Smithcaf33902011-10-10 18:28:20 +00004645bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00004646 EvalResult ExprResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004647 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00004648 !ExprResult.Val.isInt())
Richard Smith11562c52011-10-28 17:51:58 +00004649 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004650
Richard Smith11562c52011-10-28 17:51:58 +00004651 Result = ExprResult.Val.getInt();
4652 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00004653}
4654
Jay Foad39c79802011-01-12 09:06:06 +00004655bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00004656 EvalInfo Info(Ctx, Result);
4657
John McCall45d55e42010-05-07 21:00:08 +00004658 LValue LV;
Richard Smith80815602011-11-07 05:07:52 +00004659 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithf57d8cb2011-12-09 22:58:01 +00004660 CheckLValueConstantExpression(Info, this, LV, Result.Val);
Eli Friedman7d45c482009-09-13 10:17:44 +00004661}
4662
Richard Smith7b553f12011-10-29 00:50:52 +00004663/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4664/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00004665bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00004666 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00004667 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00004668}
Anders Carlsson59689ed2008-11-22 21:04:56 +00004669
Jay Foad39c79802011-01-12 09:06:06 +00004670bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00004671 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004672}
4673
Richard Smithcaf33902011-10-10 18:28:20 +00004674APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004675 EvalResult EvalResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004676 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00004677 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00004678 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004679 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00004680
Anders Carlsson6736d1a22008-12-19 20:58:05 +00004681 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00004682}
John McCall864e3962010-05-07 05:32:02 +00004683
Abramo Bagnaraf8199452010-05-14 17:07:14 +00004684 bool Expr::EvalResult::isGlobalLValue() const {
4685 assert(Val.isLValue());
4686 return IsGlobalLValue(Val.getLValueBase());
4687 }
4688
4689
John McCall864e3962010-05-07 05:32:02 +00004690/// isIntegerConstantExpr - this recursive routine will test if an expression is
4691/// an integer constant expression.
4692
4693/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4694/// comma, etc
4695///
4696/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4697/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4698/// cast+dereference.
4699
4700// CheckICE - This function does the fundamental ICE checking: the returned
4701// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4702// Note that to reduce code duplication, this helper does no evaluation
4703// itself; the caller checks whether the expression is evaluatable, and
4704// in the rare cases where CheckICE actually cares about the evaluated
4705// value, it calls into Evalute.
4706//
4707// Meanings of Val:
Richard Smith7b553f12011-10-29 00:50:52 +00004708// 0: This expression is an ICE.
John McCall864e3962010-05-07 05:32:02 +00004709// 1: This expression is not an ICE, but if it isn't evaluated, it's
4710// a legal subexpression for an ICE. This return value is used to handle
4711// the comma operator in C99 mode.
4712// 2: This expression is not an ICE, and is not a legal subexpression for one.
4713
Dan Gohman28ade552010-07-26 21:25:24 +00004714namespace {
4715
John McCall864e3962010-05-07 05:32:02 +00004716struct ICEDiag {
4717 unsigned Val;
4718 SourceLocation Loc;
4719
4720 public:
4721 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4722 ICEDiag() : Val(0) {}
4723};
4724
Dan Gohman28ade552010-07-26 21:25:24 +00004725}
4726
4727static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00004728
4729static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4730 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00004731 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00004732 !EVResult.Val.isInt()) {
4733 return ICEDiag(2, E->getLocStart());
4734 }
4735 return NoDiag();
4736}
4737
4738static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4739 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00004740 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00004741 return ICEDiag(2, E->getLocStart());
4742 }
4743
4744 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00004745#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00004746#define STMT(Node, Base) case Expr::Node##Class:
4747#define EXPR(Node, Base)
4748#include "clang/AST/StmtNodes.inc"
4749 case Expr::PredefinedExprClass:
4750 case Expr::FloatingLiteralClass:
4751 case Expr::ImaginaryLiteralClass:
4752 case Expr::StringLiteralClass:
4753 case Expr::ArraySubscriptExprClass:
4754 case Expr::MemberExprClass:
4755 case Expr::CompoundAssignOperatorClass:
4756 case Expr::CompoundLiteralExprClass:
4757 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00004758 case Expr::DesignatedInitExprClass:
4759 case Expr::ImplicitValueInitExprClass:
4760 case Expr::ParenListExprClass:
4761 case Expr::VAArgExprClass:
4762 case Expr::AddrLabelExprClass:
4763 case Expr::StmtExprClass:
4764 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00004765 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00004766 case Expr::CXXDynamicCastExprClass:
4767 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00004768 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00004769 case Expr::CXXNullPtrLiteralExprClass:
4770 case Expr::CXXThisExprClass:
4771 case Expr::CXXThrowExprClass:
4772 case Expr::CXXNewExprClass:
4773 case Expr::CXXDeleteExprClass:
4774 case Expr::CXXPseudoDestructorExprClass:
4775 case Expr::UnresolvedLookupExprClass:
4776 case Expr::DependentScopeDeclRefExprClass:
4777 case Expr::CXXConstructExprClass:
4778 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00004779 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00004780 case Expr::CXXTemporaryObjectExprClass:
4781 case Expr::CXXUnresolvedConstructExprClass:
4782 case Expr::CXXDependentScopeMemberExprClass:
4783 case Expr::UnresolvedMemberExprClass:
4784 case Expr::ObjCStringLiteralClass:
4785 case Expr::ObjCEncodeExprClass:
4786 case Expr::ObjCMessageExprClass:
4787 case Expr::ObjCSelectorExprClass:
4788 case Expr::ObjCProtocolExprClass:
4789 case Expr::ObjCIvarRefExprClass:
4790 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00004791 case Expr::ObjCIsaExprClass:
4792 case Expr::ShuffleVectorExprClass:
4793 case Expr::BlockExprClass:
4794 case Expr::BlockDeclRefExprClass:
4795 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00004796 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00004797 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00004798 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00004799 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00004800 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00004801 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00004802 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004803 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004804 case Expr::InitListExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00004805 return ICEDiag(2, E->getLocStart());
4806
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004807 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00004808 case Expr::GNUNullExprClass:
4809 // GCC considers the GNU __null value to be an integral constant expression.
4810 return NoDiag();
4811
John McCall7c454bb2011-07-15 05:09:51 +00004812 case Expr::SubstNonTypeTemplateParmExprClass:
4813 return
4814 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4815
John McCall864e3962010-05-07 05:32:02 +00004816 case Expr::ParenExprClass:
4817 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00004818 case Expr::GenericSelectionExprClass:
4819 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004820 case Expr::IntegerLiteralClass:
4821 case Expr::CharacterLiteralClass:
4822 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00004823 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00004824 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004825 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00004826 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00004827 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00004828 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00004829 return NoDiag();
4830 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00004831 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00004832 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4833 // constant expressions, but they can never be ICEs because an ICE cannot
4834 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00004835 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004836 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00004837 return CheckEvalInICE(E, Ctx);
4838 return ICEDiag(2, E->getLocStart());
4839 }
4840 case Expr::DeclRefExprClass:
4841 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4842 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00004843 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00004844 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4845
4846 // Parameter variables are never constants. Without this check,
4847 // getAnyInitializer() can find a default argument, which leads
4848 // to chaos.
4849 if (isa<ParmVarDecl>(D))
4850 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4851
4852 // C++ 7.1.5.1p2
4853 // A variable of non-volatile const-qualified integral or enumeration
4854 // type initialized by an ICE can be used in ICEs.
4855 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00004856 if (!Dcl->getType()->isIntegralOrEnumerationType())
4857 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4858
John McCall864e3962010-05-07 05:32:02 +00004859 // Look for a declaration of this variable that has an initializer.
4860 const VarDecl *ID = 0;
4861 const Expr *Init = Dcl->getAnyInitializer(ID);
4862 if (Init) {
4863 if (ID->isInitKnownICE()) {
4864 // We have already checked whether this subexpression is an
4865 // integral constant expression.
4866 if (ID->isInitICE())
4867 return NoDiag();
4868 else
4869 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4870 }
4871
4872 // It's an ICE whether or not the definition we found is
4873 // out-of-line. See DR 721 and the discussion in Clang PR
4874 // 6206 for details.
4875
4876 if (Dcl->isCheckingICE()) {
4877 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4878 }
4879
4880 Dcl->setCheckingICE();
4881 ICEDiag Result = CheckICE(Init, Ctx);
4882 // Cache the result of the ICE test.
4883 Dcl->setInitKnownICE(Result.Val == 0);
4884 return Result;
4885 }
4886 }
4887 }
4888 return ICEDiag(2, E->getLocStart());
4889 case Expr::UnaryOperatorClass: {
4890 const UnaryOperator *Exp = cast<UnaryOperator>(E);
4891 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004892 case UO_PostInc:
4893 case UO_PostDec:
4894 case UO_PreInc:
4895 case UO_PreDec:
4896 case UO_AddrOf:
4897 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00004898 // C99 6.6/3 allows increment and decrement within unevaluated
4899 // subexpressions of constant expressions, but they can never be ICEs
4900 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004901 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00004902 case UO_Extension:
4903 case UO_LNot:
4904 case UO_Plus:
4905 case UO_Minus:
4906 case UO_Not:
4907 case UO_Real:
4908 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00004909 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00004910 }
4911
4912 // OffsetOf falls through here.
4913 }
4914 case Expr::OffsetOfExprClass: {
4915 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith7b553f12011-10-29 00:50:52 +00004916 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00004917 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00004918 // compliance: we should warn earlier for offsetof expressions with
4919 // array subscripts that aren't ICEs, and if the array subscripts
4920 // are ICEs, the value of the offsetof must be an integer constant.
4921 return CheckEvalInICE(E, Ctx);
4922 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00004923 case Expr::UnaryExprOrTypeTraitExprClass: {
4924 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4925 if ((Exp->getKind() == UETT_SizeOf) &&
4926 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00004927 return ICEDiag(2, E->getLocStart());
4928 return NoDiag();
4929 }
4930 case Expr::BinaryOperatorClass: {
4931 const BinaryOperator *Exp = cast<BinaryOperator>(E);
4932 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00004933 case BO_PtrMemD:
4934 case BO_PtrMemI:
4935 case BO_Assign:
4936 case BO_MulAssign:
4937 case BO_DivAssign:
4938 case BO_RemAssign:
4939 case BO_AddAssign:
4940 case BO_SubAssign:
4941 case BO_ShlAssign:
4942 case BO_ShrAssign:
4943 case BO_AndAssign:
4944 case BO_XorAssign:
4945 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00004946 // C99 6.6/3 allows assignments within unevaluated subexpressions of
4947 // constant expressions, but they can never be ICEs because an ICE cannot
4948 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00004949 return ICEDiag(2, E->getLocStart());
4950
John McCalle3027922010-08-25 11:45:40 +00004951 case BO_Mul:
4952 case BO_Div:
4953 case BO_Rem:
4954 case BO_Add:
4955 case BO_Sub:
4956 case BO_Shl:
4957 case BO_Shr:
4958 case BO_LT:
4959 case BO_GT:
4960 case BO_LE:
4961 case BO_GE:
4962 case BO_EQ:
4963 case BO_NE:
4964 case BO_And:
4965 case BO_Xor:
4966 case BO_Or:
4967 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00004968 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4969 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00004970 if (Exp->getOpcode() == BO_Div ||
4971 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00004972 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00004973 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00004974 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00004975 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004976 if (REval == 0)
4977 return ICEDiag(1, E->getLocStart());
4978 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00004979 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00004980 if (LEval.isMinSignedValue())
4981 return ICEDiag(1, E->getLocStart());
4982 }
4983 }
4984 }
John McCalle3027922010-08-25 11:45:40 +00004985 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00004986 if (Ctx.getLangOptions().C99) {
4987 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4988 // if it isn't evaluated.
4989 if (LHSResult.Val == 0 && RHSResult.Val == 0)
4990 return ICEDiag(1, E->getLocStart());
4991 } else {
4992 // In both C89 and C++, commas in ICEs are illegal.
4993 return ICEDiag(2, E->getLocStart());
4994 }
4995 }
4996 if (LHSResult.Val >= RHSResult.Val)
4997 return LHSResult;
4998 return RHSResult;
4999 }
John McCalle3027922010-08-25 11:45:40 +00005000 case BO_LAnd:
5001 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00005002 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5003 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5004 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5005 // Rare case where the RHS has a comma "side-effect"; we need
5006 // to actually check the condition to see whether the side
5007 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00005008 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00005009 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00005010 return RHSResult;
5011 return NoDiag();
5012 }
5013
5014 if (LHSResult.Val >= RHSResult.Val)
5015 return LHSResult;
5016 return RHSResult;
5017 }
5018 }
5019 }
5020 case Expr::ImplicitCastExprClass:
5021 case Expr::CStyleCastExprClass:
5022 case Expr::CXXFunctionalCastExprClass:
5023 case Expr::CXXStaticCastExprClass:
5024 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00005025 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005026 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00005027 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00005028 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00005029 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5030 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00005031 switch (cast<CastExpr>(E)->getCastKind()) {
5032 case CK_LValueToRValue:
5033 case CK_NoOp:
5034 case CK_IntegralToBoolean:
5035 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00005036 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00005037 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00005038 return ICEDiag(2, E->getLocStart());
5039 }
John McCall864e3962010-05-07 05:32:02 +00005040 }
John McCallc07a0c72011-02-17 10:25:35 +00005041 case Expr::BinaryConditionalOperatorClass: {
5042 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5043 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5044 if (CommonResult.Val == 2) return CommonResult;
5045 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5046 if (FalseResult.Val == 2) return FalseResult;
5047 if (CommonResult.Val == 1) return CommonResult;
5048 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00005049 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00005050 return FalseResult;
5051 }
John McCall864e3962010-05-07 05:32:02 +00005052 case Expr::ConditionalOperatorClass: {
5053 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5054 // If the condition (ignoring parens) is a __builtin_constant_p call,
5055 // then only the true side is actually considered in an integer constant
5056 // expression, and it is fully evaluated. This is an important GNU
5057 // extension. See GCC PR38377 for discussion.
5058 if (const CallExpr *CallCE
5059 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smithd62306a2011-11-10 06:34:14 +00005060 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCall864e3962010-05-07 05:32:02 +00005061 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00005062 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCall864e3962010-05-07 05:32:02 +00005063 !EVResult.Val.isInt()) {
5064 return ICEDiag(2, E->getLocStart());
5065 }
5066 return NoDiag();
5067 }
5068 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00005069 if (CondResult.Val == 2)
5070 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005071
Richard Smithf57d8cb2011-12-09 22:58:01 +00005072 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5073 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00005074
John McCall864e3962010-05-07 05:32:02 +00005075 if (TrueResult.Val == 2)
5076 return TrueResult;
5077 if (FalseResult.Val == 2)
5078 return FalseResult;
5079 if (CondResult.Val == 1)
5080 return CondResult;
5081 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5082 return NoDiag();
5083 // Rare case where the diagnostics depend on which side is evaluated
5084 // Note that if we get here, CondResult is 0, and at least one of
5085 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00005086 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00005087 return FalseResult;
5088 }
5089 return TrueResult;
5090 }
5091 case Expr::CXXDefaultArgExprClass:
5092 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5093 case Expr::ChooseExprClass: {
5094 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5095 }
5096 }
5097
5098 // Silence a GCC warning
5099 return ICEDiag(2, E->getLocStart());
5100}
5101
Richard Smithf57d8cb2011-12-09 22:58:01 +00005102/// Evaluate an expression as a C++11 integral constant expression.
5103static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5104 const Expr *E,
5105 llvm::APSInt *Value,
5106 SourceLocation *Loc) {
5107 if (!E->getType()->isIntegralOrEnumerationType()) {
5108 if (Loc) *Loc = E->getExprLoc();
5109 return false;
5110 }
5111
5112 Expr::EvalResult Result;
Richard Smith92b1ce02011-12-12 09:28:41 +00005113 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5114 Result.Diag = &Diags;
5115 EvalInfo Info(Ctx, Result);
5116
5117 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5118 if (!Diags.empty()) {
5119 IsICE = false;
5120 if (Loc) *Loc = Diags[0].first;
5121 } else if (!IsICE && Loc) {
5122 *Loc = E->getExprLoc();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005123 }
Richard Smith92b1ce02011-12-12 09:28:41 +00005124
5125 if (!IsICE)
5126 return false;
5127
5128 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5129 if (Value) *Value = Result.Val.getInt();
5130 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005131}
5132
Richard Smith92b1ce02011-12-12 09:28:41 +00005133bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005134 if (Ctx.getLangOptions().CPlusPlus0x)
5135 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5136
John McCall864e3962010-05-07 05:32:02 +00005137 ICEDiag d = CheckICE(this, Ctx);
5138 if (d.Val != 0) {
5139 if (Loc) *Loc = d.Loc;
5140 return false;
5141 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005142 return true;
5143}
5144
5145bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5146 SourceLocation *Loc, bool isEvaluated) const {
5147 if (Ctx.getLangOptions().CPlusPlus0x)
5148 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5149
5150 if (!isIntegerConstantExpr(Ctx, Loc))
5151 return false;
5152 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00005153 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00005154 return true;
5155}