blob: dd1110ab11c3590c8be6d90d042f2c77e07db05c [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Richard Smith180f4792011-11-10 06:34:14 +000046 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000047 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000048 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000049
Richard Smith1bf9a9e2011-11-12 22:28:03 +000050 QualType getType(APValue::LValueBase B) {
51 if (!B) return QualType();
52 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
53 return D->getType();
54 return B.get<const Expr*>()->getType();
55 }
56
Richard Smith180f4792011-11-10 06:34:14 +000057 /// Get an LValue path entry, which is known to not be an array index, as a
58 /// field declaration.
59 const FieldDecl *getAsField(APValue::LValuePathEntry E) {
60 APValue::BaseOrMemberType Value;
61 Value.setFromOpaqueValue(E.BaseOrMember);
62 return dyn_cast<FieldDecl>(Value.getPointer());
63 }
64 /// Get an LValue path entry, which is known to not be an array index, as a
65 /// base class declaration.
66 const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
67 APValue::BaseOrMemberType Value;
68 Value.setFromOpaqueValue(E.BaseOrMember);
69 return dyn_cast<CXXRecordDecl>(Value.getPointer());
70 }
71 /// Determine whether this LValue path entry for a base class names a virtual
72 /// base class.
73 bool isVirtualBaseClass(APValue::LValuePathEntry E) {
74 APValue::BaseOrMemberType Value;
75 Value.setFromOpaqueValue(E.BaseOrMember);
76 return Value.getInt();
77 }
78
Richard Smith9a17a682011-11-07 05:07:52 +000079 /// Determine whether the described subobject is an array element.
80 static bool SubobjectIsArrayElement(QualType Base,
81 ArrayRef<APValue::LValuePathEntry> Path) {
82 bool IsArrayElement = false;
83 const Type *T = Base.getTypePtr();
84 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
85 IsArrayElement = T && T->isArrayType();
86 if (IsArrayElement)
87 T = T->getBaseElementTypeUnsafe();
Richard Smith180f4792011-11-10 06:34:14 +000088 else if (const FieldDecl *FD = getAsField(Path[I]))
Richard Smith9a17a682011-11-07 05:07:52 +000089 T = FD->getType().getTypePtr();
90 else
91 // Path[I] describes a base class.
92 T = 0;
93 }
94 return IsArrayElement;
95 }
96
Richard Smith0a3bdb62011-11-04 02:25:55 +000097 /// A path from a glvalue to a subobject of that glvalue.
98 struct SubobjectDesignator {
99 /// True if the subobject was named in a manner not supported by C++11. Such
100 /// lvalues can still be folded, but they are not core constant expressions
101 /// and we cannot perform lvalue-to-rvalue conversions on them.
102 bool Invalid : 1;
103
104 /// Whether this designates an array element.
105 bool ArrayElement : 1;
106
107 /// Whether this designates 'one past the end' of the current subobject.
108 bool OnePastTheEnd : 1;
109
Richard Smith9a17a682011-11-07 05:07:52 +0000110 typedef APValue::LValuePathEntry PathEntry;
111
Richard Smith0a3bdb62011-11-04 02:25:55 +0000112 /// The entries on the path from the glvalue to the designated subobject.
113 SmallVector<PathEntry, 8> Entries;
114
115 SubobjectDesignator() :
116 Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
117
Richard Smith9a17a682011-11-07 05:07:52 +0000118 SubobjectDesignator(const APValue &V) :
119 Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
120 OnePastTheEnd(false) {
121 if (!Invalid) {
122 ArrayRef<PathEntry> VEntries = V.getLValuePath();
123 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
124 if (V.getLValueBase())
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000125 ArrayElement = SubobjectIsArrayElement(getType(V.getLValueBase()),
Richard Smith9a17a682011-11-07 05:07:52 +0000126 V.getLValuePath());
127 else
128 assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
Richard Smithe24f5fc2011-11-17 22:56:20 +0000129 OnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000130 }
131 }
132
Richard Smith0a3bdb62011-11-04 02:25:55 +0000133 void setInvalid() {
134 Invalid = true;
135 Entries.clear();
136 }
137 /// Update this designator to refer to the given element within this array.
138 void addIndex(uint64_t N) {
139 if (Invalid) return;
140 if (OnePastTheEnd) {
141 setInvalid();
142 return;
143 }
144 PathEntry Entry;
Richard Smith9a17a682011-11-07 05:07:52 +0000145 Entry.ArrayIndex = N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000146 Entries.push_back(Entry);
147 ArrayElement = true;
148 }
149 /// Update this designator to refer to the given base or member of this
150 /// object.
Richard Smith180f4792011-11-10 06:34:14 +0000151 void addDecl(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152 if (Invalid) return;
153 if (OnePastTheEnd) {
154 setInvalid();
155 return;
156 }
157 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000158 APValue::BaseOrMemberType Value(D, Virtual);
159 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000160 Entries.push_back(Entry);
161 ArrayElement = false;
162 }
163 /// Add N to the address of this subobject.
164 void adjustIndex(uint64_t N) {
165 if (Invalid) return;
166 if (ArrayElement) {
Richard Smithcc5d4f62011-11-07 09:22:26 +0000167 // FIXME: Make sure the index stays within bounds, or one past the end.
Richard Smith9a17a682011-11-07 05:07:52 +0000168 Entries.back().ArrayIndex += N;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000169 return;
170 }
171 if (OnePastTheEnd && N == (uint64_t)-1)
172 OnePastTheEnd = false;
173 else if (!OnePastTheEnd && N == 1)
174 OnePastTheEnd = true;
175 else if (N != 0)
176 setInvalid();
177 }
178 };
179
Richard Smith47a1eed2011-10-29 20:57:55 +0000180 /// A core constant value. This can be the value of any constant expression,
181 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000182 ///
183 /// For an LValue, the base and offset are stored in the APValue subobject,
184 /// but the other information is stored in the SubobjectDesignator. For all
185 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000186 class CCValue : public APValue {
187 typedef llvm::APSInt APSInt;
188 typedef llvm::APFloat APFloat;
Richard Smith177dce72011-11-01 16:57:24 +0000189 /// If the value is a reference or pointer into a parameter or temporary,
190 /// this is the corresponding call stack frame.
191 CallStackFrame *CallFrame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000192 /// If the value is a reference or pointer, this is a description of how the
193 /// subobject was specified.
194 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000195 public:
Richard Smith177dce72011-11-01 16:57:24 +0000196 struct GlobalValue {};
197
Richard Smith47a1eed2011-10-29 20:57:55 +0000198 CCValue() {}
199 explicit CCValue(const APSInt &I) : APValue(I) {}
200 explicit CCValue(const APFloat &F) : APValue(F) {}
201 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
202 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
203 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith177dce72011-11-01 16:57:24 +0000204 CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000205 CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 const SubobjectDesignator &D) :
Richard Smith9a17a682011-11-07 05:07:52 +0000207 APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
Richard Smith177dce72011-11-01 16:57:24 +0000208 CCValue(const APValue &V, GlobalValue) :
Richard Smith9a17a682011-11-07 05:07:52 +0000209 APValue(V), CallFrame(0), Designator(V) {}
Richard Smithe24f5fc2011-11-17 22:56:20 +0000210 CCValue(const ValueDecl *D, bool IsDerivedMember,
211 ArrayRef<const CXXRecordDecl*> Path) :
212 APValue(D, IsDerivedMember, Path) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000213
Richard Smith177dce72011-11-01 16:57:24 +0000214 CallStackFrame *getLValueFrame() const {
Richard Smith47a1eed2011-10-29 20:57:55 +0000215 assert(getKind() == LValue);
Richard Smith177dce72011-11-01 16:57:24 +0000216 return CallFrame;
Richard Smith47a1eed2011-10-29 20:57:55 +0000217 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 SubobjectDesignator &getLValueDesignator() {
219 assert(getKind() == LValue);
220 return Designator;
221 }
222 const SubobjectDesignator &getLValueDesignator() const {
223 return const_cast<CCValue*>(this)->getLValueDesignator();
224 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000225 };
226
Richard Smithd0dccea2011-10-28 22:34:42 +0000227 /// A stack frame in the constexpr call stack.
228 struct CallStackFrame {
229 EvalInfo &Info;
230
231 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000232 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000233
Richard Smith180f4792011-11-10 06:34:14 +0000234 /// This - The binding for the this pointer in this call, if any.
235 const LValue *This;
236
Richard Smithd0dccea2011-10-28 22:34:42 +0000237 /// ParmBindings - Parameter bindings for this function call, indexed by
238 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000239 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000240
Richard Smithbd552ef2011-10-31 05:52:43 +0000241 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
242 typedef MapTy::const_iterator temp_iterator;
243 /// Temporaries - Temporary lvalues materialized within this stack frame.
244 MapTy Temporaries;
245
Richard Smith180f4792011-11-10 06:34:14 +0000246 CallStackFrame(EvalInfo &Info, const LValue *This,
247 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000248 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000249 };
250
Richard Smithdd1f29b2011-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 Smithbd552ef2011-10-31 05:52:43 +0000267 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000268 ASTContext &Ctx;
Richard Smithbd552ef2011-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 Smithbd552ef2011-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 Smith180f4792011-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 Smithc1c5f272011-12-13 06:39:58 +0000296 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
297 /// notes attached to it will also be stored, otherwise they will not be.
298 bool HasActiveDiagnostic;
299
Richard Smithbd552ef2011-10-31 05:52:43 +0000300
301 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000302 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
303 CallStackDepth(0), BottomFrame(*this, 0, 0), EvaluatingDecl(0),
Richard Smithc1c5f272011-12-13 06:39:58 +0000304 EvaluatingDeclValue(0), HasActiveDiagnostic(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000305
Richard Smithbd552ef2011-10-31 05:52:43 +0000306 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
307 MapTy::const_iterator i = OpaqueValues.find(e);
308 if (i == OpaqueValues.end()) return 0;
309 return &i->second;
310 }
311
Richard Smith180f4792011-11-10 06:34:14 +0000312 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
313 EvaluatingDecl = VD;
314 EvaluatingDeclValue = &Value;
315 }
316
Richard Smithc18c4232011-11-21 19:36:32 +0000317 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
318
Richard Smithc1c5f272011-12-13 06:39:58 +0000319 bool CheckCallLimit(SourceLocation Loc) {
320 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
321 return true;
322 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
323 << getLangOpts().ConstexprCallDepth;
324 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000325 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000326
Richard Smithc1c5f272011-12-13 06:39:58 +0000327 private:
328 /// Add a diagnostic to the diagnostics list.
329 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
330 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
331 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
332 return EvalStatus.Diag->back().second;
333 }
334
335 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000336 /// Diagnose that the evaluation cannot be folded.
Richard Smithc1c5f272011-12-13 06:39:58 +0000337 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
338 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000339 // If we have a prior diagnostic, it will be noting that the expression
340 // isn't a constant expression. This diagnostic is more important.
341 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000342 if (EvalStatus.Diag) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000343 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000344 EvalStatus.Diag->clear();
Richard Smithc1c5f272011-12-13 06:39:58 +0000345 EvalStatus.Diag->reserve(1 + ExtraNotes);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000346 // FIXME: Add a call stack for constexpr evaluation.
Richard Smithc1c5f272011-12-13 06:39:58 +0000347 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithdd1f29b2011-12-12 09:28:41 +0000348 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000349 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000350 return OptionalDiagnostic();
351 }
352
353 /// Diagnose that the evaluation does not produce a C++11 core constant
354 /// expression.
Richard Smithc1c5f272011-12-13 06:39:58 +0000355 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId,
356 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000357 // Don't override a previous diagnostic.
358 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
359 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000360 return Diag(Loc, DiagId, ExtraNotes);
361 }
362
363 /// Add a note to a prior diagnostic.
364 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
365 if (!HasActiveDiagnostic)
366 return OptionalDiagnostic();
367 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000368 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 };
370
Richard Smith180f4792011-11-10 06:34:14 +0000371 CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
372 const CCValue *Arguments)
373 : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
Richard Smithbd552ef2011-10-31 05:52:43 +0000374 Info.CurrentCall = this;
375 ++Info.CallStackDepth;
376 }
377
378 CallStackFrame::~CallStackFrame() {
379 assert(Info.CurrentCall == this && "calls retired out of order");
380 --Info.CallStackDepth;
381 Info.CurrentCall = Caller;
382 }
383
John McCallf4cf1a12010-05-07 17:22:02 +0000384 struct ComplexValue {
385 private:
386 bool IsInt;
387
388 public:
389 APSInt IntReal, IntImag;
390 APFloat FloatReal, FloatImag;
391
392 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
393
394 void makeComplexFloat() { IsInt = false; }
395 bool isComplexFloat() const { return !IsInt; }
396 APFloat &getComplexFloatReal() { return FloatReal; }
397 APFloat &getComplexFloatImag() { return FloatImag; }
398
399 void makeComplexInt() { IsInt = true; }
400 bool isComplexInt() const { return IsInt; }
401 APSInt &getComplexIntReal() { return IntReal; }
402 APSInt &getComplexIntImag() { return IntImag; }
403
Richard Smith47a1eed2011-10-29 20:57:55 +0000404 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000405 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000406 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000407 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000408 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000409 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000410 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000411 assert(v.isComplexFloat() || v.isComplexInt());
412 if (v.isComplexFloat()) {
413 makeComplexFloat();
414 FloatReal = v.getComplexFloatReal();
415 FloatImag = v.getComplexFloatImag();
416 } else {
417 makeComplexInt();
418 IntReal = v.getComplexIntReal();
419 IntImag = v.getComplexIntImag();
420 }
421 }
John McCallf4cf1a12010-05-07 17:22:02 +0000422 };
John McCallefdb83e2010-05-07 21:00:08 +0000423
424 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000425 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000426 CharUnits Offset;
Richard Smith177dce72011-11-01 16:57:24 +0000427 CallStackFrame *Frame;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000428 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000429
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000430 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000431 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000432 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith177dce72011-11-01 16:57:24 +0000433 CallStackFrame *getLValueFrame() const { return Frame; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000434 SubobjectDesignator &getLValueDesignator() { return Designator; }
435 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000436
Richard Smith47a1eed2011-10-29 20:57:55 +0000437 void moveInto(CCValue &V) const {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000438 V = CCValue(Base, Offset, Frame, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000439 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000440 void setFrom(const CCValue &V) {
441 assert(V.isLValue());
442 Base = V.getLValueBase();
443 Offset = V.getLValueOffset();
Richard Smith177dce72011-11-01 16:57:24 +0000444 Frame = V.getLValueFrame();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000445 Designator = V.getLValueDesignator();
446 }
447
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000448 void set(APValue::LValueBase B, CallStackFrame *F = 0) {
449 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000450 Offset = CharUnits::Zero();
451 Frame = F;
452 Designator = SubobjectDesignator();
John McCall56ca35d2011-02-17 10:25:35 +0000453 }
John McCallefdb83e2010-05-07 21:00:08 +0000454 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000455
456 struct MemberPtr {
457 MemberPtr() {}
458 explicit MemberPtr(const ValueDecl *Decl) :
459 DeclAndIsDerivedMember(Decl, false), Path() {}
460
461 /// The member or (direct or indirect) field referred to by this member
462 /// pointer, or 0 if this is a null member pointer.
463 const ValueDecl *getDecl() const {
464 return DeclAndIsDerivedMember.getPointer();
465 }
466 /// Is this actually a member of some type derived from the relevant class?
467 bool isDerivedMember() const {
468 return DeclAndIsDerivedMember.getInt();
469 }
470 /// Get the class which the declaration actually lives in.
471 const CXXRecordDecl *getContainingRecord() const {
472 return cast<CXXRecordDecl>(
473 DeclAndIsDerivedMember.getPointer()->getDeclContext());
474 }
475
476 void moveInto(CCValue &V) const {
477 V = CCValue(getDecl(), isDerivedMember(), Path);
478 }
479 void setFrom(const CCValue &V) {
480 assert(V.isMemberPointer());
481 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
482 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
483 Path.clear();
484 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
485 Path.insert(Path.end(), P.begin(), P.end());
486 }
487
488 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
489 /// whether the member is a member of some class derived from the class type
490 /// of the member pointer.
491 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
492 /// Path - The path of base/derived classes from the member declaration's
493 /// class (exclusive) to the class type of the member pointer (inclusive).
494 SmallVector<const CXXRecordDecl*, 4> Path;
495
496 /// Perform a cast towards the class of the Decl (either up or down the
497 /// hierarchy).
498 bool castBack(const CXXRecordDecl *Class) {
499 assert(!Path.empty());
500 const CXXRecordDecl *Expected;
501 if (Path.size() >= 2)
502 Expected = Path[Path.size() - 2];
503 else
504 Expected = getContainingRecord();
505 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
506 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
507 // if B does not contain the original member and is not a base or
508 // derived class of the class containing the original member, the result
509 // of the cast is undefined.
510 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
511 // (D::*). We consider that to be a language defect.
512 return false;
513 }
514 Path.pop_back();
515 return true;
516 }
517 /// Perform a base-to-derived member pointer cast.
518 bool castToDerived(const CXXRecordDecl *Derived) {
519 if (!getDecl())
520 return true;
521 if (!isDerivedMember()) {
522 Path.push_back(Derived);
523 return true;
524 }
525 if (!castBack(Derived))
526 return false;
527 if (Path.empty())
528 DeclAndIsDerivedMember.setInt(false);
529 return true;
530 }
531 /// Perform a derived-to-base member pointer cast.
532 bool castToBase(const CXXRecordDecl *Base) {
533 if (!getDecl())
534 return true;
535 if (Path.empty())
536 DeclAndIsDerivedMember.setInt(true);
537 if (isDerivedMember()) {
538 Path.push_back(Base);
539 return true;
540 }
541 return castBack(Base);
542 }
543 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000544
545 /// Kinds of constant expression checking, for diagnostics.
546 enum CheckConstantExpressionKind {
547 CCEK_Constant, ///< A normal constant.
548 CCEK_ReturnValue, ///< A constexpr function return value.
549 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
550 };
John McCallf4cf1a12010-05-07 17:22:02 +0000551}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000552
Richard Smith47a1eed2011-10-29 20:57:55 +0000553static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith69c2c502011-11-04 05:33:44 +0000554static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +0000555 const LValue &This, const Expr *E,
556 CheckConstantExpressionKind CCEK
557 = CCEK_Constant);
John McCallefdb83e2010-05-07 21:00:08 +0000558static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
559static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000560static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
561 EvalInfo &Info);
562static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000563static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000564static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000565 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000566static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000567static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000568
569//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000570// Misc utilities
571//===----------------------------------------------------------------------===//
572
Richard Smith180f4792011-11-10 06:34:14 +0000573/// Should this call expression be treated as a string literal?
574static bool IsStringLiteralCall(const CallExpr *E) {
575 unsigned Builtin = E->isBuiltinCall();
576 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
577 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
578}
579
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000580static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000581 // C++11 [expr.const]p3 An address constant expression is a prvalue core
582 // constant expression of pointer type that evaluates to...
583
584 // ... a null pointer value, or a prvalue core constant expression of type
585 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000586 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000587
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000588 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
589 // ... the address of an object with static storage duration,
590 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
591 return VD->hasGlobalStorage();
592 // ... the address of a function,
593 return isa<FunctionDecl>(D);
594 }
595
596 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000597 switch (E->getStmtClass()) {
598 default:
599 return false;
Richard Smith180f4792011-11-10 06:34:14 +0000600 case Expr::CompoundLiteralExprClass:
601 return cast<CompoundLiteralExpr>(E)->isFileScope();
602 // A string literal has static storage duration.
603 case Expr::StringLiteralClass:
604 case Expr::PredefinedExprClass:
605 case Expr::ObjCStringLiteralClass:
606 case Expr::ObjCEncodeExprClass:
607 return true;
608 case Expr::CallExprClass:
609 return IsStringLiteralCall(cast<CallExpr>(E));
610 // For GCC compatibility, &&label has static storage duration.
611 case Expr::AddrLabelExprClass:
612 return true;
613 // A Block literal expression may be used as the initialization value for
614 // Block variables at global or local static scope.
615 case Expr::BlockExprClass:
616 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
617 }
John McCall42c8f872010-05-10 23:27:23 +0000618}
619
Richard Smith9a17a682011-11-07 05:07:52 +0000620/// Check that this reference or pointer core constant expression is a valid
621/// value for a constant expression. Type T should be either LValue or CCValue.
622template<typename T>
Richard Smithf48fdb02011-12-09 22:58:01 +0000623static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000624 const T &LVal, APValue &Value,
625 CheckConstantExpressionKind CCEK) {
626 APValue::LValueBase Base = LVal.getLValueBase();
627 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
628
629 if (!IsGlobalLValue(Base)) {
630 if (Info.getLangOpts().CPlusPlus0x) {
631 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
632 Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
633 << E->isGLValue() << !Designator.Entries.empty()
634 << !!VD << CCEK << VD;
635 if (VD)
636 Info.Note(VD->getLocation(), diag::note_declared_at);
637 else
638 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
639 diag::note_constexpr_temporary_here);
640 } else {
641 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
642 }
Richard Smith9a17a682011-11-07 05:07:52 +0000643 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000644 }
Richard Smith9a17a682011-11-07 05:07:52 +0000645
Richard Smith9a17a682011-11-07 05:07:52 +0000646 // A constant expression must refer to an object or be a null pointer.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000647 if (Designator.Invalid ||
Richard Smith9a17a682011-11-07 05:07:52 +0000648 (!LVal.getLValueBase() && !Designator.Entries.empty())) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000649 // FIXME: This is not a core constant expression. We should have already
650 // produced a CCE diagnostic.
Richard Smith9a17a682011-11-07 05:07:52 +0000651 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
652 APValue::NoLValuePath());
653 return true;
654 }
655
Richard Smithc1c5f272011-12-13 06:39:58 +0000656 // Does this refer one past the end of some object?
657 // This is technically not an address constant expression nor a reference
658 // constant expression, but we allow it for address constant expressions.
659 if (E->isGLValue() && Base && Designator.OnePastTheEnd) {
660 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
661 Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
662 << !Designator.Entries.empty() << !!VD << VD;
663 if (VD)
664 Info.Note(VD->getLocation(), diag::note_declared_at);
665 else
666 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
667 diag::note_constexpr_temporary_here);
668 return false;
669 }
670
Richard Smith9a17a682011-11-07 05:07:52 +0000671 Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
Richard Smithe24f5fc2011-11-17 22:56:20 +0000672 Designator.Entries, Designator.OnePastTheEnd);
Richard Smith9a17a682011-11-07 05:07:52 +0000673 return true;
674}
675
Richard Smith47a1eed2011-10-29 20:57:55 +0000676/// Check that this core constant expression value is a valid value for a
Richard Smith69c2c502011-11-04 05:33:44 +0000677/// constant expression, and if it is, produce the corresponding constant value.
Richard Smithf48fdb02011-12-09 22:58:01 +0000678/// If not, report an appropriate diagnostic.
679static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +0000680 const CCValue &CCValue, APValue &Value,
681 CheckConstantExpressionKind CCEK
682 = CCEK_Constant) {
Richard Smith9a17a682011-11-07 05:07:52 +0000683 if (!CCValue.isLValue()) {
684 Value = CCValue;
685 return true;
686 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000687 return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
Richard Smith47a1eed2011-10-29 20:57:55 +0000688}
689
Richard Smith9e36b532011-10-31 05:11:32 +0000690const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000691 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +0000692}
693
694static bool IsLiteralLValue(const LValue &Value) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
Richard Smith9e36b532011-10-31 05:11:32 +0000696}
697
Richard Smith65ac5982011-11-01 21:06:14 +0000698static bool IsWeakLValue(const LValue &Value) {
699 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +0000700 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +0000701}
702
Richard Smithe24f5fc2011-11-17 22:56:20 +0000703static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +0000704 // A null base expression indicates a null pointer. These are always
705 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000706 if (!Value.getLValueBase()) {
707 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +0000708 return true;
709 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000710
John McCall42c8f872010-05-10 23:27:23 +0000711 // Require the base expression to be a global l-value.
Richard Smith47a1eed2011-10-29 20:57:55 +0000712 // FIXME: C++11 requires such conversions. Remove this check.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000713 if (!IsGlobalLValue(Value.getLValueBase())) return false;
John McCall42c8f872010-05-10 23:27:23 +0000714
Richard Smithe24f5fc2011-11-17 22:56:20 +0000715 // We have a non-null base. These are generally known to be true, but if it's
716 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +0000717 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000718 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +0000719 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +0000720}
721
Richard Smith47a1eed2011-10-29 20:57:55 +0000722static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +0000723 switch (Val.getKind()) {
724 case APValue::Uninitialized:
725 return false;
726 case APValue::Int:
727 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000728 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000729 case APValue::Float:
730 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +0000731 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000732 case APValue::ComplexInt:
733 Result = Val.getComplexIntReal().getBoolValue() ||
734 Val.getComplexIntImag().getBoolValue();
735 return true;
736 case APValue::ComplexFloat:
737 Result = !Val.getComplexFloatReal().isZero() ||
738 !Val.getComplexFloatImag().isZero();
739 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +0000740 case APValue::LValue:
741 return EvalPointerValueAsBool(Val, Result);
742 case APValue::MemberPointer:
743 Result = Val.getMemberPointerDecl();
744 return true;
Richard Smithc49bd112011-10-28 17:51:58 +0000745 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +0000746 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +0000747 case APValue::Struct:
748 case APValue::Union:
Richard Smithc49bd112011-10-28 17:51:58 +0000749 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000750 }
751
Richard Smithc49bd112011-10-28 17:51:58 +0000752 llvm_unreachable("unknown APValue kind");
753}
754
755static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
756 EvalInfo &Info) {
757 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +0000758 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +0000759 if (!Evaluate(Val, Info, E))
760 return false;
761 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +0000762}
763
Richard Smithc1c5f272011-12-13 06:39:58 +0000764template<typename T>
765static bool HandleOverflow(EvalInfo &Info, const Expr *E,
766 const T &SrcValue, QualType DestType) {
767 llvm::SmallVector<char, 32> Buffer;
768 SrcValue.toString(Buffer);
769 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
770 << StringRef(Buffer.data(), Buffer.size()) << DestType;
771 return false;
772}
773
774static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
775 QualType SrcType, const APFloat &Value,
776 QualType DestType, APSInt &Result) {
777 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000778 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000779 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Richard Smithc1c5f272011-12-13 06:39:58 +0000781 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000782 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000783 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
784 & APFloat::opInvalidOp)
785 return HandleOverflow(Info, E, Value, DestType);
786 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000787}
788
Richard Smithc1c5f272011-12-13 06:39:58 +0000789static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
790 QualType SrcType, QualType DestType,
791 APFloat &Result) {
792 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000793 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +0000794 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
795 APFloat::rmNearestTiesToEven, &ignored)
796 & APFloat::opOverflow)
797 return HandleOverflow(Info, E, Value, DestType);
798 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000799}
800
Mike Stump1eb44332009-09-09 15:08:12 +0000801static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000802 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000803 unsigned DestWidth = Ctx.getIntWidth(DestType);
804 APSInt Result = Value;
805 // Figure out if this is a truncate, extend or noop cast.
806 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000807 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000808 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000809 return Result;
810}
811
Richard Smithc1c5f272011-12-13 06:39:58 +0000812static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
813 QualType SrcType, const APSInt &Value,
814 QualType DestType, APFloat &Result) {
815 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
816 if (Result.convertFromAPInt(Value, Value.isSigned(),
817 APFloat::rmNearestTiesToEven)
818 & APFloat::opOverflow)
819 return HandleOverflow(Info, E, Value, DestType);
820 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000821}
822
Richard Smithe24f5fc2011-11-17 22:56:20 +0000823static bool FindMostDerivedObject(EvalInfo &Info, const LValue &LVal,
824 const CXXRecordDecl *&MostDerivedType,
825 unsigned &MostDerivedPathLength,
826 bool &MostDerivedIsArrayElement) {
827 const SubobjectDesignator &D = LVal.Designator;
828 if (D.Invalid || !LVal.Base)
Richard Smith180f4792011-11-10 06:34:14 +0000829 return false;
830
Richard Smithe24f5fc2011-11-17 22:56:20 +0000831 const Type *T = getType(LVal.Base).getTypePtr();
Richard Smith180f4792011-11-10 06:34:14 +0000832
833 // Find path prefix which leads to the most-derived subobject.
Richard Smith180f4792011-11-10 06:34:14 +0000834 MostDerivedType = T->getAsCXXRecordDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +0000835 MostDerivedPathLength = 0;
836 MostDerivedIsArrayElement = false;
Richard Smith180f4792011-11-10 06:34:14 +0000837
838 for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
839 bool IsArray = T && T->isArrayType();
840 if (IsArray)
841 T = T->getBaseElementTypeUnsafe();
842 else if (const FieldDecl *FD = getAsField(D.Entries[I]))
843 T = FD->getType().getTypePtr();
844 else
845 T = 0;
846
847 if (T) {
848 MostDerivedType = T->getAsCXXRecordDecl();
849 MostDerivedPathLength = I + 1;
850 MostDerivedIsArrayElement = IsArray;
851 }
852 }
853
Richard Smith180f4792011-11-10 06:34:14 +0000854 // (B*)&d + 1 has no most-derived object.
855 if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
856 return false;
857
Richard Smithe24f5fc2011-11-17 22:56:20 +0000858 return MostDerivedType != 0;
859}
860
861static void TruncateLValueBasePath(EvalInfo &Info, LValue &Result,
862 const RecordDecl *TruncatedType,
863 unsigned TruncatedElements,
864 bool IsArrayElement) {
865 SubobjectDesignator &D = Result.Designator;
866 const RecordDecl *RD = TruncatedType;
867 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +0000868 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
869 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000870 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +0000871 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000872 else
Richard Smith180f4792011-11-10 06:34:14 +0000873 Result.Offset -= Layout.getBaseClassOffset(Base);
874 RD = Base;
875 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000876 D.Entries.resize(TruncatedElements);
877 D.ArrayElement = IsArrayElement;
878}
879
880/// If the given LValue refers to a base subobject of some object, find the most
881/// derived object and the corresponding complete record type. This is necessary
882/// in order to find the offset of a virtual base class.
883static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
884 const CXXRecordDecl *&MostDerivedType) {
885 unsigned MostDerivedPathLength;
886 bool MostDerivedIsArrayElement;
887 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
888 MostDerivedPathLength, MostDerivedIsArrayElement))
889 return false;
890
891 // Remove the trailing base class path entries and their offsets.
892 TruncateLValueBasePath(Info, Result, MostDerivedType, MostDerivedPathLength,
893 MostDerivedIsArrayElement);
Richard Smith180f4792011-11-10 06:34:14 +0000894 return true;
895}
896
897static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
898 const CXXRecordDecl *Derived,
899 const CXXRecordDecl *Base,
900 const ASTRecordLayout *RL = 0) {
901 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
902 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
903 Obj.Designator.addDecl(Base, /*Virtual*/ false);
904}
905
906static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
907 const CXXRecordDecl *DerivedDecl,
908 const CXXBaseSpecifier *Base) {
909 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
910
911 if (!Base->isVirtual()) {
912 HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
913 return true;
914 }
915
916 // Extract most-derived object and corresponding type.
917 if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
918 return false;
919
920 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
921 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
922 Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
923 return true;
924}
925
926/// Update LVal to refer to the given field, which must be a member of the type
927/// currently described by LVal.
928static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
929 const FieldDecl *FD,
930 const ASTRecordLayout *RL = 0) {
931 if (!RL)
932 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
933
934 unsigned I = FD->getFieldIndex();
935 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
936 LVal.Designator.addDecl(FD);
937}
938
939/// Get the size of the given type in char units.
940static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
941 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
942 // extension.
943 if (Type->isVoidType() || Type->isFunctionType()) {
944 Size = CharUnits::One();
945 return true;
946 }
947
948 if (!Type->isConstantSizeType()) {
949 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
950 return false;
951 }
952
953 Size = Info.Ctx.getTypeSizeInChars(Type);
954 return true;
955}
956
957/// Update a pointer value to model pointer arithmetic.
958/// \param Info - Information about the ongoing evaluation.
959/// \param LVal - The pointer value to be updated.
960/// \param EltTy - The pointee type represented by LVal.
961/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
962static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
963 QualType EltTy, int64_t Adjustment) {
964 CharUnits SizeOfPointee;
965 if (!HandleSizeof(Info, EltTy, SizeOfPointee))
966 return false;
967
968 // Compute the new offset in the appropriate width.
969 LVal.Offset += Adjustment * SizeOfPointee;
970 LVal.Designator.adjustIndex(Adjustment);
971 return true;
972}
973
Richard Smith03f96112011-10-24 17:54:18 +0000974/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +0000975static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
976 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +0000977 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +0000978 // If this is a parameter to an active constexpr function call, perform
979 // argument substitution.
980 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000981 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000982 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +0000983 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000984 }
Richard Smith177dce72011-11-01 16:57:24 +0000985 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
986 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +0000987 }
Richard Smith03f96112011-10-24 17:54:18 +0000988
Richard Smith180f4792011-11-10 06:34:14 +0000989 // If we're currently evaluating the initializer of this declaration, use that
990 // in-flight value.
991 if (Info.EvaluatingDecl == VD) {
992 Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
993 return !Result.isUninit();
994 }
995
Richard Smith65ac5982011-11-01 21:06:14 +0000996 // Never evaluate the initializer of a weak variable. We can't be sure that
997 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +0000998 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000999 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001000 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001001 }
Richard Smith65ac5982011-11-01 21:06:14 +00001002
Richard Smith03f96112011-10-24 17:54:18 +00001003 const Expr *Init = VD->getAnyInitializer();
Richard Smithf48fdb02011-12-09 22:58:01 +00001004 if (!Init || Init->isValueDependent()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001005 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001006 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001007 }
Richard Smith03f96112011-10-24 17:54:18 +00001008
Richard Smith47a1eed2011-10-29 20:57:55 +00001009 if (APValue *V = VD->getEvaluatedValue()) {
Richard Smith177dce72011-11-01 16:57:24 +00001010 Result = CCValue(*V, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001011 return !Result.isUninit();
1012 }
Richard Smith03f96112011-10-24 17:54:18 +00001013
Richard Smithf48fdb02011-12-09 22:58:01 +00001014 if (VD->isEvaluatingValue()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001015 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001016 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001017 }
Richard Smith03f96112011-10-24 17:54:18 +00001018
1019 VD->setEvaluatingValue();
1020
Richard Smith47a1eed2011-10-29 20:57:55 +00001021 Expr::EvalStatus EStatus;
1022 EvalInfo InitInfo(Info.Ctx, EStatus);
Richard Smith180f4792011-11-10 06:34:14 +00001023 APValue EvalResult;
1024 InitInfo.setEvaluatingDecl(VD, EvalResult);
1025 LValue LVal;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001026 LVal.set(VD);
Richard Smithc49bd112011-10-28 17:51:58 +00001027 // FIXME: The caller will need to know whether the value was a constant
1028 // expression. If not, we should propagate up a diagnostic.
Richard Smith180f4792011-11-10 06:34:14 +00001029 if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001030 // FIXME: If the evaluation failure was not permanent (for instance, if we
1031 // hit a variable with no declaration yet, or a constexpr function with no
1032 // definition yet), the standard is unclear as to how we should behave.
1033 //
1034 // Either the initializer should be evaluated when the variable is defined,
1035 // or a failed evaluation of the initializer should be reattempted each time
1036 // it is used.
Richard Smith03f96112011-10-24 17:54:18 +00001037 VD->setEvaluatedValue(APValue());
Richard Smithdd1f29b2011-12-12 09:28:41 +00001038 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith47a1eed2011-10-29 20:57:55 +00001039 return false;
1040 }
Richard Smith03f96112011-10-24 17:54:18 +00001041
Richard Smith69c2c502011-11-04 05:33:44 +00001042 VD->setEvaluatedValue(EvalResult);
1043 Result = CCValue(EvalResult, CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001044 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001045}
1046
Richard Smithc49bd112011-10-28 17:51:58 +00001047static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001048 Qualifiers Quals = T.getQualifiers();
1049 return Quals.hasConst() && !Quals.hasVolatile();
1050}
1051
Richard Smith59efe262011-11-11 04:05:33 +00001052/// Get the base index of the given base class within an APValue representing
1053/// the given derived class.
1054static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1055 const CXXRecordDecl *Base) {
1056 Base = Base->getCanonicalDecl();
1057 unsigned Index = 0;
1058 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1059 E = Derived->bases_end(); I != E; ++I, ++Index) {
1060 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1061 return Index;
1062 }
1063
1064 llvm_unreachable("base class missing from derived class's bases list");
1065}
1066
Richard Smithcc5d4f62011-11-07 09:22:26 +00001067/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001068static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1069 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001070 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001071 if (Sub.Invalid || Sub.OnePastTheEnd) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001072 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001073 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001074 }
Richard Smithf64699e2011-11-11 08:28:03 +00001075 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001076 return true;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001077
1078 assert(!Obj.isLValue() && "extracting subobject of lvalue");
1079 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001080 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001081 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001082 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001083 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001084 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001085 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001086 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001087 if (CAT->getSize().ule(Index)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001088 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001089 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001090 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001091 if (O->getArrayInitializedElts() > Index)
1092 O = &O->getArrayInitializedElt(Index);
1093 else
1094 O = &O->getArrayFiller();
1095 ObjType = CAT->getElementType();
Richard Smith180f4792011-11-10 06:34:14 +00001096 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1097 // Next subobject is a class, struct or union field.
1098 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1099 if (RD->isUnion()) {
1100 const FieldDecl *UnionField = O->getUnionField();
1101 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001102 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001103 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001104 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001105 }
Richard Smith180f4792011-11-10 06:34:14 +00001106 O = &O->getUnionValue();
1107 } else
1108 O = &O->getStructField(Field->getFieldIndex());
1109 ObjType = Field->getType();
Richard Smithcc5d4f62011-11-07 09:22:26 +00001110 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001111 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001112 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1113 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1114 O = &O->getStructBase(getBaseIndex(Derived, Base));
1115 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001116 }
Richard Smith180f4792011-11-10 06:34:14 +00001117
Richard Smithf48fdb02011-12-09 22:58:01 +00001118 if (O->isUninit()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001119 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001120 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001121 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001122 }
1123
Richard Smithcc5d4f62011-11-07 09:22:26 +00001124 Obj = CCValue(*O, CCValue::GlobalValue());
1125 return true;
1126}
1127
Richard Smith180f4792011-11-10 06:34:14 +00001128/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1129/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1130/// for looking up the glvalue referred to by an entity of reference type.
1131///
1132/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001133/// \param Conv - The expression for which we are performing the conversion.
1134/// Used for diagnostics.
Richard Smith180f4792011-11-10 06:34:14 +00001135/// \param Type - The type we expect this conversion to produce.
1136/// \param LVal - The glvalue on which we are attempting to perform this action.
1137/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001138static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1139 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001140 const LValue &LVal, CCValue &RVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001141 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001142 CallStackFrame *Frame = LVal.Frame;
Richard Smithc49bd112011-10-28 17:51:58 +00001143
Richard Smithf48fdb02011-12-09 22:58:01 +00001144 if (!LVal.Base) {
1145 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithdd1f29b2011-12-12 09:28:41 +00001146 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithc49bd112011-10-28 17:51:58 +00001147 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001148 }
Richard Smithc49bd112011-10-28 17:51:58 +00001149
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001150 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001151 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1152 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001153 // expressions are constant expressions too. Inside constexpr functions,
1154 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001155 // In C, such things can also be folded, although they are not ICEs.
1156 //
Richard Smithd0dccea2011-10-28 22:34:42 +00001157 // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
1158 // interpretation of C++11 suggests that volatile parameters are OK if
1159 // they're never read (there's no prohibition against constructing volatile
1160 // objects in constant expressions), but lvalue-to-rvalue conversions on
1161 // them are not permitted.
Richard Smithc49bd112011-10-28 17:51:58 +00001162 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001163 if (!VD || VD->isInvalidDecl()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001164 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001165 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001166 }
1167
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001168 QualType VT = VD->getType();
Richard Smith0a3bdb62011-11-04 02:25:55 +00001169 if (!isa<ParmVarDecl>(VD)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001170 if (!IsConstNonVolatile(VT)) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001171 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001172 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001173 }
Richard Smithcd689922011-11-07 03:22:51 +00001174 // FIXME: Allow folding of values of any literal type in all languages.
1175 if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
Richard Smithf48fdb02011-12-09 22:58:01 +00001176 !VD->isConstexpr()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001177 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001178 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001179 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001180 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001181 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001182 return false;
1183
Richard Smith47a1eed2011-10-29 20:57:55 +00001184 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001185 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001186
1187 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1188 // conversion. This happens when the declaration and the lvalue should be
1189 // considered synonymous, for instance when initializing an array of char
1190 // from a string literal. Continue as if the initializer lvalue was the
1191 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001192 assert(RVal.getLValueOffset().isZero() &&
1193 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001194 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith177dce72011-11-01 16:57:24 +00001195 Frame = RVal.getLValueFrame();
Richard Smithc49bd112011-10-28 17:51:58 +00001196 }
1197
Richard Smith0a3bdb62011-11-04 02:25:55 +00001198 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1199 if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1200 const SubobjectDesignator &Designator = LVal.Designator;
Richard Smithf48fdb02011-12-09 22:58:01 +00001201 if (Designator.Invalid || Designator.Entries.size() != 1) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001202 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001203 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001204 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001205
1206 assert(Type->isIntegerType() && "string element not integer type");
Richard Smith9a17a682011-11-07 05:07:52 +00001207 uint64_t Index = Designator.Entries[0].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001208 if (Index > S->getLength()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001209 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001210 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001211 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001212 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1213 Type->isUnsignedIntegerType());
1214 if (Index < S->getLength())
1215 Value = S->getCodeUnit(Index);
1216 RVal = CCValue(Value);
1217 return true;
1218 }
1219
Richard Smithcc5d4f62011-11-07 09:22:26 +00001220 if (Frame) {
1221 // If this is a temporary expression with a nontrivial initializer, grab the
1222 // value from the relevant stack frame.
1223 RVal = Frame->Temporaries[Base];
1224 } else if (const CompoundLiteralExpr *CLE
1225 = dyn_cast<CompoundLiteralExpr>(Base)) {
1226 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1227 // initializer until now for such expressions. Such an expression can't be
1228 // an ICE in C, so this only matters for fold.
1229 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1230 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1231 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001232 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001233 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001234 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001235 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001236
Richard Smithf48fdb02011-12-09 22:58:01 +00001237 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1238 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001239}
1240
Richard Smith59efe262011-11-11 04:05:33 +00001241/// Build an lvalue for the object argument of a member function call.
1242static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1243 LValue &This) {
1244 if (Object->getType()->isPointerType())
1245 return EvaluatePointer(Object, This, Info);
1246
1247 if (Object->isGLValue())
1248 return EvaluateLValue(Object, This, Info);
1249
Richard Smithe24f5fc2011-11-17 22:56:20 +00001250 if (Object->getType()->isLiteralType())
1251 return EvaluateTemporary(Object, This, Info);
1252
1253 return false;
1254}
1255
1256/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1257/// lvalue referring to the result.
1258///
1259/// \param Info - Information about the ongoing evaluation.
1260/// \param BO - The member pointer access operation.
1261/// \param LV - Filled in with a reference to the resulting object.
1262/// \param IncludeMember - Specifies whether the member itself is included in
1263/// the resulting LValue subobject designator. This is not possible when
1264/// creating a bound member function.
1265/// \return The field or method declaration to which the member pointer refers,
1266/// or 0 if evaluation fails.
1267static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1268 const BinaryOperator *BO,
1269 LValue &LV,
1270 bool IncludeMember = true) {
1271 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1272
1273 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV))
1274 return 0;
1275
1276 MemberPtr MemPtr;
1277 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1278 return 0;
1279
1280 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1281 // member value, the behavior is undefined.
1282 if (!MemPtr.getDecl())
1283 return 0;
1284
1285 if (MemPtr.isDerivedMember()) {
1286 // This is a member of some derived class. Truncate LV appropriately.
1287 const CXXRecordDecl *MostDerivedType;
1288 unsigned MostDerivedPathLength;
1289 bool MostDerivedIsArrayElement;
1290 if (!FindMostDerivedObject(Info, LV, MostDerivedType, MostDerivedPathLength,
1291 MostDerivedIsArrayElement))
1292 return 0;
1293
1294 // The end of the derived-to-base path for the base object must match the
1295 // derived-to-base path for the member pointer.
1296 if (MostDerivedPathLength + MemPtr.Path.size() >
1297 LV.Designator.Entries.size())
1298 return 0;
1299 unsigned PathLengthToMember =
1300 LV.Designator.Entries.size() - MemPtr.Path.size();
1301 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1302 const CXXRecordDecl *LVDecl = getAsBaseClass(
1303 LV.Designator.Entries[PathLengthToMember + I]);
1304 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1305 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1306 return 0;
1307 }
1308
1309 // Truncate the lvalue to the appropriate derived class.
1310 bool ResultIsArray = false;
1311 if (PathLengthToMember == MostDerivedPathLength)
1312 ResultIsArray = MostDerivedIsArrayElement;
1313 TruncateLValueBasePath(Info, LV, MemPtr.getContainingRecord(),
1314 PathLengthToMember, ResultIsArray);
1315 } else if (!MemPtr.Path.empty()) {
1316 // Extend the LValue path with the member pointer's path.
1317 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1318 MemPtr.Path.size() + IncludeMember);
1319
1320 // Walk down to the appropriate base class.
1321 QualType LVType = BO->getLHS()->getType();
1322 if (const PointerType *PT = LVType->getAs<PointerType>())
1323 LVType = PT->getPointeeType();
1324 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1325 assert(RD && "member pointer access on non-class-type expression");
1326 // The first class in the path is that of the lvalue.
1327 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1328 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1329 HandleLValueDirectBase(Info, LV, RD, Base);
1330 RD = Base;
1331 }
1332 // Finally cast to the class containing the member.
1333 HandleLValueDirectBase(Info, LV, RD, MemPtr.getContainingRecord());
1334 }
1335
1336 // Add the member. Note that we cannot build bound member functions here.
1337 if (IncludeMember) {
1338 // FIXME: Deal with IndirectFieldDecls.
1339 const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl());
1340 if (!FD) return 0;
1341 HandleLValueMember(Info, LV, FD);
1342 }
1343
1344 return MemPtr.getDecl();
1345}
1346
1347/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1348/// the provided lvalue, which currently refers to the base object.
1349static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1350 LValue &Result) {
1351 const CXXRecordDecl *MostDerivedType;
1352 unsigned MostDerivedPathLength;
1353 bool MostDerivedIsArrayElement;
1354
1355 // Check this cast doesn't take us outside the object.
1356 if (!FindMostDerivedObject(Info, Result, MostDerivedType,
1357 MostDerivedPathLength,
1358 MostDerivedIsArrayElement))
1359 return false;
1360 SubobjectDesignator &D = Result.Designator;
1361 if (MostDerivedPathLength + E->path_size() > D.Entries.size())
1362 return false;
1363
1364 // Check the type of the final cast. We don't need to check the path,
1365 // since a cast can only be formed if the path is unique.
1366 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1367 bool ResultIsArray = false;
1368 QualType TargetQT = E->getType();
1369 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1370 TargetQT = PT->getPointeeType();
1371 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1372 const CXXRecordDecl *FinalType;
1373 if (NewEntriesSize == MostDerivedPathLength) {
1374 ResultIsArray = MostDerivedIsArrayElement;
1375 FinalType = MostDerivedType;
1376 } else
1377 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1378 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl())
1379 return false;
1380
1381 // Truncate the lvalue to the appropriate derived class.
1382 TruncateLValueBasePath(Info, Result, TargetType, NewEntriesSize,
1383 ResultIsArray);
1384 return true;
Richard Smith59efe262011-11-11 04:05:33 +00001385}
1386
Mike Stumpc4c90452009-10-27 22:09:17 +00001387namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001388enum EvalStmtResult {
1389 /// Evaluation failed.
1390 ESR_Failed,
1391 /// Hit a 'return' statement.
1392 ESR_Returned,
1393 /// Evaluation succeeded.
1394 ESR_Succeeded
1395};
1396}
1397
1398// Evaluate a statement.
Richard Smithc1c5f272011-12-13 06:39:58 +00001399static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00001400 const Stmt *S) {
1401 switch (S->getStmtClass()) {
1402 default:
1403 return ESR_Failed;
1404
1405 case Stmt::NullStmtClass:
1406 case Stmt::DeclStmtClass:
1407 return ESR_Succeeded;
1408
Richard Smithc1c5f272011-12-13 06:39:58 +00001409 case Stmt::ReturnStmtClass: {
1410 CCValue CCResult;
1411 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1412 if (!Evaluate(CCResult, Info, RetExpr) ||
1413 !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1414 CCEK_ReturnValue))
1415 return ESR_Failed;
1416 return ESR_Returned;
1417 }
Richard Smithd0dccea2011-10-28 22:34:42 +00001418
1419 case Stmt::CompoundStmtClass: {
1420 const CompoundStmt *CS = cast<CompoundStmt>(S);
1421 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1422 BE = CS->body_end(); BI != BE; ++BI) {
1423 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1424 if (ESR != ESR_Succeeded)
1425 return ESR;
1426 }
1427 return ESR_Succeeded;
1428 }
1429 }
1430}
1431
Richard Smithc1c5f272011-12-13 06:39:58 +00001432/// CheckConstexprFunction - Check that a function can be called in a constant
1433/// expression.
1434static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1435 const FunctionDecl *Declaration,
1436 const FunctionDecl *Definition) {
1437 // Can we evaluate this function call?
1438 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1439 return true;
1440
1441 if (Info.getLangOpts().CPlusPlus0x) {
1442 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
1443 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1444 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1445 << DiagDecl;
1446 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1447 } else {
1448 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1449 }
1450 return false;
1451}
1452
Richard Smith180f4792011-11-10 06:34:14 +00001453namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00001454typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00001455}
1456
1457/// EvaluateArgs - Evaluate the arguments to a function call.
1458static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1459 EvalInfo &Info) {
1460 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1461 I != E; ++I)
1462 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1463 return false;
1464 return true;
1465}
1466
Richard Smithd0dccea2011-10-28 22:34:42 +00001467/// Evaluate a function call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001468static bool HandleFunctionCall(const Expr *CallExpr, const LValue *This,
1469 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smithc1c5f272011-12-13 06:39:58 +00001470 EvalInfo &Info, APValue &Result) {
1471 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smithd0dccea2011-10-28 22:34:42 +00001472 return false;
1473
Richard Smith180f4792011-11-10 06:34:14 +00001474 ArgVector ArgValues(Args.size());
1475 if (!EvaluateArgs(Args, ArgValues, Info))
1476 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00001477
Richard Smith180f4792011-11-10 06:34:14 +00001478 CallStackFrame Frame(Info, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00001479 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1480}
1481
Richard Smith180f4792011-11-10 06:34:14 +00001482/// Evaluate a constructor call.
Richard Smithf48fdb02011-12-09 22:58:01 +00001483static bool HandleConstructorCall(const Expr *CallExpr, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00001484 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00001485 const CXXConstructorDecl *Definition,
Richard Smith59efe262011-11-11 04:05:33 +00001486 EvalInfo &Info,
Richard Smith180f4792011-11-10 06:34:14 +00001487 APValue &Result) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001488 if (!Info.CheckCallLimit(CallExpr->getExprLoc()))
Richard Smith180f4792011-11-10 06:34:14 +00001489 return false;
1490
1491 ArgVector ArgValues(Args.size());
1492 if (!EvaluateArgs(Args, ArgValues, Info))
1493 return false;
1494
1495 CallStackFrame Frame(Info, &This, ArgValues.data());
1496
1497 // If it's a delegating constructor, just delegate.
1498 if (Definition->isDelegatingConstructor()) {
1499 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1500 return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1501 }
1502
1503 // Reserve space for the struct members.
1504 const CXXRecordDecl *RD = Definition->getParent();
1505 if (!RD->isUnion())
1506 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1507 std::distance(RD->field_begin(), RD->field_end()));
1508
1509 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1510
1511 unsigned BasesSeen = 0;
1512#ifndef NDEBUG
1513 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1514#endif
1515 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1516 E = Definition->init_end(); I != E; ++I) {
1517 if ((*I)->isBaseInitializer()) {
1518 QualType BaseType((*I)->getBaseClass(), 0);
1519#ifndef NDEBUG
1520 // Non-virtual base classes are initialized in the order in the class
1521 // definition. We cannot have a virtual base class for a literal type.
1522 assert(!BaseIt->isVirtual() && "virtual base for literal type");
1523 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1524 "base class initializers not in expected order");
1525 ++BaseIt;
1526#endif
1527 LValue Subobject = This;
1528 HandleLValueDirectBase(Info, Subobject, RD,
1529 BaseType->getAsCXXRecordDecl(), &Layout);
1530 if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1531 Subobject, (*I)->getInit()))
1532 return false;
1533 } else if (FieldDecl *FD = (*I)->getMember()) {
1534 LValue Subobject = This;
1535 HandleLValueMember(Info, Subobject, FD, &Layout);
1536 if (RD->isUnion()) {
1537 Result = APValue(FD);
Richard Smithc1c5f272011-12-13 06:39:58 +00001538 if (!EvaluateConstantExpression(Result.getUnionValue(), Info, Subobject,
1539 (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001540 return false;
1541 } else if (!EvaluateConstantExpression(
1542 Result.getStructField(FD->getFieldIndex()),
Richard Smithc1c5f272011-12-13 06:39:58 +00001543 Info, Subobject, (*I)->getInit(), CCEK_MemberInit))
Richard Smith180f4792011-11-10 06:34:14 +00001544 return false;
1545 } else {
1546 // FIXME: handle indirect field initializers
Richard Smithdd1f29b2011-12-12 09:28:41 +00001547 Info.Diag((*I)->getInit()->getExprLoc(),
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 diag::note_invalid_subexpr_in_const_expr);
Richard Smith180f4792011-11-10 06:34:14 +00001549 return false;
1550 }
1551 }
1552
1553 return true;
1554}
1555
Richard Smithd0dccea2011-10-28 22:34:42 +00001556namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001557class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001558 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00001559 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00001560public:
1561
Richard Smith1e12c592011-10-16 21:26:27 +00001562 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00001563
1564 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001565 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00001566 return true;
1567 }
1568
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001569 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1570 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001571 return Visit(E->getResultExpr());
1572 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001573 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001574 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001575 return true;
1576 return false;
1577 }
John McCallf85e1932011-06-15 23:02:42 +00001578 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001579 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001580 return true;
1581 return false;
1582 }
1583 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001584 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00001585 return true;
1586 return false;
1587 }
1588
Mike Stumpc4c90452009-10-27 22:09:17 +00001589 // We don't want to evaluate BlockExprs multiple times, as they generate
1590 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001591 bool VisitBlockExpr(const BlockExpr *E) { return true; }
1592 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1593 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00001594 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001595 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1596 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1597 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1598 bool VisitStringLiteral(const StringLiteral *E) { return false; }
1599 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1600 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001601 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001602 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00001603 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001604 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00001605 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001606 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1607 bool VisitBinAssign(const BinaryOperator *E) { return true; }
1608 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1609 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00001610 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001611 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1612 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1613 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1614 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1615 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00001616 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00001617 return true;
Mike Stump980ca222009-10-29 20:48:09 +00001618 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00001619 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001620 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00001621
1622 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001623 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00001624 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1625 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001626 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00001627 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00001628 return false;
1629 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00001630
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001631 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00001632};
1633
John McCall56ca35d2011-02-17 10:25:35 +00001634class OpaqueValueEvaluation {
1635 EvalInfo &info;
1636 OpaqueValueExpr *opaqueValue;
1637
1638public:
1639 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1640 Expr *value)
1641 : info(info), opaqueValue(opaqueValue) {
1642
1643 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00001644 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00001645 this->opaqueValue = 0;
1646 return;
1647 }
John McCall56ca35d2011-02-17 10:25:35 +00001648 }
1649
1650 bool hasError() const { return opaqueValue == 0; }
1651
1652 ~OpaqueValueEvaluation() {
Richard Smith1e12c592011-10-16 21:26:27 +00001653 // FIXME: This will not work for recursive constexpr functions using opaque
1654 // values. Restore the former value.
John McCall56ca35d2011-02-17 10:25:35 +00001655 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1656 }
1657};
1658
Mike Stumpc4c90452009-10-27 22:09:17 +00001659} // end anonymous namespace
1660
Eli Friedman4efaa272008-11-12 09:44:48 +00001661//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001662// Generic Evaluation
1663//===----------------------------------------------------------------------===//
1664namespace {
1665
Richard Smithf48fdb02011-12-09 22:58:01 +00001666// FIXME: RetTy is always bool. Remove it.
1667template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001668class ExprEvaluatorBase
1669 : public ConstStmtVisitor<Derived, RetTy> {
1670private:
Richard Smith47a1eed2011-10-29 20:57:55 +00001671 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001672 return static_cast<Derived*>(this)->Success(V, E);
1673 }
Richard Smithf10d9172011-10-11 21:43:33 +00001674 RetTy DerivedValueInitialization(const Expr *E) {
1675 return static_cast<Derived*>(this)->ValueInitialization(E);
1676 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001677
1678protected:
1679 EvalInfo &Info;
1680 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1681 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1682
Richard Smithdd1f29b2011-12-12 09:28:41 +00001683 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00001684 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001685 }
1686
1687 /// Report an evaluation error. This should only be called when an error is
1688 /// first discovered. When propagating an error, just return false.
1689 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001690 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00001691 return false;
1692 }
1693 bool Error(const Expr *E) {
1694 return Error(E, diag::note_invalid_subexpr_in_const_expr);
1695 }
1696
1697 RetTy ValueInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00001698
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001699public:
1700 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1701
1702 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001703 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001704 }
1705 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001706 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001707 }
1708
1709 RetTy VisitParenExpr(const ParenExpr *E)
1710 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1711 RetTy VisitUnaryExtension(const UnaryOperator *E)
1712 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1713 RetTy VisitUnaryPlus(const UnaryOperator *E)
1714 { return StmtVisitorTy::Visit(E->getSubExpr()); }
1715 RetTy VisitChooseExpr(const ChooseExpr *E)
1716 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1717 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1718 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00001719 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1720 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00001721 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1722 { return StmtVisitorTy::Visit(E->getExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001723
Richard Smithc216a012011-12-12 12:46:16 +00001724 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
1725 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
1726 return static_cast<Derived*>(this)->VisitCastExpr(E);
1727 }
1728 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
1729 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
1730 return static_cast<Derived*>(this)->VisitCastExpr(E);
1731 }
1732
Richard Smithe24f5fc2011-11-17 22:56:20 +00001733 RetTy VisitBinaryOperator(const BinaryOperator *E) {
1734 switch (E->getOpcode()) {
1735 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00001736 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001737
1738 case BO_Comma:
1739 VisitIgnoredValue(E->getLHS());
1740 return StmtVisitorTy::Visit(E->getRHS());
1741
1742 case BO_PtrMemD:
1743 case BO_PtrMemI: {
1744 LValue Obj;
1745 if (!HandleMemberPointerAccess(Info, E, Obj))
1746 return false;
1747 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00001748 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001749 return false;
1750 return DerivedSuccess(Result, E);
1751 }
1752 }
1753 }
1754
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001755 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1756 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1757 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00001758 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001759
1760 bool cond;
Richard Smithc49bd112011-10-28 17:51:58 +00001761 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001762 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001763
1764 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1765 }
1766
1767 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1768 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00001769 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00001770 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001771
Richard Smithc49bd112011-10-28 17:51:58 +00001772 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001773 return StmtVisitorTy::Visit(EvalExpr);
1774 }
1775
1776 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001777 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001778 if (!Value) {
1779 const Expr *Source = E->getSourceExpr();
1780 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00001781 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001782 if (Source == E) { // sanity checking.
1783 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00001784 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00001785 }
1786 return StmtVisitorTy::Visit(Source);
1787 }
Richard Smith47a1eed2011-10-29 20:57:55 +00001788 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001789 }
Richard Smithf10d9172011-10-11 21:43:33 +00001790
Richard Smithd0dccea2011-10-28 22:34:42 +00001791 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001792 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00001793 QualType CalleeType = Callee->getType();
1794
Richard Smithd0dccea2011-10-28 22:34:42 +00001795 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00001796 LValue *This = 0, ThisVal;
1797 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith6c957872011-11-10 09:31:24 +00001798
Richard Smith59efe262011-11-11 04:05:33 +00001799 // Extract function decl and 'this' pointer from the callee.
1800 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001801 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001802 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
1803 // Explicit bound member calls, such as x.f() or p->g();
1804 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 return false;
1806 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001807 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001808 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
1809 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00001810 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
1811 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001812 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001813 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001814 return Error(Callee);
1815
1816 FD = dyn_cast<FunctionDecl>(Member);
1817 if (!FD)
1818 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001819 } else if (CalleeType->isFunctionPointerType()) {
1820 CCValue Call;
Richard Smithf48fdb02011-12-09 22:58:01 +00001821 if (!Evaluate(Call, Info, Callee))
1822 return false;
Richard Smith59efe262011-11-11 04:05:33 +00001823
Richard Smithf48fdb02011-12-09 22:58:01 +00001824 if (!Call.isLValue() || !Call.getLValueOffset().isZero())
1825 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001826 FD = dyn_cast_or_null<FunctionDecl>(
1827 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00001828 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00001829 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00001830
1831 // Overloaded operator calls to member functions are represented as normal
1832 // calls with '*this' as the first argument.
1833 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1834 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00001835 // FIXME: When selecting an implicit conversion for an overloaded
1836 // operator delete, we sometimes try to evaluate calls to conversion
1837 // operators without a 'this' parameter!
1838 if (Args.empty())
1839 return Error(E);
1840
Richard Smith59efe262011-11-11 04:05:33 +00001841 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1842 return false;
1843 This = &ThisVal;
1844 Args = Args.slice(1);
1845 }
1846
1847 // Don't call function pointers which have been cast to some other type.
1848 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00001849 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00001850 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00001851 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001852
Richard Smithc1c5f272011-12-13 06:39:58 +00001853 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00001854 Stmt *Body = FD->getBody(Definition);
Richard Smith69c2c502011-11-04 05:33:44 +00001855 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00001856
Richard Smithc1c5f272011-12-13 06:39:58 +00001857 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
1858 !HandleFunctionCall(E, This, Args, Body, Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00001859 return false;
1860
1861 return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
Richard Smithd0dccea2011-10-28 22:34:42 +00001862 }
1863
Richard Smithc49bd112011-10-28 17:51:58 +00001864 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1865 return StmtVisitorTy::Visit(E->getInitializer());
1866 }
Richard Smithf10d9172011-10-11 21:43:33 +00001867 RetTy VisitInitListExpr(const InitListExpr *E) {
1868 if (Info.getLangOpts().CPlusPlus0x) {
1869 if (E->getNumInits() == 0)
1870 return DerivedValueInitialization(E);
1871 if (E->getNumInits() == 1)
1872 return StmtVisitorTy::Visit(E->getInit(0));
1873 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001874 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00001875 }
1876 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1877 return DerivedValueInitialization(E);
1878 }
1879 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1880 return DerivedValueInitialization(E);
1881 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001882 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
1883 return DerivedValueInitialization(E);
1884 }
Richard Smithf10d9172011-10-11 21:43:33 +00001885
Richard Smith180f4792011-11-10 06:34:14 +00001886 /// A member expression where the object is a prvalue is itself a prvalue.
1887 RetTy VisitMemberExpr(const MemberExpr *E) {
1888 assert(!E->isArrow() && "missing call to bound member function?");
1889
1890 CCValue Val;
1891 if (!Evaluate(Val, Info, E->getBase()))
1892 return false;
1893
1894 QualType BaseTy = E->getBase()->getType();
1895
1896 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00001897 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00001898 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1899 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1900 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1901
1902 SubobjectDesignator Designator;
1903 Designator.addDecl(FD);
1904
Richard Smithf48fdb02011-12-09 22:58:01 +00001905 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00001906 DerivedSuccess(Val, E);
1907 }
1908
Richard Smithc49bd112011-10-28 17:51:58 +00001909 RetTy VisitCastExpr(const CastExpr *E) {
1910 switch (E->getCastKind()) {
1911 default:
1912 break;
1913
1914 case CK_NoOp:
1915 return StmtVisitorTy::Visit(E->getSubExpr());
1916
1917 case CK_LValueToRValue: {
1918 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00001919 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
1920 return false;
1921 CCValue RVal;
1922 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
1923 return false;
1924 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00001925 }
1926 }
1927
Richard Smithf48fdb02011-12-09 22:58:01 +00001928 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00001929 }
1930
Richard Smith8327fad2011-10-24 18:44:57 +00001931 /// Visit a value which is evaluated, but whose value is ignored.
1932 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00001933 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00001934 if (!Evaluate(Scratch, Info, E))
1935 Info.EvalStatus.HasSideEffects = true;
1936 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001937};
1938
1939}
1940
1941//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00001942// Common base class for lvalue and temporary evaluation.
1943//===----------------------------------------------------------------------===//
1944namespace {
1945template<class Derived>
1946class LValueExprEvaluatorBase
1947 : public ExprEvaluatorBase<Derived, bool> {
1948protected:
1949 LValue &Result;
1950 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
1951 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
1952
1953 bool Success(APValue::LValueBase B) {
1954 Result.set(B);
1955 return true;
1956 }
1957
1958public:
1959 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
1960 ExprEvaluatorBaseTy(Info), Result(Result) {}
1961
1962 bool Success(const CCValue &V, const Expr *E) {
1963 Result.setFrom(V);
1964 return true;
1965 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001966
1967 bool CheckValidLValue() {
1968 // C++11 [basic.lval]p1: An lvalue designates a function or an object. Hence
1969 // there are no null references, nor once-past-the-end references.
1970 // FIXME: Check for one-past-the-end array indices
1971 return Result.Base && !Result.Designator.Invalid &&
1972 !Result.Designator.OnePastTheEnd;
1973 }
1974
1975 bool VisitMemberExpr(const MemberExpr *E) {
1976 // Handle non-static data members.
1977 QualType BaseTy;
1978 if (E->isArrow()) {
1979 if (!EvaluatePointer(E->getBase(), Result, this->Info))
1980 return false;
1981 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00001982 } else if (E->getBase()->isRValue()) {
1983 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
1984 return false;
1985 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 } else {
1987 if (!this->Visit(E->getBase()))
1988 return false;
1989 BaseTy = E->getBase()->getType();
1990 }
1991 // FIXME: In C++11, require the result to be a valid lvalue.
1992
1993 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1994 // FIXME: Handle IndirectFieldDecls
Richard Smithf48fdb02011-12-09 22:58:01 +00001995 if (!FD) return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1997 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1998 (void)BaseTy;
1999
2000 HandleLValueMember(this->Info, Result, FD);
2001
2002 if (FD->getType()->isReferenceType()) {
2003 CCValue RefValue;
Richard Smithf48fdb02011-12-09 22:58:01 +00002004 if (!HandleLValueToRValueConversion(this->Info, E, FD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002005 RefValue))
2006 return false;
2007 return Success(RefValue, E);
2008 }
2009 return true;
2010 }
2011
2012 bool VisitBinaryOperator(const BinaryOperator *E) {
2013 switch (E->getOpcode()) {
2014 default:
2015 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2016
2017 case BO_PtrMemD:
2018 case BO_PtrMemI:
2019 return HandleMemberPointerAccess(this->Info, E, Result);
2020 }
2021 }
2022
2023 bool VisitCastExpr(const CastExpr *E) {
2024 switch (E->getCastKind()) {
2025 default:
2026 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2027
2028 case CK_DerivedToBase:
2029 case CK_UncheckedDerivedToBase: {
2030 if (!this->Visit(E->getSubExpr()))
2031 return false;
2032 if (!CheckValidLValue())
2033 return false;
2034
2035 // Now figure out the necessary offset to add to the base LV to get from
2036 // the derived class to the base class.
2037 QualType Type = E->getSubExpr()->getType();
2038
2039 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2040 PathE = E->path_end(); PathI != PathE; ++PathI) {
2041 if (!HandleLValueBase(this->Info, Result, Type->getAsCXXRecordDecl(),
2042 *PathI))
2043 return false;
2044 Type = (*PathI)->getType();
2045 }
2046
2047 return true;
2048 }
2049 }
2050 }
2051};
2052}
2053
2054//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002055// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002056//
2057// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2058// function designators (in C), decl references to void objects (in C), and
2059// temporaries (if building with -Wno-address-of-temporary).
2060//
2061// LValue evaluation produces values comprising a base expression of one of the
2062// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002063// - Declarations
2064// * VarDecl
2065// * FunctionDecl
2066// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002067// * CompoundLiteralExpr in C
2068// * StringLiteral
2069// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002070// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002071// * ObjCEncodeExpr
2072// * AddrLabelExpr
2073// * BlockExpr
2074// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002075// - Locals and temporaries
2076// * Any Expr, with a Frame indicating the function in which the temporary was
2077// evaluated.
2078// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002079//===----------------------------------------------------------------------===//
2080namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002081class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002082 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002083public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002084 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2085 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Richard Smithc49bd112011-10-28 17:51:58 +00002087 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2088
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002089 bool VisitDeclRefExpr(const DeclRefExpr *E);
2090 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002091 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002092 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2093 bool VisitMemberExpr(const MemberExpr *E);
2094 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2095 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2096 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2097 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002098
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002099 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002100 switch (E->getCastKind()) {
2101 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002102 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002103
Eli Friedmandb924222011-10-11 00:13:24 +00002104 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002105 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002106 if (!Visit(E->getSubExpr()))
2107 return false;
2108 Result.Designator.setInvalid();
2109 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002110
Richard Smithe24f5fc2011-11-17 22:56:20 +00002111 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002112 if (!Visit(E->getSubExpr()))
2113 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002114 if (!CheckValidLValue())
2115 return false;
2116 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002117 }
2118 }
Sebastian Redlcea8d962011-09-24 17:48:14 +00002119
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002120 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002121
Eli Friedman4efaa272008-11-12 09:44:48 +00002122};
2123} // end anonymous namespace
2124
Richard Smithc49bd112011-10-28 17:51:58 +00002125/// Evaluate an expression as an lvalue. This can be legitimately called on
2126/// expressions which are not glvalues, in a few cases:
2127/// * function designators in C,
2128/// * "extern void" objects,
2129/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002130static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002131 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2132 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2133 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002134 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002135}
2136
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002137bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002138 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2139 return Success(FD);
2140 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002141 return VisitVarDecl(E, VD);
2142 return Error(E);
2143}
Richard Smith436c8892011-10-24 23:14:33 +00002144
Richard Smithc49bd112011-10-28 17:51:58 +00002145bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002146 if (!VD->getType()->isReferenceType()) {
2147 if (isa<ParmVarDecl>(VD)) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002148 Result.set(VD, Info.CurrentCall);
Richard Smith177dce72011-11-01 16:57:24 +00002149 return true;
2150 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002151 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002152 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002153
Richard Smith47a1eed2011-10-29 20:57:55 +00002154 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002155 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2156 return false;
2157 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002158}
2159
Richard Smithbd552ef2011-10-31 05:52:43 +00002160bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2161 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002162 if (E->GetTemporaryExpr()->isRValue()) {
2163 if (E->getType()->isRecordType() && E->getType()->isLiteralType())
2164 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2165
2166 Result.set(E, Info.CurrentCall);
2167 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2168 Result, E->GetTemporaryExpr());
2169 }
2170
2171 // Materialization of an lvalue temporary occurs when we need to force a copy
2172 // (for instance, if it's a bitfield).
2173 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2174 if (!Visit(E->GetTemporaryExpr()))
2175 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002176 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002177 Info.CurrentCall->Temporaries[E]))
2178 return false;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002179 Result.set(E, Info.CurrentCall);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002180 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002181}
2182
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002183bool
2184LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002185 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2186 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2187 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002188 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002189}
2190
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002191bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002192 // Handle static data members.
2193 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2194 VisitIgnoredValue(E->getBase());
2195 return VisitVarDecl(E, VD);
2196 }
2197
Richard Smithd0dccea2011-10-28 22:34:42 +00002198 // Handle static member functions.
2199 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2200 if (MD->isStatic()) {
2201 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002202 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002203 }
2204 }
2205
Richard Smith180f4792011-11-10 06:34:14 +00002206 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002207 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002208}
2209
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002210bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002211 // FIXME: Deal with vectors as array subscript bases.
2212 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002213 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002214
Anders Carlsson3068d112008-11-16 19:01:22 +00002215 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002216 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002217
Anders Carlsson3068d112008-11-16 19:01:22 +00002218 APSInt Index;
2219 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002220 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002221 int64_t IndexValue
2222 = Index.isSigned() ? Index.getSExtValue()
2223 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002224
Richard Smithe24f5fc2011-11-17 22:56:20 +00002225 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002226 return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002227}
Eli Friedman4efaa272008-11-12 09:44:48 +00002228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002229bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002230 // FIXME: In C++11, require the result to be a valid lvalue.
John McCallefdb83e2010-05-07 21:00:08 +00002231 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002232}
2233
Eli Friedman4efaa272008-11-12 09:44:48 +00002234//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002235// Pointer Evaluation
2236//===----------------------------------------------------------------------===//
2237
Anders Carlssonc754aa62008-07-08 05:13:58 +00002238namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002239class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002240 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002241 LValue &Result;
2242
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002243 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002244 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002245 return true;
2246 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002247public:
Mike Stump1eb44332009-09-09 15:08:12 +00002248
John McCallefdb83e2010-05-07 21:00:08 +00002249 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002250 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002251
Richard Smith47a1eed2011-10-29 20:57:55 +00002252 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253 Result.setFrom(V);
2254 return true;
2255 }
Richard Smithf10d9172011-10-11 21:43:33 +00002256 bool ValueInitialization(const Expr *E) {
2257 return Success((Expr*)0);
2258 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002259
John McCallefdb83e2010-05-07 21:00:08 +00002260 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002261 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002262 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002263 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002264 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002265 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002266 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267 bool VisitCallExpr(const CallExpr *E);
2268 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002269 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002270 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002271 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002272 }
Richard Smith180f4792011-11-10 06:34:14 +00002273 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2274 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00002275 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002276 Result = *Info.CurrentCall->This;
2277 return true;
2278 }
John McCall56ca35d2011-02-17 10:25:35 +00002279
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002280 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00002281};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002282} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00002283
John McCallefdb83e2010-05-07 21:00:08 +00002284static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002285 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002286 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002287}
2288
John McCallefdb83e2010-05-07 21:00:08 +00002289bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002290 if (E->getOpcode() != BO_Add &&
2291 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00002292 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002294 const Expr *PExp = E->getLHS();
2295 const Expr *IExp = E->getRHS();
2296 if (IExp->getType()->isPointerType())
2297 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002298
John McCallefdb83e2010-05-07 21:00:08 +00002299 if (!EvaluatePointer(PExp, Result, Info))
2300 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002301
John McCallefdb83e2010-05-07 21:00:08 +00002302 llvm::APSInt Offset;
2303 if (!EvaluateInteger(IExp, Offset, Info))
2304 return false;
2305 int64_t AdditionalOffset
2306 = Offset.isSigned() ? Offset.getSExtValue()
2307 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00002308 if (E->getOpcode() == BO_Sub)
2309 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002310
Richard Smith180f4792011-11-10 06:34:14 +00002311 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002312 // FIXME: In C++11, require the result to be a valid lvalue.
Richard Smith180f4792011-11-10 06:34:14 +00002313 return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002314}
Eli Friedman4efaa272008-11-12 09:44:48 +00002315
John McCallefdb83e2010-05-07 21:00:08 +00002316bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2317 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002318}
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002320bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2321 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002322
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002323 switch (E->getCastKind()) {
2324 default:
2325 break;
2326
John McCall2de56d12010-08-25 11:45:40 +00002327 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002328 case CK_CPointerToObjCPointerCast:
2329 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00002330 case CK_AnyPointerToBlockPointerCast:
Richard Smithc216a012011-12-12 12:46:16 +00002331 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2332 // permitted in constant expressions in C++11. Bitcasts from cv void* are
2333 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00002334 if (!E->getType()->isVoidPointerType()) {
2335 if (SubExpr->getType()->isVoidPointerType())
2336 CCEDiag(E, diag::note_constexpr_invalid_cast)
2337 << 3 << SubExpr->getType();
2338 else
2339 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2340 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002341 if (!Visit(SubExpr))
2342 return false;
2343 Result.Designator.setInvalid();
2344 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002345
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002346 case CK_DerivedToBase:
2347 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00002348 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002349 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002350 if (!Result.Base && Result.Offset.isZero())
2351 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002352
Richard Smith180f4792011-11-10 06:34:14 +00002353 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002354 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00002355 QualType Type =
2356 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002357
Richard Smith180f4792011-11-10 06:34:14 +00002358 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002359 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smith180f4792011-11-10 06:34:14 +00002360 if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002361 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002362 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002363 }
2364
Anders Carlsson5c5a7642010-10-31 20:41:46 +00002365 return true;
2366 }
2367
Richard Smithe24f5fc2011-11-17 22:56:20 +00002368 case CK_BaseToDerived:
2369 if (!Visit(E->getSubExpr()))
2370 return false;
2371 if (!Result.Base && Result.Offset.isZero())
2372 return true;
2373 return HandleBaseToDerivedCast(Info, E, Result);
2374
Richard Smith47a1eed2011-10-29 20:57:55 +00002375 case CK_NullToPointer:
2376 return ValueInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00002377
John McCall2de56d12010-08-25 11:45:40 +00002378 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00002379 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2380
Richard Smith47a1eed2011-10-29 20:57:55 +00002381 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00002382 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00002383 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00002384
John McCallefdb83e2010-05-07 21:00:08 +00002385 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002386 unsigned Size = Info.Ctx.getTypeSize(E->getType());
2387 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002388 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00002389 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith177dce72011-11-01 16:57:24 +00002390 Result.Frame = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002391 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00002392 return true;
2393 } else {
2394 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00002395 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00002396 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002397 }
2398 }
John McCall2de56d12010-08-25 11:45:40 +00002399 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002400 if (SubExpr->isGLValue()) {
2401 if (!EvaluateLValue(SubExpr, Result, Info))
2402 return false;
2403 } else {
2404 Result.set(SubExpr, Info.CurrentCall);
2405 if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2406 Info, Result, SubExpr))
2407 return false;
2408 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00002409 // The result is a pointer to the first element of the array.
2410 Result.Designator.addIndex(0);
2411 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00002412
John McCall2de56d12010-08-25 11:45:40 +00002413 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00002414 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00002415 }
2416
Richard Smithc49bd112011-10-28 17:51:58 +00002417 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002418}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002419
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002420bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00002421 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00002422 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00002423
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002424 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002425}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002426
2427//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002428// Member Pointer Evaluation
2429//===----------------------------------------------------------------------===//
2430
2431namespace {
2432class MemberPointerExprEvaluator
2433 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2434 MemberPtr &Result;
2435
2436 bool Success(const ValueDecl *D) {
2437 Result = MemberPtr(D);
2438 return true;
2439 }
2440public:
2441
2442 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2443 : ExprEvaluatorBaseTy(Info), Result(Result) {}
2444
2445 bool Success(const CCValue &V, const Expr *E) {
2446 Result.setFrom(V);
2447 return true;
2448 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002449 bool ValueInitialization(const Expr *E) {
2450 return Success((const ValueDecl*)0);
2451 }
2452
2453 bool VisitCastExpr(const CastExpr *E);
2454 bool VisitUnaryAddrOf(const UnaryOperator *E);
2455};
2456} // end anonymous namespace
2457
2458static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2459 EvalInfo &Info) {
2460 assert(E->isRValue() && E->getType()->isMemberPointerType());
2461 return MemberPointerExprEvaluator(Info, Result).Visit(E);
2462}
2463
2464bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2465 switch (E->getCastKind()) {
2466 default:
2467 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2468
2469 case CK_NullToMemberPointer:
2470 return ValueInitialization(E);
2471
2472 case CK_BaseToDerivedMemberPointer: {
2473 if (!Visit(E->getSubExpr()))
2474 return false;
2475 if (E->path_empty())
2476 return true;
2477 // Base-to-derived member pointer casts store the path in derived-to-base
2478 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2479 // the wrong end of the derived->base arc, so stagger the path by one class.
2480 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2481 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2482 PathI != PathE; ++PathI) {
2483 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2484 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2485 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00002486 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002487 }
2488 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2489 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002490 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491 return true;
2492 }
2493
2494 case CK_DerivedToBaseMemberPointer:
2495 if (!Visit(E->getSubExpr()))
2496 return false;
2497 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2498 PathE = E->path_end(); PathI != PathE; ++PathI) {
2499 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2500 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2501 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503 }
2504 return true;
2505 }
2506}
2507
2508bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2509 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
2510 // member can be formed.
2511 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
2512}
2513
2514//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00002515// Record Evaluation
2516//===----------------------------------------------------------------------===//
2517
2518namespace {
2519 class RecordExprEvaluator
2520 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
2521 const LValue &This;
2522 APValue &Result;
2523 public:
2524
2525 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
2526 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
2527
2528 bool Success(const CCValue &V, const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002529 return CheckConstantExpression(Info, E, V, Result);
Richard Smith180f4792011-11-10 06:34:14 +00002530 }
Richard Smith180f4792011-11-10 06:34:14 +00002531
Richard Smith59efe262011-11-11 04:05:33 +00002532 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00002533 bool VisitInitListExpr(const InitListExpr *E);
2534 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
2535 };
2536}
2537
Richard Smith59efe262011-11-11 04:05:33 +00002538bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
2539 switch (E->getCastKind()) {
2540 default:
2541 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2542
2543 case CK_ConstructorConversion:
2544 return Visit(E->getSubExpr());
2545
2546 case CK_DerivedToBase:
2547 case CK_UncheckedDerivedToBase: {
2548 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00002549 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00002550 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002551 if (!DerivedObject.isStruct())
2552 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00002553
2554 // Derived-to-base rvalue conversion: just slice off the derived part.
2555 APValue *Value = &DerivedObject;
2556 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
2557 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2558 PathE = E->path_end(); PathI != PathE; ++PathI) {
2559 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
2560 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2561 Value = &Value->getStructBase(getBaseIndex(RD, Base));
2562 RD = Base;
2563 }
2564 Result = *Value;
2565 return true;
2566 }
2567 }
2568}
2569
Richard Smith180f4792011-11-10 06:34:14 +00002570bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2571 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
2572 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2573
2574 if (RD->isUnion()) {
2575 Result = APValue(E->getInitializedFieldInUnion());
2576 if (!E->getNumInits())
2577 return true;
2578 LValue Subobject = This;
2579 HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
2580 &Layout);
2581 return EvaluateConstantExpression(Result.getUnionValue(), Info,
2582 Subobject, E->getInit(0));
2583 }
2584
2585 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
2586 "initializer list for class with base classes");
2587 Result = APValue(APValue::UninitStruct(), 0,
2588 std::distance(RD->field_begin(), RD->field_end()));
2589 unsigned ElementNo = 0;
2590 for (RecordDecl::field_iterator Field = RD->field_begin(),
2591 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
2592 // Anonymous bit-fields are not considered members of the class for
2593 // purposes of aggregate initialization.
2594 if (Field->isUnnamedBitfield())
2595 continue;
2596
2597 LValue Subobject = This;
2598 HandleLValueMember(Info, Subobject, *Field, &Layout);
2599
2600 if (ElementNo < E->getNumInits()) {
2601 if (!EvaluateConstantExpression(
2602 Result.getStructField((*Field)->getFieldIndex()),
2603 Info, Subobject, E->getInit(ElementNo++)))
2604 return false;
2605 } else {
2606 // Perform an implicit value-initialization for members beyond the end of
2607 // the initializer list.
2608 ImplicitValueInitExpr VIE(Field->getType());
2609 if (!EvaluateConstantExpression(
2610 Result.getStructField((*Field)->getFieldIndex()),
2611 Info, Subobject, &VIE))
2612 return false;
2613 }
2614 }
2615
2616 return true;
2617}
2618
2619bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2620 const CXXConstructorDecl *FD = E->getConstructor();
2621 const FunctionDecl *Definition = 0;
2622 FD->getBody(Definition);
2623
Richard Smithc1c5f272011-12-13 06:39:58 +00002624 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2625 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002626
2627 // FIXME: Elide the copy/move construction wherever we can.
2628 if (E->isElidable())
2629 if (const MaterializeTemporaryExpr *ME
2630 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
2631 return Visit(ME->GetTemporaryExpr());
2632
2633 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002634 return HandleConstructorCall(E, This, Args,
2635 cast<CXXConstructorDecl>(Definition), Info,
2636 Result);
Richard Smith180f4792011-11-10 06:34:14 +00002637}
2638
2639static bool EvaluateRecord(const Expr *E, const LValue &This,
2640 APValue &Result, EvalInfo &Info) {
2641 assert(E->isRValue() && E->getType()->isRecordType() &&
2642 E->getType()->isLiteralType() &&
2643 "can't evaluate expression as a record rvalue");
2644 return RecordExprEvaluator(Info, This, Result).Visit(E);
2645}
2646
2647//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002648// Temporary Evaluation
2649//
2650// Temporaries are represented in the AST as rvalues, but generally behave like
2651// lvalues. The full-object of which the temporary is a subobject is implicitly
2652// materialized so that a reference can bind to it.
2653//===----------------------------------------------------------------------===//
2654namespace {
2655class TemporaryExprEvaluator
2656 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
2657public:
2658 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
2659 LValueExprEvaluatorBaseTy(Info, Result) {}
2660
2661 /// Visit an expression which constructs the value of this temporary.
2662 bool VisitConstructExpr(const Expr *E) {
2663 Result.set(E, Info.CurrentCall);
2664 return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2665 Result, E);
2666 }
2667
2668 bool VisitCastExpr(const CastExpr *E) {
2669 switch (E->getCastKind()) {
2670 default:
2671 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2672
2673 case CK_ConstructorConversion:
2674 return VisitConstructExpr(E->getSubExpr());
2675 }
2676 }
2677 bool VisitInitListExpr(const InitListExpr *E) {
2678 return VisitConstructExpr(E);
2679 }
2680 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
2681 return VisitConstructExpr(E);
2682 }
2683 bool VisitCallExpr(const CallExpr *E) {
2684 return VisitConstructExpr(E);
2685 }
2686};
2687} // end anonymous namespace
2688
2689/// Evaluate an expression of record type as a temporary.
2690static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
2691 assert(E->isRValue() && E->getType()->isRecordType() &&
2692 E->getType()->isLiteralType());
2693 return TemporaryExprEvaluator(Info, Result).Visit(E);
2694}
2695
2696//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00002697// Vector Evaluation
2698//===----------------------------------------------------------------------===//
2699
2700namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002701 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00002702 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
2703 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00002704 public:
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Richard Smith07fc6572011-10-22 21:10:00 +00002706 VectorExprEvaluator(EvalInfo &info, APValue &Result)
2707 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002708
Richard Smith07fc6572011-10-22 21:10:00 +00002709 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
2710 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
2711 // FIXME: remove this APValue copy.
2712 Result = APValue(V.data(), V.size());
2713 return true;
2714 }
Richard Smith69c2c502011-11-04 05:33:44 +00002715 bool Success(const CCValue &V, const Expr *E) {
2716 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00002717 Result = V;
2718 return true;
2719 }
Richard Smith07fc6572011-10-22 21:10:00 +00002720 bool ValueInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Richard Smith07fc6572011-10-22 21:10:00 +00002722 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00002723 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00002724 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00002725 bool VisitInitListExpr(const InitListExpr *E);
2726 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002727 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00002728 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00002729 // shufflevector, ExtVectorElementExpr
2730 // (Note that these require implementing conversions
2731 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +00002732 };
2733} // end anonymous namespace
2734
2735static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002736 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00002737 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002738}
2739
Richard Smith07fc6572011-10-22 21:10:00 +00002740bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2741 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00002742 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002743
Richard Smithd62ca372011-12-06 22:44:34 +00002744 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00002745 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00002746
Eli Friedman46a52322011-03-25 00:43:55 +00002747 switch (E->getCastKind()) {
2748 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00002749 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00002750 if (SETy->isIntegerType()) {
2751 APSInt IntResult;
2752 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002753 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002754 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00002755 } else if (SETy->isRealFloatingType()) {
2756 APFloat F(0.0);
2757 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002758 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00002759 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00002760 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00002761 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002762 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00002763
2764 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00002765 SmallVector<APValue, 4> Elts(NElts, Val);
2766 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00002767 }
Eli Friedman46a52322011-03-25 00:43:55 +00002768 default:
Richard Smithc49bd112011-10-28 17:51:58 +00002769 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00002770 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002771}
2772
Richard Smith07fc6572011-10-22 21:10:00 +00002773bool
Nate Begeman59b5da62009-01-18 03:20:47 +00002774VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00002775 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00002776 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00002777 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00002778
Nate Begeman59b5da62009-01-18 03:20:47 +00002779 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002780 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00002781
John McCalla7d6c222010-06-11 17:54:15 +00002782 // If a vector is initialized with a single element, that value
2783 // becomes every element of the vector, not just the first.
2784 // This is the behavior described in the IBM AltiVec documentation.
2785 if (NumInits == 1) {
Richard Smith07fc6572011-10-22 21:10:00 +00002786
2787 // Handle the case where the vector is initialized by another
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +00002788 // vector (OpenCL 6.1.6).
2789 if (E->getInit(0)->getType()->isVectorType())
Richard Smith07fc6572011-10-22 21:10:00 +00002790 return Visit(E->getInit(0));
2791
John McCalla7d6c222010-06-11 17:54:15 +00002792 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +00002793 if (EltTy->isIntegerType()) {
2794 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +00002795 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002796 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002797 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +00002798 } else {
2799 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +00002800 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002801 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002802 InitValue = APValue(f);
2803 }
2804 for (unsigned i = 0; i < NumElements; i++) {
2805 Elements.push_back(InitValue);
2806 }
2807 } else {
2808 for (unsigned i = 0; i < NumElements; i++) {
2809 if (EltTy->isIntegerType()) {
2810 llvm::APSInt sInt(32);
2811 if (i < NumInits) {
2812 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002813 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002814 } else {
2815 sInt = Info.Ctx.MakeIntValue(0, EltTy);
2816 }
2817 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +00002818 } else {
John McCalla7d6c222010-06-11 17:54:15 +00002819 llvm::APFloat f(0.0);
2820 if (i < NumInits) {
2821 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002822 return false;
John McCalla7d6c222010-06-11 17:54:15 +00002823 } else {
2824 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2825 }
2826 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +00002827 }
Nate Begeman59b5da62009-01-18 03:20:47 +00002828 }
2829 }
Richard Smith07fc6572011-10-22 21:10:00 +00002830 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00002831}
2832
Richard Smith07fc6572011-10-22 21:10:00 +00002833bool
2834VectorExprEvaluator::ValueInitialization(const Expr *E) {
2835 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00002836 QualType EltTy = VT->getElementType();
2837 APValue ZeroElement;
2838 if (EltTy->isIntegerType())
2839 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2840 else
2841 ZeroElement =
2842 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2843
Chris Lattner5f9e2722011-07-23 10:55:15 +00002844 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00002845 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002846}
2847
Richard Smith07fc6572011-10-22 21:10:00 +00002848bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00002849 VisitIgnoredValue(E->getSubExpr());
Richard Smith07fc6572011-10-22 21:10:00 +00002850 return ValueInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00002851}
2852
Nate Begeman59b5da62009-01-18 03:20:47 +00002853//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00002854// Array Evaluation
2855//===----------------------------------------------------------------------===//
2856
2857namespace {
2858 class ArrayExprEvaluator
2859 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00002860 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002861 APValue &Result;
2862 public:
2863
Richard Smith180f4792011-11-10 06:34:14 +00002864 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2865 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00002866
2867 bool Success(const APValue &V, const Expr *E) {
2868 assert(V.isArray() && "Expected array type");
2869 Result = V;
2870 return true;
2871 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002872
Richard Smith180f4792011-11-10 06:34:14 +00002873 bool ValueInitialization(const Expr *E) {
2874 const ConstantArrayType *CAT =
2875 Info.Ctx.getAsConstantArrayType(E->getType());
2876 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002877 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002878
2879 Result = APValue(APValue::UninitArray(), 0,
2880 CAT->getSize().getZExtValue());
2881 if (!Result.hasArrayFiller()) return true;
2882
2883 // Value-initialize all elements.
2884 LValue Subobject = This;
2885 Subobject.Designator.addIndex(0);
2886 ImplicitValueInitExpr VIE(CAT->getElementType());
2887 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2888 Subobject, &VIE);
2889 }
2890
Richard Smithcc5d4f62011-11-07 09:22:26 +00002891 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002892 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002893 };
2894} // end anonymous namespace
2895
Richard Smith180f4792011-11-10 06:34:14 +00002896static bool EvaluateArray(const Expr *E, const LValue &This,
2897 APValue &Result, EvalInfo &Info) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00002898 assert(E->isRValue() && E->getType()->isArrayType() &&
2899 E->getType()->isLiteralType() && "not a literal array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00002900 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002901}
2902
2903bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2904 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2905 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002906 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00002907
2908 Result = APValue(APValue::UninitArray(), E->getNumInits(),
2909 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00002910 LValue Subobject = This;
2911 Subobject.Designator.addIndex(0);
2912 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00002913 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00002914 I != End; ++I, ++Index) {
2915 if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2916 Info, Subobject, cast<Expr>(*I)))
Richard Smithcc5d4f62011-11-07 09:22:26 +00002917 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002918 if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2919 return false;
2920 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00002921
2922 if (!Result.hasArrayFiller()) return true;
2923 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00002924 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2925 // but sometimes does:
2926 // struct S { constexpr S() : p(&p) {} void *p; };
2927 // S s[10] = {};
Richard Smithcc5d4f62011-11-07 09:22:26 +00002928 return EvaluateConstantExpression(Result.getArrayFiller(), Info,
Richard Smith180f4792011-11-10 06:34:14 +00002929 Subobject, E->getArrayFiller());
Richard Smithcc5d4f62011-11-07 09:22:26 +00002930}
2931
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2933 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2934 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00002935 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002936
2937 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
2938 if (!Result.hasArrayFiller())
2939 return true;
2940
2941 const CXXConstructorDecl *FD = E->getConstructor();
2942 const FunctionDecl *Definition = 0;
2943 FD->getBody(Definition);
2944
Richard Smithc1c5f272011-12-13 06:39:58 +00002945 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
2946 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002947
2948 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2949 // but sometimes does:
2950 // struct S { constexpr S() : p(&p) {} void *p; };
2951 // S s[10];
2952 LValue Subobject = This;
2953 Subobject.Designator.addIndex(0);
2954 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smithf48fdb02011-12-09 22:58:01 +00002955 return HandleConstructorCall(E, Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002956 cast<CXXConstructorDecl>(Definition),
2957 Info, Result.getArrayFiller());
2958}
2959
Richard Smithcc5d4f62011-11-07 09:22:26 +00002960//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002961// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002962//
2963// As a GNU extension, we support casting pointers to sufficiently-wide integer
2964// types and back in constant folding. Integer values are thus represented
2965// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002966//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002967
2968namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002969class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002970 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00002971 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00002972public:
Richard Smith47a1eed2011-10-29 20:57:55 +00002973 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002974 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002975
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002976 bool Success(const llvm::APSInt &SI, const Expr *E) {
2977 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002978 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002979 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002980 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00002981 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002982 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002983 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002984 return true;
2985 }
2986
Daniel Dunbar131eb432009-02-19 09:06:44 +00002987 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002988 assert(E->getType()->isIntegralOrEnumerationType() &&
2989 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002990 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002991 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00002992 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00002993 Result.getInt().setIsUnsigned(
2994 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00002995 return true;
2996 }
2997
2998 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002999 assert(E->getType()->isIntegralOrEnumerationType() &&
3000 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00003001 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003002 return true;
3003 }
3004
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003005 bool Success(CharUnits Size, const Expr *E) {
3006 return Success(Size.getQuantity(), E);
3007 }
3008
Richard Smith47a1eed2011-10-29 20:57:55 +00003009 bool Success(const CCValue &V, const Expr *E) {
Richard Smith342f1f82011-10-29 22:55:55 +00003010 if (V.isLValue()) {
3011 Result = V;
3012 return true;
3013 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003014 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003015 }
Mike Stump1eb44332009-09-09 15:08:12 +00003016
Richard Smithf10d9172011-10-11 21:43:33 +00003017 bool ValueInitialization(const Expr *E) { return Success(0, E); }
3018
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003019 //===--------------------------------------------------------------------===//
3020 // Visitor Methods
3021 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003022
Chris Lattner4c4867e2008-07-12 00:38:25 +00003023 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003024 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003025 }
3026 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003027 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003028 }
Eli Friedman04309752009-11-24 05:28:59 +00003029
3030 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3031 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003032 if (CheckReferencedDecl(E, E->getDecl()))
3033 return true;
3034
3035 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003036 }
3037 bool VisitMemberExpr(const MemberExpr *E) {
3038 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003039 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003040 return true;
3041 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003042
3043 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003044 }
3045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003047 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003048 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003049 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00003050
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003052 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00003053
Anders Carlsson3068d112008-11-16 19:01:22 +00003054 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003055 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00003056 }
Mike Stump1eb44332009-09-09 15:08:12 +00003057
Richard Smithf10d9172011-10-11 21:43:33 +00003058 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00003059 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003060 return ValueInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00003061 }
3062
Sebastian Redl64b45f72009-01-05 20:52:13 +00003063 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00003064 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003065 }
3066
Francois Pichet6ad6f282010-12-07 00:08:36 +00003067 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3068 return Success(E->getValue(), E);
3069 }
3070
John Wiegley21ff2e52011-04-28 00:16:57 +00003071 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3072 return Success(E->getValue(), E);
3073 }
3074
John Wiegley55262202011-04-25 06:54:41 +00003075 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3076 return Success(E->getValue(), E);
3077 }
3078
Eli Friedman722c7172009-02-28 03:59:05 +00003079 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003080 bool VisitUnaryImag(const UnaryOperator *E);
3081
Sebastian Redl295995c2010-09-10 20:55:47 +00003082 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00003083 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00003084
Chris Lattnerfcee0012008-07-11 21:24:13 +00003085private:
Ken Dyck8b752f12010-01-27 17:10:57 +00003086 CharUnits GetAlignOfExpr(const Expr *E);
3087 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003088 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003089 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00003090 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003091};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003092} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003093
Richard Smithc49bd112011-10-28 17:51:58 +00003094/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3095/// produce either the integer value or a pointer.
3096///
3097/// GCC has a heinous extension which folds casts between pointer types and
3098/// pointer-sized integral types. We support this by allowing the evaluation of
3099/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3100/// Some simple arithmetic on such values is supported (they are treated much
3101/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00003102static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00003103 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003104 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003105 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003106}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003107
Richard Smithf48fdb02011-12-09 22:58:01 +00003108static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003109 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00003110 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003111 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003112 if (!Val.isInt()) {
3113 // FIXME: It would be better to produce the diagnostic for casting
3114 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00003115 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00003116 return false;
3117 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003118 Result = Val.getInt();
3119 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00003120}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003121
Richard Smithf48fdb02011-12-09 22:58:01 +00003122/// Check whether the given declaration can be directly converted to an integral
3123/// rvalue. If not, no diagnostic is produced; there are other things we can
3124/// try.
Eli Friedman04309752009-11-24 05:28:59 +00003125bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00003126 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003127 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003128 // Check for signedness/width mismatches between E type and ECD value.
3129 bool SameSign = (ECD->getInitVal().isSigned()
3130 == E->getType()->isSignedIntegerOrEnumerationType());
3131 bool SameWidth = (ECD->getInitVal().getBitWidth()
3132 == Info.Ctx.getIntWidth(E->getType()));
3133 if (SameSign && SameWidth)
3134 return Success(ECD->getInitVal(), E);
3135 else {
3136 // Get rid of mismatch (otherwise Success assertions will fail)
3137 // by computing a new value matching the type of E.
3138 llvm::APSInt Val = ECD->getInitVal();
3139 if (!SameSign)
3140 Val.setIsSigned(!ECD->getInitVal().isSigned());
3141 if (!SameWidth)
3142 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3143 return Success(Val, E);
3144 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00003145 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003146 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00003147}
3148
Chris Lattnera4d55d82008-10-06 06:40:35 +00003149/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3150/// as GCC.
3151static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3152 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003153 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00003154 enum gcc_type_class {
3155 no_type_class = -1,
3156 void_type_class, integer_type_class, char_type_class,
3157 enumeral_type_class, boolean_type_class,
3158 pointer_type_class, reference_type_class, offset_type_class,
3159 real_type_class, complex_type_class,
3160 function_type_class, method_type_class,
3161 record_type_class, union_type_class,
3162 array_type_class, string_type_class,
3163 lang_type_class
3164 };
Mike Stump1eb44332009-09-09 15:08:12 +00003165
3166 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00003167 // ideal, however it is what gcc does.
3168 if (E->getNumArgs() == 0)
3169 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Chris Lattnera4d55d82008-10-06 06:40:35 +00003171 QualType ArgTy = E->getArg(0)->getType();
3172 if (ArgTy->isVoidType())
3173 return void_type_class;
3174 else if (ArgTy->isEnumeralType())
3175 return enumeral_type_class;
3176 else if (ArgTy->isBooleanType())
3177 return boolean_type_class;
3178 else if (ArgTy->isCharType())
3179 return string_type_class; // gcc doesn't appear to use char_type_class
3180 else if (ArgTy->isIntegerType())
3181 return integer_type_class;
3182 else if (ArgTy->isPointerType())
3183 return pointer_type_class;
3184 else if (ArgTy->isReferenceType())
3185 return reference_type_class;
3186 else if (ArgTy->isRealType())
3187 return real_type_class;
3188 else if (ArgTy->isComplexType())
3189 return complex_type_class;
3190 else if (ArgTy->isFunctionType())
3191 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00003192 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00003193 return record_type_class;
3194 else if (ArgTy->isUnionType())
3195 return union_type_class;
3196 else if (ArgTy->isArrayType())
3197 return array_type_class;
3198 else if (ArgTy->isUnionType())
3199 return union_type_class;
3200 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00003201 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00003202 return -1;
3203}
3204
John McCall42c8f872010-05-10 23:27:23 +00003205/// Retrieves the "underlying object type" of the given expression,
3206/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003207QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3208 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3209 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00003210 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003211 } else if (const Expr *E = B.get<const Expr*>()) {
3212 if (isa<CompoundLiteralExpr>(E))
3213 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00003214 }
3215
3216 return QualType();
3217}
3218
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003219bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00003220 // TODO: Perhaps we should let LLVM lower this?
3221 LValue Base;
3222 if (!EvaluatePointer(E->getArg(0), Base, Info))
3223 return false;
3224
3225 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003226 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00003227
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003228 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00003229 if (T.isNull() ||
3230 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00003231 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00003232 T->isVariablyModifiedType() ||
3233 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003234 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00003235
3236 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3237 CharUnits Offset = Base.getLValueOffset();
3238
3239 if (!Offset.isNegative() && Offset <= Size)
3240 Size -= Offset;
3241 else
3242 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003243 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00003244}
3245
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003246bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003247 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00003248 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003249 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003250
3251 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00003252 if (TryEvaluateBuiltinObjectSize(E))
3253 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00003254
Eric Christopherb2aaf512010-01-19 22:58:35 +00003255 // If evaluating the argument has side-effects we can't determine
3256 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00003257 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003258 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00003259 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003260 return Success(0, E);
3261 }
Mike Stumpc4c90452009-10-27 22:09:17 +00003262
Richard Smithf48fdb02011-12-09 22:58:01 +00003263 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00003264 }
3265
Chris Lattner019f4e82008-10-06 05:28:25 +00003266 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003267 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Richard Smithe052d462011-12-09 02:04:48 +00003269 case Builtin::BI__builtin_constant_p: {
3270 const Expr *Arg = E->getArg(0);
3271 QualType ArgType = Arg->getType();
3272 // __builtin_constant_p always has one operand. The rules which gcc follows
3273 // are not precisely documented, but are as follows:
3274 //
3275 // - If the operand is of integral, floating, complex or enumeration type,
3276 // and can be folded to a known value of that type, it returns 1.
3277 // - If the operand and can be folded to a pointer to the first character
3278 // of a string literal (or such a pointer cast to an integral type), it
3279 // returns 1.
3280 //
3281 // Otherwise, it returns 0.
3282 //
3283 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3284 // its support for this does not currently work.
3285 int IsConstant = 0;
3286 if (ArgType->isIntegralOrEnumerationType()) {
3287 // Note, a pointer cast to an integral type is only a constant if it is
3288 // a pointer to the first character of a string literal.
3289 Expr::EvalResult Result;
3290 if (Arg->EvaluateAsRValue(Result, Info.Ctx) && !Result.HasSideEffects) {
3291 APValue &V = Result.Val;
3292 if (V.getKind() == APValue::LValue) {
3293 if (const Expr *E = V.getLValueBase().dyn_cast<const Expr*>())
3294 IsConstant = isa<StringLiteral>(E) && V.getLValueOffset().isZero();
3295 } else {
3296 IsConstant = 1;
3297 }
3298 }
3299 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3300 IsConstant = Arg->isEvaluatable(Info.Ctx);
3301 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3302 LValue LV;
3303 // Use a separate EvalInfo: ignore constexpr parameter and 'this' bindings
3304 // during the check.
3305 Expr::EvalStatus Status;
3306 EvalInfo SubInfo(Info.Ctx, Status);
3307 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, SubInfo)
3308 : EvaluatePointer(Arg, LV, SubInfo)) &&
3309 !Status.HasSideEffects)
3310 if (const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>())
3311 IsConstant = isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3312 }
3313
3314 return Success(IsConstant, E);
3315 }
Chris Lattner21fb98e2009-09-23 06:06:36 +00003316 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003317 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00003318 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00003319 return Success(Operand, E);
3320 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00003321
3322 case Builtin::BI__builtin_expect:
3323 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00003324
3325 case Builtin::BIstrlen:
3326 case Builtin::BI__builtin_strlen:
3327 // As an extension, we support strlen() and __builtin_strlen() as constant
3328 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003329 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00003330 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
3331 // The string literal may have embedded null characters. Find the first
3332 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003333 StringRef Str = S->getString();
3334 StringRef::size_type Pos = Str.find(0);
3335 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00003336 Str = Str.substr(0, Pos);
3337
3338 return Success(Str.size(), E);
3339 }
3340
Richard Smithf48fdb02011-12-09 22:58:01 +00003341 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003342
3343 case Builtin::BI__atomic_is_lock_free: {
3344 APSInt SizeVal;
3345 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
3346 return false;
3347
3348 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
3349 // of two less than the maximum inline atomic width, we know it is
3350 // lock-free. If the size isn't a power of two, or greater than the
3351 // maximum alignment where we promote atomics, we know it is not lock-free
3352 // (at least not in the sense of atomic_is_lock_free). Otherwise,
3353 // the answer can only be determined at runtime; for example, 16-byte
3354 // atomics have lock-free implementations on some, but not all,
3355 // x86-64 processors.
3356
3357 // Check power-of-two.
3358 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
3359 if (!Size.isPowerOfTwo())
3360#if 0
3361 // FIXME: Suppress this folding until the ABI for the promotion width
3362 // settles.
3363 return Success(0, E);
3364#else
Richard Smithf48fdb02011-12-09 22:58:01 +00003365 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003366#endif
3367
3368#if 0
3369 // Check against promotion width.
3370 // FIXME: Suppress this folding until the ABI for the promotion width
3371 // settles.
3372 unsigned PromoteWidthBits =
3373 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
3374 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
3375 return Success(0, E);
3376#endif
3377
3378 // Check against inlining width.
3379 unsigned InlineWidthBits =
3380 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
3381 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
3382 return Success(1, E);
3383
Richard Smithf48fdb02011-12-09 22:58:01 +00003384 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00003385 }
Chris Lattner019f4e82008-10-06 05:28:25 +00003386 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00003387}
Anders Carlsson650c92f2008-07-08 15:34:11 +00003388
Richard Smith625b8072011-10-31 01:37:14 +00003389static bool HasSameBase(const LValue &A, const LValue &B) {
3390 if (!A.getLValueBase())
3391 return !B.getLValueBase();
3392 if (!B.getLValueBase())
3393 return false;
3394
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003395 if (A.getLValueBase().getOpaqueValue() !=
3396 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00003397 const Decl *ADecl = GetLValueBaseDecl(A);
3398 if (!ADecl)
3399 return false;
3400 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00003401 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00003402 return false;
3403 }
3404
3405 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith177dce72011-11-01 16:57:24 +00003406 A.getLValueFrame() == B.getLValueFrame();
Richard Smith625b8072011-10-31 01:37:14 +00003407}
3408
Chris Lattnerb542afe2008-07-11 19:10:17 +00003409bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003410 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003411 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003412
John McCall2de56d12010-08-25 11:45:40 +00003413 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00003414 VisitIgnoredValue(E->getLHS());
3415 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00003416 }
3417
3418 if (E->isLogicalOp()) {
3419 // These need to be handled specially because the operands aren't
3420 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003421 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00003422
Richard Smithc49bd112011-10-28 17:51:58 +00003423 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00003424 // We were able to evaluate the LHS, see if we can get away with not
3425 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00003426 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003427 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003428
Richard Smithc49bd112011-10-28 17:51:58 +00003429 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00003430 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003431 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003432 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00003433 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003434 }
3435 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00003436 // FIXME: If both evaluations fail, we should produce the diagnostic from
3437 // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
3438 // less clear how to diagnose this.
Richard Smithc49bd112011-10-28 17:51:58 +00003439 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003440 // We can't evaluate the LHS; however, sometimes the result
3441 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smithf48fdb02011-12-09 22:58:01 +00003442 if (rhsResult == (E->getOpcode() == BO_LOr)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003443 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00003444 // must have had side effects.
Richard Smith1e12c592011-10-16 21:26:27 +00003445 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003446
3447 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00003448 }
3449 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00003450 }
Eli Friedmana6afa762008-11-13 06:09:17 +00003451
Eli Friedmana6afa762008-11-13 06:09:17 +00003452 return false;
3453 }
3454
Anders Carlsson286f85e2008-11-16 07:17:21 +00003455 QualType LHSTy = E->getLHS()->getType();
3456 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00003457
3458 if (LHSTy->isAnyComplexType()) {
3459 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00003460 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00003461
3462 if (!EvaluateComplex(E->getLHS(), LHS, Info))
3463 return false;
3464
3465 if (!EvaluateComplex(E->getRHS(), RHS, Info))
3466 return false;
3467
3468 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003469 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003470 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00003471 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00003472 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
3473
John McCall2de56d12010-08-25 11:45:40 +00003474 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003475 return Success((CR_r == APFloat::cmpEqual &&
3476 CR_i == APFloat::cmpEqual), E);
3477 else {
John McCall2de56d12010-08-25 11:45:40 +00003478 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003479 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00003480 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003481 CR_r == APFloat::cmpLessThan ||
3482 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00003483 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00003484 CR_i == APFloat::cmpLessThan ||
3485 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00003486 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003487 } else {
John McCall2de56d12010-08-25 11:45:40 +00003488 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00003489 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
3490 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
3491 else {
John McCall2de56d12010-08-25 11:45:40 +00003492 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00003493 "Invalid compex comparison.");
3494 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
3495 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
3496 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00003497 }
3498 }
Mike Stump1eb44332009-09-09 15:08:12 +00003499
Anders Carlsson286f85e2008-11-16 07:17:21 +00003500 if (LHSTy->isRealFloatingType() &&
3501 RHSTy->isRealFloatingType()) {
3502 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00003503
Anders Carlsson286f85e2008-11-16 07:17:21 +00003504 if (!EvaluateFloat(E->getRHS(), RHS, Info))
3505 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003506
Anders Carlsson286f85e2008-11-16 07:17:21 +00003507 if (!EvaluateFloat(E->getLHS(), LHS, Info))
3508 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Anders Carlsson286f85e2008-11-16 07:17:21 +00003510 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00003511
Anders Carlsson286f85e2008-11-16 07:17:21 +00003512 switch (E->getOpcode()) {
3513 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00003514 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00003515 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003516 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003517 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003518 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00003519 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003520 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003521 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00003522 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00003523 E);
John McCall2de56d12010-08-25 11:45:40 +00003524 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00003525 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00003526 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00003527 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00003528 || CR == APFloat::cmpLessThan
3529 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00003530 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00003531 }
Mike Stump1eb44332009-09-09 15:08:12 +00003532
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003533 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00003534 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00003535 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003536 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
3537 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003538
John McCallefdb83e2010-05-07 21:00:08 +00003539 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00003540 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
3541 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003542
Richard Smith625b8072011-10-31 01:37:14 +00003543 // Reject differing bases from the normal codepath; we special-case
3544 // comparisons to null.
3545 if (!HasSameBase(LHSValue, RHSValue)) {
Richard Smith9e36b532011-10-31 05:11:32 +00003546 // Inequalities and subtractions between unrelated pointers have
3547 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00003548 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00003549 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00003550 // A constant address may compare equal to the address of a symbol.
3551 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00003552 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00003553 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
3554 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003555 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003556 // It's implementation-defined whether distinct literals will have
Eli Friedmanc45061b2011-10-31 22:54:30 +00003557 // distinct addresses. In clang, we do not guarantee the addresses are
Richard Smith74f46342011-11-04 01:10:57 +00003558 // distinct. However, we do know that the address of a literal will be
3559 // non-null.
3560 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
3561 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00003562 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003563 // We can't tell whether weak symbols will end up pointing to the same
3564 // object.
3565 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00003566 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00003567 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00003568 // (Note that clang defaults to -fmerge-all-constants, which can
3569 // lead to inconsistent results for comparisons involving the address
3570 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00003571 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00003572 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003573
Richard Smithcc5d4f62011-11-07 09:22:26 +00003574 // FIXME: Implement the C++11 restrictions:
3575 // - Pointer subtractions must be on elements of the same array.
3576 // - Pointer comparisons must be between members with the same access.
3577
John McCall2de56d12010-08-25 11:45:40 +00003578 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00003579 QualType Type = E->getLHS()->getType();
3580 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00003581
Richard Smith180f4792011-11-10 06:34:14 +00003582 CharUnits ElementSize;
3583 if (!HandleSizeof(Info, ElementType, ElementSize))
3584 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00003585
Richard Smith180f4792011-11-10 06:34:14 +00003586 CharUnits Diff = LHSValue.getLValueOffset() -
Ken Dycka7305832010-01-15 12:37:54 +00003587 RHSValue.getLValueOffset();
3588 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003589 }
Richard Smith625b8072011-10-31 01:37:14 +00003590
3591 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
3592 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
3593 switch (E->getOpcode()) {
3594 default: llvm_unreachable("missing comparison operator");
3595 case BO_LT: return Success(LHSOffset < RHSOffset, E);
3596 case BO_GT: return Success(LHSOffset > RHSOffset, E);
3597 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
3598 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
3599 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
3600 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00003601 }
Anders Carlsson3068d112008-11-16 19:01:22 +00003602 }
3603 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003604 if (!LHSTy->isIntegralOrEnumerationType() ||
3605 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003606 // We can't continue from here for non-integral types.
3607 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003608 }
3609
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003610 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00003611 CCValue LHSVal;
Richard Smithc49bd112011-10-28 17:51:58 +00003612 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003613 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00003614
Richard Smithc49bd112011-10-28 17:51:58 +00003615 if (!Visit(E->getRHS()))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003616 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00003617 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003618
3619 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00003620 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00003621 CharUnits AdditionalOffset = CharUnits::fromQuantity(
3622 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00003623 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00003624 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003625 else
Richard Smith47a1eed2011-10-29 20:57:55 +00003626 LHSVal.getLValueOffset() -= AdditionalOffset;
3627 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00003628 return true;
3629 }
3630
3631 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00003632 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00003633 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003634 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
3635 LHSVal.getInt().getZExtValue());
3636 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00003637 return true;
3638 }
3639
3640 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00003641 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00003642 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003643
Richard Smithc49bd112011-10-28 17:51:58 +00003644 APSInt &LHS = LHSVal.getInt();
3645 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00003646
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003647 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00003648 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00003649 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003650 case BO_Mul: return Success(LHS * RHS, E);
3651 case BO_Add: return Success(LHS + RHS, E);
3652 case BO_Sub: return Success(LHS - RHS, E);
3653 case BO_And: return Success(LHS & RHS, E);
3654 case BO_Xor: return Success(LHS ^ RHS, E);
3655 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003656 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00003657 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003658 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003659 return Success(LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003660 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00003661 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003662 return Error(E, diag::note_expr_divide_by_zero);
Richard Smithc49bd112011-10-28 17:51:58 +00003663 return Success(LHS % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00003664 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00003665 // During constant-folding, a negative shift is an opposite shift.
3666 if (RHS.isSigned() && RHS.isNegative()) {
3667 RHS = -RHS;
3668 goto shift_right;
3669 }
3670
3671 shift_left:
3672 unsigned SA
Richard Smithc49bd112011-10-28 17:51:58 +00003673 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3674 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003675 }
John McCall2de56d12010-08-25 11:45:40 +00003676 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00003677 // During constant-folding, a negative shift is an opposite shift.
3678 if (RHS.isSigned() && RHS.isNegative()) {
3679 RHS = -RHS;
3680 goto shift_left;
3681 }
3682
3683 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00003684 unsigned SA =
Richard Smithc49bd112011-10-28 17:51:58 +00003685 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
3686 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003687 }
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Richard Smithc49bd112011-10-28 17:51:58 +00003689 case BO_LT: return Success(LHS < RHS, E);
3690 case BO_GT: return Success(LHS > RHS, E);
3691 case BO_LE: return Success(LHS <= RHS, E);
3692 case BO_GE: return Success(LHS >= RHS, E);
3693 case BO_EQ: return Success(LHS == RHS, E);
3694 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00003695 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003696}
3697
Ken Dyck8b752f12010-01-27 17:10:57 +00003698CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00003699 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3700 // the result is the size of the referenced type."
3701 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3702 // result shall be the alignment of the referenced type."
3703 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3704 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00003705
3706 // __alignof is defined to return the preferred alignment.
3707 return Info.Ctx.toCharUnitsFromBits(
3708 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00003709}
3710
Ken Dyck8b752f12010-01-27 17:10:57 +00003711CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00003712 E = E->IgnoreParens();
3713
3714 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00003715 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00003716 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003717 return Info.Ctx.getDeclAlign(DRE->getDecl(),
3718 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00003719
Chris Lattneraf707ab2009-01-24 21:53:27 +00003720 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00003721 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
3722 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00003723
Chris Lattnere9feb472009-01-24 21:09:06 +00003724 return GetAlignOfType(E->getType());
3725}
3726
3727
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003728/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
3729/// a result as the expression's type.
3730bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
3731 const UnaryExprOrTypeTraitExpr *E) {
3732 switch(E->getKind()) {
3733 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00003734 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003735 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003736 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003737 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00003738 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00003739
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003740 case UETT_VecStep: {
3741 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00003742
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003743 if (Ty->isVectorType()) {
3744 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00003745
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003746 // The vec_step built-in functions that take a 3-component
3747 // vector return 4. (OpenCL 1.1 spec 6.11.12)
3748 if (n == 3)
3749 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00003750
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003751 return Success(n, E);
3752 } else
3753 return Success(1, E);
3754 }
3755
3756 case UETT_SizeOf: {
3757 QualType SrcTy = E->getTypeOfArgument();
3758 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3759 // the result is the size of the referenced type."
3760 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3761 // result shall be the alignment of the referenced type."
3762 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3763 SrcTy = Ref->getPointeeType();
3764
Richard Smith180f4792011-11-10 06:34:14 +00003765 CharUnits Sizeof;
3766 if (!HandleSizeof(Info, SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003767 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003768 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003769 }
3770 }
3771
3772 llvm_unreachable("unknown expr/type trait");
Richard Smithf48fdb02011-12-09 22:58:01 +00003773 return Error(E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00003774}
3775
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003776bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003777 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003778 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003779 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00003780 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003781 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003782 for (unsigned i = 0; i != n; ++i) {
3783 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3784 switch (ON.getKind()) {
3785 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003786 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003787 APSInt IdxResult;
3788 if (!EvaluateInteger(Idx, IdxResult, Info))
3789 return false;
3790 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3791 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003792 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003793 CurrentType = AT->getElementType();
3794 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3795 Result += IdxResult.getSExtValue() * ElementSize;
3796 break;
3797 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003798
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003799 case OffsetOfExpr::OffsetOfNode::Field: {
3800 FieldDecl *MemberDecl = ON.getField();
3801 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003802 if (!RT)
3803 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003804 RecordDecl *RD = RT->getDecl();
3805 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00003806 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003807 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00003808 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003809 CurrentType = MemberDecl->getType().getNonReferenceType();
3810 break;
3811 }
Richard Smithf48fdb02011-12-09 22:58:01 +00003812
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003813 case OffsetOfExpr::OffsetOfNode::Identifier:
3814 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00003815 return Error(OOE);
3816
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003817 case OffsetOfExpr::OffsetOfNode::Base: {
3818 CXXBaseSpecifier *BaseSpec = ON.getBase();
3819 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00003820 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003821
3822 // Find the layout of the class whose base we are looking into.
3823 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00003824 if (!RT)
3825 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003826 RecordDecl *RD = RT->getDecl();
3827 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3828
3829 // Find the base class itself.
3830 CurrentType = BaseSpec->getType();
3831 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3832 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003833 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003834
3835 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00003836 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00003837 break;
3838 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003839 }
3840 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003841 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003842}
3843
Chris Lattnerb542afe2008-07-11 19:10:17 +00003844bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00003845 switch (E->getOpcode()) {
3846 default:
3847 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3848 // See C99 6.6p3.
3849 return Error(E);
3850 case UO_Extension:
3851 // FIXME: Should extension allow i-c-e extension expressions in its scope?
3852 // If so, we could clear the diagnostic ID.
3853 return Visit(E->getSubExpr());
3854 case UO_Plus:
3855 // The result is just the value.
3856 return Visit(E->getSubExpr());
3857 case UO_Minus: {
3858 if (!Visit(E->getSubExpr()))
3859 return false;
3860 if (!Result.isInt()) return Error(E);
3861 return Success(-Result.getInt(), E);
3862 }
3863 case UO_Not: {
3864 if (!Visit(E->getSubExpr()))
3865 return false;
3866 if (!Result.isInt()) return Error(E);
3867 return Success(~Result.getInt(), E);
3868 }
3869 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00003870 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00003871 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00003872 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003873 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00003874 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003875 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003876}
Mike Stump1eb44332009-09-09 15:08:12 +00003877
Chris Lattner732b2232008-07-12 01:15:53 +00003878/// HandleCast - This is used to evaluate implicit or explicit casts where the
3879/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003880bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3881 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00003882 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00003883 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00003884
Eli Friedman46a52322011-03-25 00:43:55 +00003885 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00003886 case CK_BaseToDerived:
3887 case CK_DerivedToBase:
3888 case CK_UncheckedDerivedToBase:
3889 case CK_Dynamic:
3890 case CK_ToUnion:
3891 case CK_ArrayToPointerDecay:
3892 case CK_FunctionToPointerDecay:
3893 case CK_NullToPointer:
3894 case CK_NullToMemberPointer:
3895 case CK_BaseToDerivedMemberPointer:
3896 case CK_DerivedToBaseMemberPointer:
3897 case CK_ConstructorConversion:
3898 case CK_IntegralToPointer:
3899 case CK_ToVoid:
3900 case CK_VectorSplat:
3901 case CK_IntegralToFloating:
3902 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003903 case CK_CPointerToObjCPointerCast:
3904 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003905 case CK_AnyPointerToBlockPointerCast:
3906 case CK_ObjCObjectLValueCast:
3907 case CK_FloatingRealToComplex:
3908 case CK_FloatingComplexToReal:
3909 case CK_FloatingComplexCast:
3910 case CK_FloatingComplexToIntegralComplex:
3911 case CK_IntegralRealToComplex:
3912 case CK_IntegralComplexCast:
3913 case CK_IntegralComplexToFloatingComplex:
3914 llvm_unreachable("invalid cast kind for integral value");
3915
Eli Friedmane50c2972011-03-25 19:07:11 +00003916 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00003917 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00003918 case CK_LValueBitCast:
3919 case CK_UserDefinedConversion:
John McCall33e56f32011-09-10 06:18:15 +00003920 case CK_ARCProduceObject:
3921 case CK_ARCConsumeObject:
3922 case CK_ARCReclaimReturnedObject:
3923 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00003924 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003925
3926 case CK_LValueToRValue:
3927 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00003928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003929
3930 case CK_MemberPointerToBoolean:
3931 case CK_PointerToBoolean:
3932 case CK_IntegralToBoolean:
3933 case CK_FloatingToBoolean:
3934 case CK_FloatingComplexToBoolean:
3935 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00003936 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00003937 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00003938 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00003939 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003940 }
3941
Eli Friedman46a52322011-03-25 00:43:55 +00003942 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00003943 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003944 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00003945
Eli Friedmanbe265702009-02-20 01:15:07 +00003946 if (!Result.isInt()) {
3947 // Only allow casts of lvalues if they are lossless.
3948 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3949 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003950
Daniel Dunbardd211642009-02-19 22:24:01 +00003951 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003952 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00003953 }
Mike Stump1eb44332009-09-09 15:08:12 +00003954
Eli Friedman46a52322011-03-25 00:43:55 +00003955 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00003956 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3957
John McCallefdb83e2010-05-07 21:00:08 +00003958 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00003959 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00003960 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00003961
Daniel Dunbardd211642009-02-19 22:24:01 +00003962 if (LV.getLValueBase()) {
3963 // Only allow based lvalue casts if they are lossless.
3964 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00003965 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003966
Richard Smithb755a9d2011-11-16 07:18:12 +00003967 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003968 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00003969 return true;
3970 }
3971
Ken Dycka7305832010-01-15 12:37:54 +00003972 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3973 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00003974 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00003975 }
Eli Friedman4efaa272008-11-12 09:44:48 +00003976
Eli Friedman46a52322011-03-25 00:43:55 +00003977 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00003978 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00003979 if (!EvaluateComplex(SubExpr, C, Info))
3980 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00003981 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00003982 }
Eli Friedman2217c872009-02-22 11:46:18 +00003983
Eli Friedman46a52322011-03-25 00:43:55 +00003984 case CK_FloatingToIntegral: {
3985 APFloat F(0.0);
3986 if (!EvaluateFloat(SubExpr, F, Info))
3987 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00003988
Richard Smithc1c5f272011-12-13 06:39:58 +00003989 APSInt Value;
3990 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
3991 return false;
3992 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00003993 }
3994 }
Mike Stump1eb44332009-09-09 15:08:12 +00003995
Eli Friedman46a52322011-03-25 00:43:55 +00003996 llvm_unreachable("unknown cast resulting in integral value");
Richard Smithf48fdb02011-12-09 22:58:01 +00003997 return Error(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00003998}
Anders Carlsson2bad1682008-07-08 14:30:00 +00003999
Eli Friedman722c7172009-02-28 03:59:05 +00004000bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4001 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004002 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004003 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4004 return false;
4005 if (!LV.isComplexInt())
4006 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004007 return Success(LV.getComplexIntReal(), E);
4008 }
4009
4010 return Visit(E->getSubExpr());
4011}
4012
Eli Friedman664a1042009-02-27 04:45:43 +00004013bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00004014 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004015 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00004016 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4017 return false;
4018 if (!LV.isComplexInt())
4019 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00004020 return Success(LV.getComplexIntImag(), E);
4021 }
4022
Richard Smith8327fad2011-10-24 18:44:57 +00004023 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00004024 return Success(0, E);
4025}
4026
Douglas Gregoree8aff02011-01-04 17:33:58 +00004027bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4028 return Success(E->getPackLength(), E);
4029}
4030
Sebastian Redl295995c2010-09-10 20:55:47 +00004031bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4032 return Success(E->getValue(), E);
4033}
4034
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004035//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004036// Float Evaluation
4037//===----------------------------------------------------------------------===//
4038
4039namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004040class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004041 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004042 APFloat &Result;
4043public:
4044 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004045 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004046
Richard Smith47a1eed2011-10-29 20:57:55 +00004047 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004048 Result = V.getFloat();
4049 return true;
4050 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004051
Richard Smithf10d9172011-10-11 21:43:33 +00004052 bool ValueInitialization(const Expr *E) {
4053 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4054 return true;
4055 }
4056
Chris Lattner019f4e82008-10-06 05:28:25 +00004057 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004058
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004059 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004060 bool VisitBinaryOperator(const BinaryOperator *E);
4061 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004062 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00004063
John McCallabd3a852010-05-07 22:08:54 +00004064 bool VisitUnaryReal(const UnaryOperator *E);
4065 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00004066
John McCallabd3a852010-05-07 22:08:54 +00004067 // FIXME: Missing: array subscript of vector, member of vector,
4068 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004069};
4070} // end anonymous namespace
4071
4072static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004073 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004074 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004075}
4076
Jay Foad4ba2a172011-01-12 09:06:06 +00004077static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00004078 QualType ResultTy,
4079 const Expr *Arg,
4080 bool SNaN,
4081 llvm::APFloat &Result) {
4082 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4083 if (!S) return false;
4084
4085 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4086
4087 llvm::APInt fill;
4088
4089 // Treat empty strings as if they were zero.
4090 if (S->getString().empty())
4091 fill = llvm::APInt(32, 0);
4092 else if (S->getString().getAsInteger(0, fill))
4093 return false;
4094
4095 if (SNaN)
4096 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4097 else
4098 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4099 return true;
4100}
4101
Chris Lattner019f4e82008-10-06 05:28:25 +00004102bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004103 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004104 default:
4105 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4106
Chris Lattner019f4e82008-10-06 05:28:25 +00004107 case Builtin::BI__builtin_huge_val:
4108 case Builtin::BI__builtin_huge_valf:
4109 case Builtin::BI__builtin_huge_vall:
4110 case Builtin::BI__builtin_inf:
4111 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004112 case Builtin::BI__builtin_infl: {
4113 const llvm::fltSemantics &Sem =
4114 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00004115 Result = llvm::APFloat::getInf(Sem);
4116 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00004117 }
Mike Stump1eb44332009-09-09 15:08:12 +00004118
John McCalldb7b72a2010-02-28 13:00:19 +00004119 case Builtin::BI__builtin_nans:
4120 case Builtin::BI__builtin_nansf:
4121 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00004122 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4123 true, Result))
4124 return Error(E);
4125 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00004126
Chris Lattner9e621712008-10-06 06:31:58 +00004127 case Builtin::BI__builtin_nan:
4128 case Builtin::BI__builtin_nanf:
4129 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00004130 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00004131 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00004132 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4133 false, Result))
4134 return Error(E);
4135 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004136
4137 case Builtin::BI__builtin_fabs:
4138 case Builtin::BI__builtin_fabsf:
4139 case Builtin::BI__builtin_fabsl:
4140 if (!EvaluateFloat(E->getArg(0), Result, Info))
4141 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004143 if (Result.isNegative())
4144 Result.changeSign();
4145 return true;
4146
Mike Stump1eb44332009-09-09 15:08:12 +00004147 case Builtin::BI__builtin_copysign:
4148 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004149 case Builtin::BI__builtin_copysignl: {
4150 APFloat RHS(0.);
4151 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4152 !EvaluateFloat(E->getArg(1), RHS, Info))
4153 return false;
4154 Result.copySign(RHS);
4155 return true;
4156 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004157 }
4158}
4159
John McCallabd3a852010-05-07 22:08:54 +00004160bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004161 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4162 ComplexValue CV;
4163 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4164 return false;
4165 Result = CV.FloatReal;
4166 return true;
4167 }
4168
4169 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00004170}
4171
4172bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00004173 if (E->getSubExpr()->getType()->isAnyComplexType()) {
4174 ComplexValue CV;
4175 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4176 return false;
4177 Result = CV.FloatImag;
4178 return true;
4179 }
4180
Richard Smith8327fad2011-10-24 18:44:57 +00004181 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00004182 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4183 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00004184 return true;
4185}
4186
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004187bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004188 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004189 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004190 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004191 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00004192 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00004193 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4194 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004195 Result.changeSign();
4196 return true;
4197 }
4198}
Chris Lattner019f4e82008-10-06 05:28:25 +00004199
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004200bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004201 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4202 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00004203
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00004204 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004205 if (!EvaluateFloat(E->getLHS(), Result, Info))
4206 return false;
4207 if (!EvaluateFloat(E->getRHS(), RHS, Info))
4208 return false;
4209
4210 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004211 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004212 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004213 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4214 return true;
John McCall2de56d12010-08-25 11:45:40 +00004215 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004216 Result.add(RHS, APFloat::rmNearestTiesToEven);
4217 return true;
John McCall2de56d12010-08-25 11:45:40 +00004218 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004219 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4220 return true;
John McCall2de56d12010-08-25 11:45:40 +00004221 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004222 Result.divide(RHS, APFloat::rmNearestTiesToEven);
4223 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004224 }
4225}
4226
4227bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4228 Result = E->getValue();
4229 return true;
4230}
4231
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004232bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4233 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00004234
Eli Friedman2a523ee2011-03-25 00:54:52 +00004235 switch (E->getCastKind()) {
4236 default:
Richard Smithc49bd112011-10-28 17:51:58 +00004237 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00004238
4239 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004240 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00004241 return EvaluateInteger(SubExpr, IntResult, Info) &&
4242 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4243 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004244 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004245
4246 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00004247 if (!Visit(SubExpr))
4248 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004249 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
4250 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00004251 }
John McCallf3ea8cf2010-11-14 08:17:51 +00004252
Eli Friedman2a523ee2011-03-25 00:54:52 +00004253 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00004254 ComplexValue V;
4255 if (!EvaluateComplex(SubExpr, V, Info))
4256 return false;
4257 Result = V.getComplexFloatReal();
4258 return true;
4259 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00004260 }
Eli Friedman4efaa272008-11-12 09:44:48 +00004261
Richard Smithf48fdb02011-12-09 22:58:01 +00004262 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00004263}
4264
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00004265//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004266// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004267//===----------------------------------------------------------------------===//
4268
4269namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004270class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004271 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00004272 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004274public:
John McCallf4cf1a12010-05-07 17:22:02 +00004275 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004276 : ExprEvaluatorBaseTy(info), Result(Result) {}
4277
Richard Smith47a1eed2011-10-29 20:57:55 +00004278 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004279 Result.setFrom(V);
4280 return true;
4281 }
Mike Stump1eb44332009-09-09 15:08:12 +00004282
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004283 //===--------------------------------------------------------------------===//
4284 // Visitor Methods
4285 //===--------------------------------------------------------------------===//
4286
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004287 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004288
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004289 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00004290
John McCallf4cf1a12010-05-07 17:22:02 +00004291 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004292 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004293 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004294};
4295} // end anonymous namespace
4296
John McCallf4cf1a12010-05-07 17:22:02 +00004297static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
4298 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004299 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004300 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004301}
4302
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004303bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
4304 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004305
4306 if (SubExpr->getType()->isRealFloatingType()) {
4307 Result.makeComplexFloat();
4308 APFloat &Imag = Result.FloatImag;
4309 if (!EvaluateFloat(SubExpr, Imag, Info))
4310 return false;
4311
4312 Result.FloatReal = APFloat(Imag.getSemantics());
4313 return true;
4314 } else {
4315 assert(SubExpr->getType()->isIntegerType() &&
4316 "Unexpected imaginary literal.");
4317
4318 Result.makeComplexInt();
4319 APSInt &Imag = Result.IntImag;
4320 if (!EvaluateInteger(SubExpr, Imag, Info))
4321 return false;
4322
4323 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
4324 return true;
4325 }
4326}
4327
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004328bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004329
John McCall8786da72010-12-14 17:51:41 +00004330 switch (E->getCastKind()) {
4331 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00004332 case CK_BaseToDerived:
4333 case CK_DerivedToBase:
4334 case CK_UncheckedDerivedToBase:
4335 case CK_Dynamic:
4336 case CK_ToUnion:
4337 case CK_ArrayToPointerDecay:
4338 case CK_FunctionToPointerDecay:
4339 case CK_NullToPointer:
4340 case CK_NullToMemberPointer:
4341 case CK_BaseToDerivedMemberPointer:
4342 case CK_DerivedToBaseMemberPointer:
4343 case CK_MemberPointerToBoolean:
4344 case CK_ConstructorConversion:
4345 case CK_IntegralToPointer:
4346 case CK_PointerToIntegral:
4347 case CK_PointerToBoolean:
4348 case CK_ToVoid:
4349 case CK_VectorSplat:
4350 case CK_IntegralCast:
4351 case CK_IntegralToBoolean:
4352 case CK_IntegralToFloating:
4353 case CK_FloatingToIntegral:
4354 case CK_FloatingToBoolean:
4355 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00004356 case CK_CPointerToObjCPointerCast:
4357 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00004358 case CK_AnyPointerToBlockPointerCast:
4359 case CK_ObjCObjectLValueCast:
4360 case CK_FloatingComplexToReal:
4361 case CK_FloatingComplexToBoolean:
4362 case CK_IntegralComplexToReal:
4363 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00004364 case CK_ARCProduceObject:
4365 case CK_ARCConsumeObject:
4366 case CK_ARCReclaimReturnedObject:
4367 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00004368 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00004369
John McCall8786da72010-12-14 17:51:41 +00004370 case CK_LValueToRValue:
4371 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00004372 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00004373
4374 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00004375 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00004376 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00004377 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00004378
4379 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004380 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00004381 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004382 return false;
4383
John McCall8786da72010-12-14 17:51:41 +00004384 Result.makeComplexFloat();
4385 Result.FloatImag = APFloat(Real.getSemantics());
4386 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004387 }
4388
John McCall8786da72010-12-14 17:51:41 +00004389 case CK_FloatingComplexCast: {
4390 if (!Visit(E->getSubExpr()))
4391 return false;
4392
4393 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4394 QualType From
4395 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4396
Richard Smithc1c5f272011-12-13 06:39:58 +00004397 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
4398 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004399 }
4400
4401 case CK_FloatingComplexToIntegralComplex: {
4402 if (!Visit(E->getSubExpr()))
4403 return false;
4404
4405 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4406 QualType From
4407 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4408 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00004409 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
4410 To, Result.IntReal) &&
4411 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
4412 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00004413 }
4414
4415 case CK_IntegralRealToComplex: {
4416 APSInt &Real = Result.IntReal;
4417 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
4418 return false;
4419
4420 Result.makeComplexInt();
4421 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
4422 return true;
4423 }
4424
4425 case CK_IntegralComplexCast: {
4426 if (!Visit(E->getSubExpr()))
4427 return false;
4428
4429 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4430 QualType From
4431 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4432
4433 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
4434 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
4435 return true;
4436 }
4437
4438 case CK_IntegralComplexToFloatingComplex: {
4439 if (!Visit(E->getSubExpr()))
4440 return false;
4441
4442 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
4443 QualType From
4444 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
4445 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00004446 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
4447 To, Result.FloatReal) &&
4448 HandleIntToFloatCast(Info, E, From, Result.IntImag,
4449 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00004450 }
4451 }
4452
4453 llvm_unreachable("unknown cast resulting in complex value");
Richard Smithf48fdb02011-12-09 22:58:01 +00004454 return Error(E);
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00004455}
4456
John McCallf4cf1a12010-05-07 17:22:02 +00004457bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004458 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00004459 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4460
John McCallf4cf1a12010-05-07 17:22:02 +00004461 if (!Visit(E->getLHS()))
4462 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004463
John McCallf4cf1a12010-05-07 17:22:02 +00004464 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004465 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00004466 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004467
Daniel Dunbar3f279872009-01-29 01:32:56 +00004468 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
4469 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004470 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00004471 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00004472 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004473 if (Result.isComplexFloat()) {
4474 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
4475 APFloat::rmNearestTiesToEven);
4476 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
4477 APFloat::rmNearestTiesToEven);
4478 } else {
4479 Result.getComplexIntReal() += RHS.getComplexIntReal();
4480 Result.getComplexIntImag() += RHS.getComplexIntImag();
4481 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004482 break;
John McCall2de56d12010-08-25 11:45:40 +00004483 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00004484 if (Result.isComplexFloat()) {
4485 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
4486 APFloat::rmNearestTiesToEven);
4487 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
4488 APFloat::rmNearestTiesToEven);
4489 } else {
4490 Result.getComplexIntReal() -= RHS.getComplexIntReal();
4491 Result.getComplexIntImag() -= RHS.getComplexIntImag();
4492 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00004493 break;
John McCall2de56d12010-08-25 11:45:40 +00004494 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00004495 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00004496 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00004497 APFloat &LHS_r = LHS.getComplexFloatReal();
4498 APFloat &LHS_i = LHS.getComplexFloatImag();
4499 APFloat &RHS_r = RHS.getComplexFloatReal();
4500 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00004501
Daniel Dunbar3f279872009-01-29 01:32:56 +00004502 APFloat Tmp = LHS_r;
4503 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4504 Result.getComplexFloatReal() = Tmp;
4505 Tmp = LHS_i;
4506 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4507 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
4508
4509 Tmp = LHS_r;
4510 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4511 Result.getComplexFloatImag() = Tmp;
4512 Tmp = LHS_i;
4513 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4514 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
4515 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00004516 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00004517 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004518 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
4519 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00004520 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00004521 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
4522 LHS.getComplexIntImag() * RHS.getComplexIntReal());
4523 }
4524 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004525 case BO_Div:
4526 if (Result.isComplexFloat()) {
4527 ComplexValue LHS = Result;
4528 APFloat &LHS_r = LHS.getComplexFloatReal();
4529 APFloat &LHS_i = LHS.getComplexFloatImag();
4530 APFloat &RHS_r = RHS.getComplexFloatReal();
4531 APFloat &RHS_i = RHS.getComplexFloatImag();
4532 APFloat &Res_r = Result.getComplexFloatReal();
4533 APFloat &Res_i = Result.getComplexFloatImag();
4534
4535 APFloat Den = RHS_r;
4536 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4537 APFloat Tmp = RHS_i;
4538 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4539 Den.add(Tmp, APFloat::rmNearestTiesToEven);
4540
4541 Res_r = LHS_r;
4542 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4543 Tmp = LHS_i;
4544 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4545 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
4546 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
4547
4548 Res_i = LHS_i;
4549 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
4550 Tmp = LHS_r;
4551 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
4552 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
4553 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
4554 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00004555 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
4556 return Error(E, diag::note_expr_divide_by_zero);
4557
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004558 ComplexValue LHS = Result;
4559 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
4560 RHS.getComplexIntImag() * RHS.getComplexIntImag();
4561 Result.getComplexIntReal() =
4562 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
4563 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
4564 Result.getComplexIntImag() =
4565 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
4566 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
4567 }
4568 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004569 }
4570
John McCallf4cf1a12010-05-07 17:22:02 +00004571 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00004572}
4573
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004574bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4575 // Get the operand value into 'Result'.
4576 if (!Visit(E->getSubExpr()))
4577 return false;
4578
4579 switch (E->getOpcode()) {
4580 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004581 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00004582 case UO_Extension:
4583 return true;
4584 case UO_Plus:
4585 // The result is always just the subexpr.
4586 return true;
4587 case UO_Minus:
4588 if (Result.isComplexFloat()) {
4589 Result.getComplexFloatReal().changeSign();
4590 Result.getComplexFloatImag().changeSign();
4591 }
4592 else {
4593 Result.getComplexIntReal() = -Result.getComplexIntReal();
4594 Result.getComplexIntImag() = -Result.getComplexIntImag();
4595 }
4596 return true;
4597 case UO_Not:
4598 if (Result.isComplexFloat())
4599 Result.getComplexFloatImag().changeSign();
4600 else
4601 Result.getComplexIntImag() = -Result.getComplexIntImag();
4602 return true;
4603 }
4604}
4605
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00004606//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00004607// Void expression evaluation, primarily for a cast to void on the LHS of a
4608// comma operator
4609//===----------------------------------------------------------------------===//
4610
4611namespace {
4612class VoidExprEvaluator
4613 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
4614public:
4615 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
4616
4617 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00004618
4619 bool VisitCastExpr(const CastExpr *E) {
4620 switch (E->getCastKind()) {
4621 default:
4622 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4623 case CK_ToVoid:
4624 VisitIgnoredValue(E->getSubExpr());
4625 return true;
4626 }
4627 }
4628};
4629} // end anonymous namespace
4630
4631static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
4632 assert(E->isRValue() && E->getType()->isVoidType());
4633 return VoidExprEvaluator(Info).Visit(E);
4634}
4635
4636//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00004637// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004638//===----------------------------------------------------------------------===//
4639
Richard Smith47a1eed2011-10-29 20:57:55 +00004640static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004641 // In C, function designators are not lvalues, but we evaluate them as if they
4642 // are.
4643 if (E->isGLValue() || E->getType()->isFunctionType()) {
4644 LValue LV;
4645 if (!EvaluateLValue(E, LV, Info))
4646 return false;
4647 LV.moveInto(Result);
4648 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004649 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00004650 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00004651 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00004652 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004653 return false;
John McCallefdb83e2010-05-07 21:00:08 +00004654 } else if (E->getType()->hasPointerRepresentation()) {
4655 LValue LV;
4656 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004657 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004658 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00004659 } else if (E->getType()->isRealFloatingType()) {
4660 llvm::APFloat F(0.0);
4661 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004662 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00004663 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00004664 } else if (E->getType()->isAnyComplexType()) {
4665 ComplexValue C;
4666 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004667 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00004668 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00004669 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004670 MemberPtr P;
4671 if (!EvaluateMemberPointer(E, P, Info))
4672 return false;
4673 P.moveInto(Result);
4674 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00004675 } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004676 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004677 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004678 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00004679 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004680 Result = Info.CurrentCall->Temporaries[E];
Richard Smith69c2c502011-11-04 05:33:44 +00004681 } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
Richard Smith180f4792011-11-10 06:34:14 +00004682 LValue LV;
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004683 LV.set(E, Info.CurrentCall);
Richard Smith180f4792011-11-10 06:34:14 +00004684 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
4685 return false;
4686 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00004687 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00004688 if (Info.getLangOpts().CPlusPlus0x)
4689 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
4690 << E->getType();
4691 else
4692 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00004693 if (!EvaluateVoid(E, Info))
4694 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00004695 } else if (Info.getLangOpts().CPlusPlus0x) {
4696 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
4697 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004698 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00004699 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00004700 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004701 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00004702
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00004703 return true;
4704}
4705
Richard Smith69c2c502011-11-04 05:33:44 +00004706/// EvaluateConstantExpression - Evaluate an expression as a constant expression
4707/// in-place in an APValue. In some cases, the in-place evaluation is essential,
4708/// since later initializers for an object can indirectly refer to subobjects
4709/// which were initialized earlier.
4710static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
Richard Smithc1c5f272011-12-13 06:39:58 +00004711 const LValue &This, const Expr *E,
4712 CheckConstantExpressionKind CCEK) {
Richard Smith69c2c502011-11-04 05:33:44 +00004713 if (E->isRValue() && E->getType()->isLiteralType()) {
4714 // Evaluate arrays and record types in-place, so that later initializers can
4715 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00004716 if (E->getType()->isArrayType())
4717 return EvaluateArray(E, This, Result, Info);
4718 else if (E->getType()->isRecordType())
4719 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00004720 }
4721
4722 // For any other type, in-place evaluation is unimportant.
4723 CCValue CoreConstResult;
4724 return Evaluate(CoreConstResult, Info, E) &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004725 CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
Richard Smith69c2c502011-11-04 05:33:44 +00004726}
4727
Richard Smithf48fdb02011-12-09 22:58:01 +00004728/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
4729/// lvalue-to-rvalue cast if it is an lvalue.
4730static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
4731 CCValue Value;
4732 if (!::Evaluate(Value, Info, E))
4733 return false;
4734
4735 if (E->isGLValue()) {
4736 LValue LV;
4737 LV.setFrom(Value);
4738 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
4739 return false;
4740 }
4741
4742 // Check this core constant expression is a constant expression, and if so,
4743 // convert it to one.
4744 return CheckConstantExpression(Info, E, Value, Result);
4745}
Richard Smithc49bd112011-10-28 17:51:58 +00004746
Richard Smith51f47082011-10-29 00:50:52 +00004747/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00004748/// any crazy technique (that has nothing to do with language standards) that
4749/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00004750/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
4751/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00004752bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00004753 // Fast-path evaluations of integer literals, since we sometimes see files
4754 // containing vast quantities of these.
4755 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
4756 Result.Val = APValue(APSInt(L->getValue(),
4757 L->getType()->isUnsignedIntegerType()));
4758 return true;
4759 }
4760
Richard Smith1445bba2011-11-10 03:30:42 +00004761 // FIXME: Evaluating initializers for large arrays can cause performance
4762 // problems, and we don't use such values yet. Once we have a more efficient
4763 // array representation, this should be reinstated, and used by CodeGen.
Richard Smithe24f5fc2011-11-17 22:56:20 +00004764 // The same problem affects large records.
4765 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
4766 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00004767 return false;
4768
Richard Smith180f4792011-11-10 06:34:14 +00004769 // FIXME: If this is the initializer for an lvalue, pass that in.
Richard Smithf48fdb02011-12-09 22:58:01 +00004770 EvalInfo Info(Ctx, Result);
4771 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00004772}
4773
Jay Foad4ba2a172011-01-12 09:06:06 +00004774bool Expr::EvaluateAsBooleanCondition(bool &Result,
4775 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004776 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00004777 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith177dce72011-11-01 16:57:24 +00004778 HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00004779 Result);
John McCallcd7a4452010-01-05 23:42:56 +00004780}
4781
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004782bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00004783 EvalResult ExprResult;
Richard Smith51f47082011-10-29 00:50:52 +00004784 if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
Richard Smithf48fdb02011-12-09 22:58:01 +00004785 !ExprResult.Val.isInt())
Richard Smithc49bd112011-10-28 17:51:58 +00004786 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004787
Richard Smithc49bd112011-10-28 17:51:58 +00004788 Result = ExprResult.Val.getInt();
4789 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004790}
4791
Jay Foad4ba2a172011-01-12 09:06:06 +00004792bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00004793 EvalInfo Info(Ctx, Result);
4794
John McCallefdb83e2010-05-07 21:00:08 +00004795 LValue LV;
Richard Smith9a17a682011-11-07 05:07:52 +00004796 return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Richard Smithc1c5f272011-12-13 06:39:58 +00004797 CheckLValueConstantExpression(Info, this, LV, Result.Val,
4798 CCEK_Constant);
Eli Friedmanb2f295c2009-09-13 10:17:44 +00004799}
4800
Richard Smith51f47082011-10-29 00:50:52 +00004801/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
4802/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00004803bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00004804 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00004805 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00004806}
Anders Carlsson51fe9962008-11-22 21:04:56 +00004807
Jay Foad4ba2a172011-01-12 09:06:06 +00004808bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00004809 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004810}
4811
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004812APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004813 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00004814 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00004815 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00004816 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004817 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00004818
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00004819 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00004820}
John McCalld905f5a2010-05-07 05:32:02 +00004821
Abramo Bagnarae17a6432010-05-14 17:07:14 +00004822 bool Expr::EvalResult::isGlobalLValue() const {
4823 assert(Val.isLValue());
4824 return IsGlobalLValue(Val.getLValueBase());
4825 }
4826
4827
John McCalld905f5a2010-05-07 05:32:02 +00004828/// isIntegerConstantExpr - this recursive routine will test if an expression is
4829/// an integer constant expression.
4830
4831/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4832/// comma, etc
4833///
4834/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
4835/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
4836/// cast+dereference.
4837
4838// CheckICE - This function does the fundamental ICE checking: the returned
4839// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4840// Note that to reduce code duplication, this helper does no evaluation
4841// itself; the caller checks whether the expression is evaluatable, and
4842// in the rare cases where CheckICE actually cares about the evaluated
4843// value, it calls into Evalute.
4844//
4845// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00004846// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00004847// 1: This expression is not an ICE, but if it isn't evaluated, it's
4848// a legal subexpression for an ICE. This return value is used to handle
4849// the comma operator in C99 mode.
4850// 2: This expression is not an ICE, and is not a legal subexpression for one.
4851
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004852namespace {
4853
John McCalld905f5a2010-05-07 05:32:02 +00004854struct ICEDiag {
4855 unsigned Val;
4856 SourceLocation Loc;
4857
4858 public:
4859 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4860 ICEDiag() : Val(0) {}
4861};
4862
Dan Gohman3c46e8d2010-07-26 21:25:24 +00004863}
4864
4865static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00004866
4867static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4868 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00004869 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00004870 !EVResult.Val.isInt()) {
4871 return ICEDiag(2, E->getLocStart());
4872 }
4873 return NoDiag();
4874}
4875
4876static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4877 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004878 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00004879 return ICEDiag(2, E->getLocStart());
4880 }
4881
4882 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00004883#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00004884#define STMT(Node, Base) case Expr::Node##Class:
4885#define EXPR(Node, Base)
4886#include "clang/AST/StmtNodes.inc"
4887 case Expr::PredefinedExprClass:
4888 case Expr::FloatingLiteralClass:
4889 case Expr::ImaginaryLiteralClass:
4890 case Expr::StringLiteralClass:
4891 case Expr::ArraySubscriptExprClass:
4892 case Expr::MemberExprClass:
4893 case Expr::CompoundAssignOperatorClass:
4894 case Expr::CompoundLiteralExprClass:
4895 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004896 case Expr::DesignatedInitExprClass:
4897 case Expr::ImplicitValueInitExprClass:
4898 case Expr::ParenListExprClass:
4899 case Expr::VAArgExprClass:
4900 case Expr::AddrLabelExprClass:
4901 case Expr::StmtExprClass:
4902 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00004903 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004904 case Expr::CXXDynamicCastExprClass:
4905 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00004906 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004907 case Expr::CXXNullPtrLiteralExprClass:
4908 case Expr::CXXThisExprClass:
4909 case Expr::CXXThrowExprClass:
4910 case Expr::CXXNewExprClass:
4911 case Expr::CXXDeleteExprClass:
4912 case Expr::CXXPseudoDestructorExprClass:
4913 case Expr::UnresolvedLookupExprClass:
4914 case Expr::DependentScopeDeclRefExprClass:
4915 case Expr::CXXConstructExprClass:
4916 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00004917 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00004918 case Expr::CXXTemporaryObjectExprClass:
4919 case Expr::CXXUnresolvedConstructExprClass:
4920 case Expr::CXXDependentScopeMemberExprClass:
4921 case Expr::UnresolvedMemberExprClass:
4922 case Expr::ObjCStringLiteralClass:
4923 case Expr::ObjCEncodeExprClass:
4924 case Expr::ObjCMessageExprClass:
4925 case Expr::ObjCSelectorExprClass:
4926 case Expr::ObjCProtocolExprClass:
4927 case Expr::ObjCIvarRefExprClass:
4928 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004929 case Expr::ObjCIsaExprClass:
4930 case Expr::ShuffleVectorExprClass:
4931 case Expr::BlockExprClass:
4932 case Expr::BlockDeclRefExprClass:
4933 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00004934 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00004935 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00004936 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00004937 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004938 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00004939 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00004940 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00004941 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00004942 case Expr::InitListExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00004943 return ICEDiag(2, E->getLocStart());
4944
Douglas Gregoree8aff02011-01-04 17:33:58 +00004945 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004946 case Expr::GNUNullExprClass:
4947 // GCC considers the GNU __null value to be an integral constant expression.
4948 return NoDiag();
4949
John McCall91a57552011-07-15 05:09:51 +00004950 case Expr::SubstNonTypeTemplateParmExprClass:
4951 return
4952 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4953
John McCalld905f5a2010-05-07 05:32:02 +00004954 case Expr::ParenExprClass:
4955 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00004956 case Expr::GenericSelectionExprClass:
4957 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00004958 case Expr::IntegerLiteralClass:
4959 case Expr::CharacterLiteralClass:
4960 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00004961 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004962 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00004963 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00004964 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00004965 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00004966 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00004967 return NoDiag();
4968 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00004969 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00004970 // C99 6.6/3 allows function calls within unevaluated subexpressions of
4971 // constant expressions, but they can never be ICEs because an ICE cannot
4972 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00004973 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00004974 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00004975 return CheckEvalInICE(E, Ctx);
4976 return ICEDiag(2, E->getLocStart());
4977 }
4978 case Expr::DeclRefExprClass:
4979 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4980 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00004981 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00004982 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4983
4984 // Parameter variables are never constants. Without this check,
4985 // getAnyInitializer() can find a default argument, which leads
4986 // to chaos.
4987 if (isa<ParmVarDecl>(D))
4988 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4989
4990 // C++ 7.1.5.1p2
4991 // A variable of non-volatile const-qualified integral or enumeration
4992 // type initialized by an ICE can be used in ICEs.
4993 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00004994 if (!Dcl->getType()->isIntegralOrEnumerationType())
4995 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4996
John McCalld905f5a2010-05-07 05:32:02 +00004997 // Look for a declaration of this variable that has an initializer.
4998 const VarDecl *ID = 0;
4999 const Expr *Init = Dcl->getAnyInitializer(ID);
5000 if (Init) {
5001 if (ID->isInitKnownICE()) {
5002 // We have already checked whether this subexpression is an
5003 // integral constant expression.
5004 if (ID->isInitICE())
5005 return NoDiag();
5006 else
5007 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5008 }
5009
5010 // It's an ICE whether or not the definition we found is
5011 // out-of-line. See DR 721 and the discussion in Clang PR
5012 // 6206 for details.
5013
5014 if (Dcl->isCheckingICE()) {
5015 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5016 }
5017
5018 Dcl->setCheckingICE();
5019 ICEDiag Result = CheckICE(Init, Ctx);
5020 // Cache the result of the ICE test.
5021 Dcl->setInitKnownICE(Result.Val == 0);
5022 return Result;
5023 }
5024 }
5025 }
5026 return ICEDiag(2, E->getLocStart());
5027 case Expr::UnaryOperatorClass: {
5028 const UnaryOperator *Exp = cast<UnaryOperator>(E);
5029 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005030 case UO_PostInc:
5031 case UO_PostDec:
5032 case UO_PreInc:
5033 case UO_PreDec:
5034 case UO_AddrOf:
5035 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00005036 // C99 6.6/3 allows increment and decrement within unevaluated
5037 // subexpressions of constant expressions, but they can never be ICEs
5038 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005039 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00005040 case UO_Extension:
5041 case UO_LNot:
5042 case UO_Plus:
5043 case UO_Minus:
5044 case UO_Not:
5045 case UO_Real:
5046 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00005047 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005048 }
5049
5050 // OffsetOf falls through here.
5051 }
5052 case Expr::OffsetOfExprClass: {
5053 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00005054 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00005055 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00005056 // compliance: we should warn earlier for offsetof expressions with
5057 // array subscripts that aren't ICEs, and if the array subscripts
5058 // are ICEs, the value of the offsetof must be an integer constant.
5059 return CheckEvalInICE(E, Ctx);
5060 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005061 case Expr::UnaryExprOrTypeTraitExprClass: {
5062 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5063 if ((Exp->getKind() == UETT_SizeOf) &&
5064 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00005065 return ICEDiag(2, E->getLocStart());
5066 return NoDiag();
5067 }
5068 case Expr::BinaryOperatorClass: {
5069 const BinaryOperator *Exp = cast<BinaryOperator>(E);
5070 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00005071 case BO_PtrMemD:
5072 case BO_PtrMemI:
5073 case BO_Assign:
5074 case BO_MulAssign:
5075 case BO_DivAssign:
5076 case BO_RemAssign:
5077 case BO_AddAssign:
5078 case BO_SubAssign:
5079 case BO_ShlAssign:
5080 case BO_ShrAssign:
5081 case BO_AndAssign:
5082 case BO_XorAssign:
5083 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00005084 // C99 6.6/3 allows assignments within unevaluated subexpressions of
5085 // constant expressions, but they can never be ICEs because an ICE cannot
5086 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00005087 return ICEDiag(2, E->getLocStart());
5088
John McCall2de56d12010-08-25 11:45:40 +00005089 case BO_Mul:
5090 case BO_Div:
5091 case BO_Rem:
5092 case BO_Add:
5093 case BO_Sub:
5094 case BO_Shl:
5095 case BO_Shr:
5096 case BO_LT:
5097 case BO_GT:
5098 case BO_LE:
5099 case BO_GE:
5100 case BO_EQ:
5101 case BO_NE:
5102 case BO_And:
5103 case BO_Xor:
5104 case BO_Or:
5105 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00005106 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5107 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00005108 if (Exp->getOpcode() == BO_Div ||
5109 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00005110 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00005111 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00005112 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005113 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005114 if (REval == 0)
5115 return ICEDiag(1, E->getLocStart());
5116 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005117 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005118 if (LEval.isMinSignedValue())
5119 return ICEDiag(1, E->getLocStart());
5120 }
5121 }
5122 }
John McCall2de56d12010-08-25 11:45:40 +00005123 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00005124 if (Ctx.getLangOptions().C99) {
5125 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5126 // if it isn't evaluated.
5127 if (LHSResult.Val == 0 && RHSResult.Val == 0)
5128 return ICEDiag(1, E->getLocStart());
5129 } else {
5130 // In both C89 and C++, commas in ICEs are illegal.
5131 return ICEDiag(2, E->getLocStart());
5132 }
5133 }
5134 if (LHSResult.Val >= RHSResult.Val)
5135 return LHSResult;
5136 return RHSResult;
5137 }
John McCall2de56d12010-08-25 11:45:40 +00005138 case BO_LAnd:
5139 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00005140 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5141 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5142 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5143 // Rare case where the RHS has a comma "side-effect"; we need
5144 // to actually check the condition to see whether the side
5145 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00005146 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005147 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00005148 return RHSResult;
5149 return NoDiag();
5150 }
5151
5152 if (LHSResult.Val >= RHSResult.Val)
5153 return LHSResult;
5154 return RHSResult;
5155 }
5156 }
5157 }
5158 case Expr::ImplicitCastExprClass:
5159 case Expr::CStyleCastExprClass:
5160 case Expr::CXXFunctionalCastExprClass:
5161 case Expr::CXXStaticCastExprClass:
5162 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00005163 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00005164 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00005165 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith98326ed2011-10-25 00:21:54 +00005166 if (isa<ExplicitCastExpr>(E) &&
Richard Smith32cb4712011-10-24 18:26:35 +00005167 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
5168 return NoDiag();
Eli Friedmaneea0e812011-09-29 21:49:34 +00005169 switch (cast<CastExpr>(E)->getCastKind()) {
5170 case CK_LValueToRValue:
5171 case CK_NoOp:
5172 case CK_IntegralToBoolean:
5173 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00005174 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00005175 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00005176 return ICEDiag(2, E->getLocStart());
5177 }
John McCalld905f5a2010-05-07 05:32:02 +00005178 }
John McCall56ca35d2011-02-17 10:25:35 +00005179 case Expr::BinaryConditionalOperatorClass: {
5180 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
5181 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
5182 if (CommonResult.Val == 2) return CommonResult;
5183 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
5184 if (FalseResult.Val == 2) return FalseResult;
5185 if (CommonResult.Val == 1) return CommonResult;
5186 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005187 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00005188 return FalseResult;
5189 }
John McCalld905f5a2010-05-07 05:32:02 +00005190 case Expr::ConditionalOperatorClass: {
5191 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
5192 // If the condition (ignoring parens) is a __builtin_constant_p call,
5193 // then only the true side is actually considered in an integer constant
5194 // expression, and it is fully evaluated. This is an important GNU
5195 // extension. See GCC PR38377 for discussion.
5196 if (const CallExpr *CallCE
5197 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith180f4792011-11-10 06:34:14 +00005198 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
John McCalld905f5a2010-05-07 05:32:02 +00005199 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00005200 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00005201 !EVResult.Val.isInt()) {
5202 return ICEDiag(2, E->getLocStart());
5203 }
5204 return NoDiag();
5205 }
5206 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00005207 if (CondResult.Val == 2)
5208 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00005209
Richard Smithf48fdb02011-12-09 22:58:01 +00005210 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
5211 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00005212
John McCalld905f5a2010-05-07 05:32:02 +00005213 if (TrueResult.Val == 2)
5214 return TrueResult;
5215 if (FalseResult.Val == 2)
5216 return FalseResult;
5217 if (CondResult.Val == 1)
5218 return CondResult;
5219 if (TrueResult.Val == 0 && FalseResult.Val == 0)
5220 return NoDiag();
5221 // Rare case where the diagnostics depend on which side is evaluated
5222 // Note that if we get here, CondResult is 0, and at least one of
5223 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005224 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00005225 return FalseResult;
5226 }
5227 return TrueResult;
5228 }
5229 case Expr::CXXDefaultArgExprClass:
5230 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
5231 case Expr::ChooseExprClass: {
5232 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
5233 }
5234 }
5235
5236 // Silence a GCC warning
5237 return ICEDiag(2, E->getLocStart());
5238}
5239
Richard Smithf48fdb02011-12-09 22:58:01 +00005240/// Evaluate an expression as a C++11 integral constant expression.
5241static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
5242 const Expr *E,
5243 llvm::APSInt *Value,
5244 SourceLocation *Loc) {
5245 if (!E->getType()->isIntegralOrEnumerationType()) {
5246 if (Loc) *Loc = E->getExprLoc();
5247 return false;
5248 }
5249
5250 Expr::EvalResult Result;
Richard Smithdd1f29b2011-12-12 09:28:41 +00005251 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
5252 Result.Diag = &Diags;
5253 EvalInfo Info(Ctx, Result);
5254
5255 bool IsICE = EvaluateAsRValue(Info, E, Result.Val);
5256 if (!Diags.empty()) {
5257 IsICE = false;
5258 if (Loc) *Loc = Diags[0].first;
5259 } else if (!IsICE && Loc) {
5260 *Loc = E->getExprLoc();
Richard Smithf48fdb02011-12-09 22:58:01 +00005261 }
Richard Smithdd1f29b2011-12-12 09:28:41 +00005262
5263 if (!IsICE)
5264 return false;
5265
5266 assert(Result.Val.isInt() && "pointer cast to int is not an ICE");
5267 if (Value) *Value = Result.Val.getInt();
5268 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00005269}
5270
Richard Smithdd1f29b2011-12-12 09:28:41 +00005271bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00005272 if (Ctx.getLangOptions().CPlusPlus0x)
5273 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
5274
John McCalld905f5a2010-05-07 05:32:02 +00005275 ICEDiag d = CheckICE(this, Ctx);
5276 if (d.Val != 0) {
5277 if (Loc) *Loc = d.Loc;
5278 return false;
5279 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005280 return true;
5281}
5282
5283bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
5284 SourceLocation *Loc, bool isEvaluated) const {
5285 if (Ctx.getLangOptions().CPlusPlus0x)
5286 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
5287
5288 if (!isIntegerConstantExpr(Ctx, Loc))
5289 return false;
5290 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00005291 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00005292 return true;
5293}