blob: b8b98da25da470386402f761d5b6b7148c6b0c1d [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//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidisb2c60b02012-03-01 19:45:56 +000047#include "llvm/Support/SaveAndRestore.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Richard Smith1aa0be82012-03-03 22:46:17 +0000291 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000292 typedef MapTy::const_iterator temp_iterator;
293 /// Temporaries - Temporary lvalues materialized within this stack frame.
294 MapTy Temporaries;
295
Richard Smith08d6e032011-12-16 19:06:07 +0000296 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
297 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000298 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000299 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000300 };
301
Richard Smithdd1f29b2011-12-12 09:28:41 +0000302 /// A partial diagnostic which we might know in advance that we are not going
303 /// to emit.
304 class OptionalDiagnostic {
305 PartialDiagnostic *Diag;
306
307 public:
308 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
309
310 template<typename T>
311 OptionalDiagnostic &operator<<(const T &v) {
312 if (Diag)
313 *Diag << v;
314 return *this;
315 }
Richard Smith789f9b62012-01-31 04:08:20 +0000316
317 OptionalDiagnostic &operator<<(const APSInt &I) {
318 if (Diag) {
319 llvm::SmallVector<char, 32> Buffer;
320 I.toString(Buffer);
321 *Diag << StringRef(Buffer.data(), Buffer.size());
322 }
323 return *this;
324 }
325
326 OptionalDiagnostic &operator<<(const APFloat &F) {
327 if (Diag) {
328 llvm::SmallVector<char, 32> Buffer;
329 F.toString(Buffer);
330 *Diag << StringRef(Buffer.data(), Buffer.size());
331 }
332 return *this;
333 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000334 };
335
Richard Smith83587db2012-02-15 02:18:13 +0000336 /// EvalInfo - This is a private struct used by the evaluator to capture
337 /// information about a subexpression as it is folded. It retains information
338 /// about the AST context, but also maintains information about the folded
339 /// expression.
340 ///
341 /// If an expression could be evaluated, it is still possible it is not a C
342 /// "integer constant expression" or constant expression. If not, this struct
343 /// captures information about how and why not.
344 ///
345 /// One bit of information passed *into* the request for constant folding
346 /// indicates whether the subexpression is "evaluated" or not according to C
347 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
348 /// evaluate the expression regardless of what the RHS is, but C only allows
349 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000350 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000351 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000352
Richard Smithbd552ef2011-10-31 05:52:43 +0000353 /// EvalStatus - Contains information about the evaluation.
354 Expr::EvalStatus &EvalStatus;
355
356 /// CurrentCall - The top of the constexpr call stack.
357 CallStackFrame *CurrentCall;
358
Richard Smithbd552ef2011-10-31 05:52:43 +0000359 /// CallStackDepth - The number of calls in the call stack right now.
360 unsigned CallStackDepth;
361
Richard Smith83587db2012-02-15 02:18:13 +0000362 /// NextCallIndex - The next call index to assign.
363 unsigned NextCallIndex;
364
Richard Smith1aa0be82012-03-03 22:46:17 +0000365 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000366 /// OpaqueValues - Values used as the common expression in a
367 /// BinaryConditionalOperator.
368 MapTy OpaqueValues;
369
370 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000371 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 CallStackFrame BottomFrame;
373
Richard Smith180f4792011-11-10 06:34:14 +0000374 /// EvaluatingDecl - This is the declaration whose initializer is being
375 /// evaluated, if any.
376 const VarDecl *EvaluatingDecl;
377
378 /// EvaluatingDeclValue - This is the value being constructed for the
379 /// declaration whose initializer is being evaluated, if any.
380 APValue *EvaluatingDeclValue;
381
Richard Smithc1c5f272011-12-13 06:39:58 +0000382 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383 /// notes attached to it will also be stored, otherwise they will not be.
384 bool HasActiveDiagnostic;
385
Richard Smith745f5142012-01-27 01:14:48 +0000386 /// CheckingPotentialConstantExpression - Are we checking whether the
387 /// expression is a potential constant expression? If so, some diagnostics
388 /// are suppressed.
389 bool CheckingPotentialConstantExpression;
390
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000391 /// \brief Stack depth of IntExprEvaluator.
392 /// We check this against a maximum value to avoid stack overflow, see
393 /// test case in test/Sema/many-logical-ops.c.
394 // FIXME: This is a hack; handle properly unlimited logical ops.
395 unsigned IntExprEvaluatorDepth;
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
397 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000398 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000399 CallStackDepth(0), NextCallIndex(1),
400 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000401 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +0000402 CheckingPotentialConstantExpression(false), IntExprEvaluatorDepth(0) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000403
Richard Smith1aa0be82012-03-03 22:46:17 +0000404 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000405 MapTy::const_iterator i = OpaqueValues.find(e);
406 if (i == OpaqueValues.end()) return 0;
407 return &i->second;
408 }
409
Richard Smith180f4792011-11-10 06:34:14 +0000410 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
411 EvaluatingDecl = VD;
412 EvaluatingDeclValue = &Value;
413 }
414
David Blaikie4e4d0842012-03-11 07:00:24 +0000415 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000416
Richard Smithc1c5f272011-12-13 06:39:58 +0000417 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000418 // Don't perform any constexpr calls (other than the call we're checking)
419 // when checking a potential constant expression.
420 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
421 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000422 if (NextCallIndex == 0) {
423 // NextCallIndex has wrapped around.
424 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
425 return false;
426 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000427 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
428 return true;
429 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
430 << getLangOpts().ConstexprCallDepth;
431 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000432 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000433
Richard Smith83587db2012-02-15 02:18:13 +0000434 CallStackFrame *getCallFrame(unsigned CallIndex) {
435 assert(CallIndex && "no call index in getCallFrame");
436 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
437 // be null in this loop.
438 CallStackFrame *Frame = CurrentCall;
439 while (Frame->Index > CallIndex)
440 Frame = Frame->Caller;
441 return (Frame->Index == CallIndex) ? Frame : 0;
442 }
443
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 private:
445 /// Add a diagnostic to the diagnostics list.
446 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
447 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
448 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
449 return EvalStatus.Diag->back().second;
450 }
451
Richard Smith08d6e032011-12-16 19:06:07 +0000452 /// Add notes containing a call stack to the current point of evaluation.
453 void addCallStack(unsigned Limit);
454
Richard Smithc1c5f272011-12-13 06:39:58 +0000455 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000456 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000457 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
458 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000459 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000460 // If we have a prior diagnostic, it will be noting that the expression
461 // isn't a constant expression. This diagnostic is more important.
462 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000463 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000464 unsigned CallStackNotes = CallStackDepth - 1;
465 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
466 if (Limit)
467 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (CheckingPotentialConstantExpression)
469 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000470
Richard Smithc1c5f272011-12-13 06:39:58 +0000471 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000472 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000473 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
474 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000475 if (!CheckingPotentialConstantExpression)
476 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000477 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000478 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000480 return OptionalDiagnostic();
481 }
482
Richard Smith5cfc7d82012-03-15 04:53:45 +0000483 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
484 = diag::note_invalid_subexpr_in_const_expr,
485 unsigned ExtraNotes = 0) {
486 if (EvalStatus.Diag)
487 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
488 HasActiveDiagnostic = false;
489 return OptionalDiagnostic();
490 }
491
Richard Smithdd1f29b2011-12-12 09:28:41 +0000492 /// Diagnose that the evaluation does not produce a C++11 core constant
493 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000494 template<typename LocArg>
495 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000496 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000497 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000498 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000499 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
500 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000501 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000502 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000503 return Diag(Loc, DiagId, ExtraNotes);
504 }
505
506 /// Add a note to a prior diagnostic.
507 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
508 if (!HasActiveDiagnostic)
509 return OptionalDiagnostic();
510 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000511 }
Richard Smith099e7f62011-12-19 06:19:21 +0000512
513 /// Add a stack of notes to a prior diagnostic.
514 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
515 if (HasActiveDiagnostic) {
516 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
517 Diags.begin(), Diags.end());
518 }
519 }
Richard Smith745f5142012-01-27 01:14:48 +0000520
521 /// Should we continue evaluation as much as possible after encountering a
522 /// construct which can't be folded?
523 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000524 return CheckingPotentialConstantExpression &&
525 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000526 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000527 };
Richard Smithf15fda02012-02-02 01:16:57 +0000528
529 /// Object used to treat all foldable expressions as constant expressions.
530 struct FoldConstant {
531 bool Enabled;
532
533 explicit FoldConstant(EvalInfo &Info)
534 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
535 !Info.EvalStatus.HasSideEffects) {
536 }
537 // Treat the value we've computed since this object was created as constant.
538 void Fold(EvalInfo &Info) {
539 if (Enabled && !Info.EvalStatus.Diag->empty() &&
540 !Info.EvalStatus.HasSideEffects)
541 Info.EvalStatus.Diag->clear();
542 }
543 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000544
545 /// RAII object used to suppress diagnostics and side-effects from a
546 /// speculative evaluation.
547 class SpeculativeEvaluationRAII {
548 EvalInfo &Info;
549 Expr::EvalStatus Old;
550
551 public:
552 SpeculativeEvaluationRAII(EvalInfo &Info,
553 llvm::SmallVectorImpl<PartialDiagnosticAt>
554 *NewDiag = 0)
555 : Info(Info), Old(Info.EvalStatus) {
556 Info.EvalStatus.Diag = NewDiag;
557 }
558 ~SpeculativeEvaluationRAII() {
559 Info.EvalStatus = Old;
560 }
561 };
Richard Smith08d6e032011-12-16 19:06:07 +0000562}
Richard Smithbd552ef2011-10-31 05:52:43 +0000563
Richard Smithb4e85ed2012-01-06 16:39:00 +0000564bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
565 CheckSubobjectKind CSK) {
566 if (Invalid)
567 return false;
568 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000569 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000570 << CSK;
571 setInvalid();
572 return false;
573 }
574 return true;
575}
576
577void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
578 const Expr *E, uint64_t N) {
579 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000580 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000581 << static_cast<int>(N) << /*array*/ 0
582 << static_cast<unsigned>(MostDerivedArraySize);
583 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000584 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000585 << static_cast<int>(N) << /*non-array*/ 1;
586 setInvalid();
587}
588
Richard Smith08d6e032011-12-16 19:06:07 +0000589CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
590 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000591 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000592 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000593 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000594 Info.CurrentCall = this;
595 ++Info.CallStackDepth;
596}
597
598CallStackFrame::~CallStackFrame() {
599 assert(Info.CurrentCall == this && "calls retired out of order");
600 --Info.CallStackDepth;
601 Info.CurrentCall = Caller;
602}
603
604/// Produce a string describing the given constexpr call.
605static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
606 unsigned ArgIndex = 0;
607 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000608 !isa<CXXConstructorDecl>(Frame->Callee) &&
609 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000610
611 if (!IsMemberCall)
612 Out << *Frame->Callee << '(';
613
614 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
615 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000616 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000617 Out << ", ";
618
619 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000620 const APValue &Arg = Frame->Arguments[ArgIndex];
621 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000622
623 if (ArgIndex == 0 && IsMemberCall)
624 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000625 }
626
Richard Smith08d6e032011-12-16 19:06:07 +0000627 Out << ')';
628}
629
630void EvalInfo::addCallStack(unsigned Limit) {
631 // Determine which calls to skip, if any.
632 unsigned ActiveCalls = CallStackDepth - 1;
633 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
634 if (Limit && Limit < ActiveCalls) {
635 SkipStart = Limit / 2 + Limit % 2;
636 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000637 }
638
Richard Smith08d6e032011-12-16 19:06:07 +0000639 // Walk the call stack and add the diagnostics.
640 unsigned CallIdx = 0;
641 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
642 Frame = Frame->Caller, ++CallIdx) {
643 // Skip this call?
644 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
645 if (CallIdx == SkipStart) {
646 // Note that we're skipping calls.
647 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
648 << unsigned(ActiveCalls - Limit);
649 }
650 continue;
651 }
652
653 llvm::SmallVector<char, 128> Buffer;
654 llvm::raw_svector_ostream Out(Buffer);
655 describeCall(Frame, Out);
656 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
657 }
658}
659
660namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000661 struct ComplexValue {
662 private:
663 bool IsInt;
664
665 public:
666 APSInt IntReal, IntImag;
667 APFloat FloatReal, FloatImag;
668
669 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
670
671 void makeComplexFloat() { IsInt = false; }
672 bool isComplexFloat() const { return !IsInt; }
673 APFloat &getComplexFloatReal() { return FloatReal; }
674 APFloat &getComplexFloatImag() { return FloatImag; }
675
676 void makeComplexInt() { IsInt = true; }
677 bool isComplexInt() const { return IsInt; }
678 APSInt &getComplexIntReal() { return IntReal; }
679 APSInt &getComplexIntImag() { return IntImag; }
680
Richard Smith1aa0be82012-03-03 22:46:17 +0000681 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000682 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000683 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000684 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000685 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000686 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000687 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000688 assert(v.isComplexFloat() || v.isComplexInt());
689 if (v.isComplexFloat()) {
690 makeComplexFloat();
691 FloatReal = v.getComplexFloatReal();
692 FloatImag = v.getComplexFloatImag();
693 } else {
694 makeComplexInt();
695 IntReal = v.getComplexIntReal();
696 IntImag = v.getComplexIntImag();
697 }
698 }
John McCallf4cf1a12010-05-07 17:22:02 +0000699 };
John McCallefdb83e2010-05-07 21:00:08 +0000700
701 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000702 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000703 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000704 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000705 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000707 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000708 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000709 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000710 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000711 SubobjectDesignator &getLValueDesignator() { return Designator; }
712 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000713
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void moveInto(APValue &V) const {
715 if (Designator.Invalid)
716 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
717 else
718 V = APValue(Base, Offset, Designator.Entries,
719 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000720 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000721 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000722 assert(V.isLValue());
723 Base = V.getLValueBase();
724 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000726 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000727 }
728
Richard Smith83587db2012-02-15 02:18:13 +0000729 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000730 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000731 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000732 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000733 Designator = SubobjectDesignator(getType(B));
734 }
735
736 // Check that this LValue is not based on a null pointer. If it is, produce
737 // a diagnostic and mark the designator as invalid.
738 bool checkNullPointer(EvalInfo &Info, const Expr *E,
739 CheckSubobjectKind CSK) {
740 if (Designator.Invalid)
741 return false;
742 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000743 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000744 << CSK;
745 Designator.setInvalid();
746 return false;
747 }
748 return true;
749 }
750
751 // Check this LValue refers to an object. If not, set the designator to be
752 // invalid and emit a diagnostic.
753 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000754 // Outside C++11, do not build a designator referring to a subobject of
755 // any object: we won't use such a designator for anything.
756 if (!Info.getLangOpts().CPlusPlus0x)
757 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000758 return checkNullPointer(Info, E, CSK) &&
759 Designator.checkSubobject(Info, E, CSK);
760 }
761
762 void addDecl(EvalInfo &Info, const Expr *E,
763 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000764 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
765 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000766 }
767 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000768 if (checkSubobject(Info, E, CSK_ArrayToPointer))
769 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000770 }
Richard Smith86024012012-02-18 22:04:06 +0000771 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000772 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
773 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000774 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000775 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000776 if (checkNullPointer(Info, E, CSK_ArrayIndex))
777 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000778 }
John McCallefdb83e2010-05-07 21:00:08 +0000779 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000780
781 struct MemberPtr {
782 MemberPtr() {}
783 explicit MemberPtr(const ValueDecl *Decl) :
784 DeclAndIsDerivedMember(Decl, false), Path() {}
785
786 /// The member or (direct or indirect) field referred to by this member
787 /// pointer, or 0 if this is a null member pointer.
788 const ValueDecl *getDecl() const {
789 return DeclAndIsDerivedMember.getPointer();
790 }
791 /// Is this actually a member of some type derived from the relevant class?
792 bool isDerivedMember() const {
793 return DeclAndIsDerivedMember.getInt();
794 }
795 /// Get the class which the declaration actually lives in.
796 const CXXRecordDecl *getContainingRecord() const {
797 return cast<CXXRecordDecl>(
798 DeclAndIsDerivedMember.getPointer()->getDeclContext());
799 }
800
Richard Smith1aa0be82012-03-03 22:46:17 +0000801 void moveInto(APValue &V) const {
802 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000803 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000804 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000805 assert(V.isMemberPointer());
806 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
807 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
808 Path.clear();
809 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
810 Path.insert(Path.end(), P.begin(), P.end());
811 }
812
813 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
814 /// whether the member is a member of some class derived from the class type
815 /// of the member pointer.
816 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
817 /// Path - The path of base/derived classes from the member declaration's
818 /// class (exclusive) to the class type of the member pointer (inclusive).
819 SmallVector<const CXXRecordDecl*, 4> Path;
820
821 /// Perform a cast towards the class of the Decl (either up or down the
822 /// hierarchy).
823 bool castBack(const CXXRecordDecl *Class) {
824 assert(!Path.empty());
825 const CXXRecordDecl *Expected;
826 if (Path.size() >= 2)
827 Expected = Path[Path.size() - 2];
828 else
829 Expected = getContainingRecord();
830 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
831 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
832 // if B does not contain the original member and is not a base or
833 // derived class of the class containing the original member, the result
834 // of the cast is undefined.
835 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
836 // (D::*). We consider that to be a language defect.
837 return false;
838 }
839 Path.pop_back();
840 return true;
841 }
842 /// Perform a base-to-derived member pointer cast.
843 bool castToDerived(const CXXRecordDecl *Derived) {
844 if (!getDecl())
845 return true;
846 if (!isDerivedMember()) {
847 Path.push_back(Derived);
848 return true;
849 }
850 if (!castBack(Derived))
851 return false;
852 if (Path.empty())
853 DeclAndIsDerivedMember.setInt(false);
854 return true;
855 }
856 /// Perform a derived-to-base member pointer cast.
857 bool castToBase(const CXXRecordDecl *Base) {
858 if (!getDecl())
859 return true;
860 if (Path.empty())
861 DeclAndIsDerivedMember.setInt(true);
862 if (isDerivedMember()) {
863 Path.push_back(Base);
864 return true;
865 }
866 return castBack(Base);
867 }
868 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000869
Richard Smithb02e4622012-02-01 01:42:44 +0000870 /// Compare two member pointers, which are assumed to be of the same type.
871 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
872 if (!LHS.getDecl() || !RHS.getDecl())
873 return !LHS.getDecl() && !RHS.getDecl();
874 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
875 return false;
876 return LHS.Path == RHS.Path;
877 }
878
Richard Smithc1c5f272011-12-13 06:39:58 +0000879 /// Kinds of constant expression checking, for diagnostics.
880 enum CheckConstantExpressionKind {
881 CCEK_Constant, ///< A normal constant.
882 CCEK_ReturnValue, ///< A constexpr function return value.
883 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
884 };
John McCallf4cf1a12010-05-07 17:22:02 +0000885}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000886
Richard Smith1aa0be82012-03-03 22:46:17 +0000887static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000888static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
889 const LValue &This, const Expr *E,
890 CheckConstantExpressionKind CCEK = CCEK_Constant,
891 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000892static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
893static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000894static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
895 EvalInfo &Info);
896static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000897static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000898static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000899 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000900static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000901static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000902
903//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000904// Misc utilities
905//===----------------------------------------------------------------------===//
906
Richard Smith180f4792011-11-10 06:34:14 +0000907/// Should this call expression be treated as a string literal?
908static bool IsStringLiteralCall(const CallExpr *E) {
909 unsigned Builtin = E->isBuiltinCall();
910 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
911 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
912}
913
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000914static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000915 // C++11 [expr.const]p3 An address constant expression is a prvalue core
916 // constant expression of pointer type that evaluates to...
917
918 // ... a null pointer value, or a prvalue core constant expression of type
919 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000920 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000921
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000922 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
923 // ... the address of an object with static storage duration,
924 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
925 return VD->hasGlobalStorage();
926 // ... the address of a function,
927 return isa<FunctionDecl>(D);
928 }
929
930 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000931 switch (E->getStmtClass()) {
932 default:
933 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000934 case Expr::CompoundLiteralExprClass: {
935 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
936 return CLE->isFileScope() && CLE->isLValue();
937 }
Richard Smith180f4792011-11-10 06:34:14 +0000938 // A string literal has static storage duration.
939 case Expr::StringLiteralClass:
940 case Expr::PredefinedExprClass:
941 case Expr::ObjCStringLiteralClass:
942 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000943 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000944 return true;
945 case Expr::CallExprClass:
946 return IsStringLiteralCall(cast<CallExpr>(E));
947 // For GCC compatibility, &&label has static storage duration.
948 case Expr::AddrLabelExprClass:
949 return true;
950 // A Block literal expression may be used as the initialization value for
951 // Block variables at global or local static scope.
952 case Expr::BlockExprClass:
953 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000954 case Expr::ImplicitValueInitExprClass:
955 // FIXME:
956 // We can never form an lvalue with an implicit value initialization as its
957 // base through expression evaluation, so these only appear in one case: the
958 // implicit variable declaration we invent when checking whether a constexpr
959 // constructor can produce a constant expression. We must assume that such
960 // an expression might be a global lvalue.
961 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000962 }
John McCall42c8f872010-05-10 23:27:23 +0000963}
964
Richard Smith83587db2012-02-15 02:18:13 +0000965static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
966 assert(Base && "no location for a null lvalue");
967 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
968 if (VD)
969 Info.Note(VD->getLocation(), diag::note_declared_at);
970 else
971 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
972 diag::note_constexpr_temporary_here);
973}
974
Richard Smith9a17a682011-11-07 05:07:52 +0000975/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000976/// value for an address or reference constant expression. Return true if we
977/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000978static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
979 QualType Type, const LValue &LVal) {
980 bool IsReferenceType = Type->isReferenceType();
981
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 APValue::LValueBase Base = LVal.getLValueBase();
983 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
984
Richard Smithb78ae972012-02-18 04:58:18 +0000985 // Check that the object is a global. Note that the fake 'this' object we
986 // manufacture when checking potential constant expressions is conservatively
987 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000988 if (!IsGlobalLValue(Base)) {
989 if (Info.getLangOpts().CPlusPlus0x) {
990 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000991 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
992 << IsReferenceType << !Designator.Entries.empty()
993 << !!VD << VD;
994 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000995 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000996 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000997 }
Richard Smith61e61622012-01-12 06:08:57 +0000998 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000999 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001000 }
Richard Smith83587db2012-02-15 02:18:13 +00001001 assert((Info.CheckingPotentialConstantExpression ||
1002 LVal.getLValueCallIndex() == 0) &&
1003 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001004
1005 // Allow address constant expressions to be past-the-end pointers. This is
1006 // an extension: the standard requires them to point to an object.
1007 if (!IsReferenceType)
1008 return true;
1009
1010 // A reference constant expression must refer to an object.
1011 if (!Base) {
1012 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001014 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001015 }
1016
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001018 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001020 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001021 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001022 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001023 }
1024
Richard Smith9a17a682011-11-07 05:07:52 +00001025 return true;
1026}
1027
Richard Smith51201882011-12-30 21:15:51 +00001028/// Check that this core constant expression is of literal type, and if not,
1029/// produce an appropriate diagnostic.
1030static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1031 if (!E->isRValue() || E->getType()->isLiteralType())
1032 return true;
1033
1034 // Prvalue constant expressions must be of literal types.
1035 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001036 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001037 << E->getType();
1038 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001039 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001040 return false;
1041}
1042
Richard Smith47a1eed2011-10-29 20:57:55 +00001043/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001044/// constant expression. If not, report an appropriate diagnostic. Does not
1045/// check that the expression is of literal type.
1046static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1047 QualType Type, const APValue &Value) {
1048 // Core issue 1454: For a literal constant expression of array or class type,
1049 // each subobject of its value shall have been initialized by a constant
1050 // expression.
1051 if (Value.isArray()) {
1052 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1053 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1054 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1055 Value.getArrayInitializedElt(I)))
1056 return false;
1057 }
1058 if (!Value.hasArrayFiller())
1059 return true;
1060 return CheckConstantExpression(Info, DiagLoc, EltTy,
1061 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001062 }
Richard Smith83587db2012-02-15 02:18:13 +00001063 if (Value.isUnion() && Value.getUnionField()) {
1064 return CheckConstantExpression(Info, DiagLoc,
1065 Value.getUnionField()->getType(),
1066 Value.getUnionValue());
1067 }
1068 if (Value.isStruct()) {
1069 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1070 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1071 unsigned BaseIndex = 0;
1072 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1073 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075 Value.getStructBase(BaseIndex)))
1076 return false;
1077 }
1078 }
1079 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1080 I != E; ++I) {
1081 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1082 Value.getStructField((*I)->getFieldIndex())))
1083 return false;
1084 }
1085 }
1086
1087 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001088 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001089 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001090 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1091 }
1092
1093 // Everything else is fine.
1094 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001095}
1096
Richard Smith9e36b532011-10-31 05:11:32 +00001097const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001098 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001099}
1100
1101static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001102 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001103}
1104
Richard Smith65ac5982011-11-01 21:06:14 +00001105static bool IsWeakLValue(const LValue &Value) {
1106 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001107 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001108}
1109
Richard Smith1aa0be82012-03-03 22:46:17 +00001110static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001111 // A null base expression indicates a null pointer. These are always
1112 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001113 if (!Value.getLValueBase()) {
1114 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001115 return true;
1116 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001117
Richard Smithe24f5fc2011-11-17 22:56:20 +00001118 // We have a non-null base. These are generally known to be true, but if it's
1119 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001120 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001121 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001122 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001123}
1124
Richard Smith1aa0be82012-03-03 22:46:17 +00001125static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001126 switch (Val.getKind()) {
1127 case APValue::Uninitialized:
1128 return false;
1129 case APValue::Int:
1130 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001131 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001132 case APValue::Float:
1133 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001134 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001135 case APValue::ComplexInt:
1136 Result = Val.getComplexIntReal().getBoolValue() ||
1137 Val.getComplexIntImag().getBoolValue();
1138 return true;
1139 case APValue::ComplexFloat:
1140 Result = !Val.getComplexFloatReal().isZero() ||
1141 !Val.getComplexFloatImag().isZero();
1142 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001143 case APValue::LValue:
1144 return EvalPointerValueAsBool(Val, Result);
1145 case APValue::MemberPointer:
1146 Result = Val.getMemberPointerDecl();
1147 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001148 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001149 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001150 case APValue::Struct:
1151 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001152 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001153 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001154 }
1155
Richard Smithc49bd112011-10-28 17:51:58 +00001156 llvm_unreachable("unknown APValue kind");
1157}
1158
1159static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1160 EvalInfo &Info) {
1161 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001162 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001163 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001164 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001165 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001166}
1167
Richard Smithc1c5f272011-12-13 06:39:58 +00001168template<typename T>
1169static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1170 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001171 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001172 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001173 return false;
1174}
1175
1176static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1177 QualType SrcType, const APFloat &Value,
1178 QualType DestType, APSInt &Result) {
1179 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001180 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001181 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Richard Smithc1c5f272011-12-13 06:39:58 +00001183 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001184 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001185 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1186 & APFloat::opInvalidOp)
1187 return HandleOverflow(Info, E, Value, DestType);
1188 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001189}
1190
Richard Smithc1c5f272011-12-13 06:39:58 +00001191static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1192 QualType SrcType, QualType DestType,
1193 APFloat &Result) {
1194 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001195 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001196 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1197 APFloat::rmNearestTiesToEven, &ignored)
1198 & APFloat::opOverflow)
1199 return HandleOverflow(Info, E, Value, DestType);
1200 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001201}
1202
Richard Smithf72fccf2012-01-30 22:27:01 +00001203static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1204 QualType DestType, QualType SrcType,
1205 APSInt &Value) {
1206 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001207 APSInt Result = Value;
1208 // Figure out if this is a truncate, extend or noop cast.
1209 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001210 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001211 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001212 return Result;
1213}
1214
Richard Smithc1c5f272011-12-13 06:39:58 +00001215static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1216 QualType SrcType, const APSInt &Value,
1217 QualType DestType, APFloat &Result) {
1218 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1219 if (Result.convertFromAPInt(Value, Value.isSigned(),
1220 APFloat::rmNearestTiesToEven)
1221 & APFloat::opOverflow)
1222 return HandleOverflow(Info, E, Value, DestType);
1223 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001224}
1225
Eli Friedmane6a24e82011-12-22 03:51:45 +00001226static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1227 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001228 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001229 if (!Evaluate(SVal, Info, E))
1230 return false;
1231 if (SVal.isInt()) {
1232 Res = SVal.getInt();
1233 return true;
1234 }
1235 if (SVal.isFloat()) {
1236 Res = SVal.getFloat().bitcastToAPInt();
1237 return true;
1238 }
1239 if (SVal.isVector()) {
1240 QualType VecTy = E->getType();
1241 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1242 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1243 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1244 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1245 Res = llvm::APInt::getNullValue(VecSize);
1246 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1247 APValue &Elt = SVal.getVectorElt(i);
1248 llvm::APInt EltAsInt;
1249 if (Elt.isInt()) {
1250 EltAsInt = Elt.getInt();
1251 } else if (Elt.isFloat()) {
1252 EltAsInt = Elt.getFloat().bitcastToAPInt();
1253 } else {
1254 // Don't try to handle vectors of anything other than int or float
1255 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001256 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001257 return false;
1258 }
1259 unsigned BaseEltSize = EltAsInt.getBitWidth();
1260 if (BigEndian)
1261 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1262 else
1263 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1264 }
1265 return true;
1266 }
1267 // Give up if the input isn't an int, float, or vector. For example, we
1268 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001269 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001270 return false;
1271}
1272
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273/// Cast an lvalue referring to a base subobject to a derived class, by
1274/// truncating the lvalue's path to the given length.
1275static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1276 const RecordDecl *TruncatedType,
1277 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001278 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001279
1280 // Check we actually point to a derived class object.
1281 if (TruncatedElements == D.Entries.size())
1282 return true;
1283 assert(TruncatedElements >= D.MostDerivedPathLength &&
1284 "not casting to a derived class");
1285 if (!Result.checkSubobject(Info, E, CSK_Derived))
1286 return false;
1287
1288 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001289 const RecordDecl *RD = TruncatedType;
1290 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001291 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1292 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001293 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001294 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001295 else
Richard Smith180f4792011-11-10 06:34:14 +00001296 Result.Offset -= Layout.getBaseClassOffset(Base);
1297 RD = Base;
1298 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001299 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001300 return true;
1301}
1302
Richard Smithb4e85ed2012-01-06 16:39:00 +00001303static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001304 const CXXRecordDecl *Derived,
1305 const CXXRecordDecl *Base,
1306 const ASTRecordLayout *RL = 0) {
1307 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1308 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001309 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001310}
1311
Richard Smithb4e85ed2012-01-06 16:39:00 +00001312static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001313 const CXXRecordDecl *DerivedDecl,
1314 const CXXBaseSpecifier *Base) {
1315 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1316
1317 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001319 return true;
1320 }
1321
Richard Smithb4e85ed2012-01-06 16:39:00 +00001322 SubobjectDesignator &D = Obj.Designator;
1323 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001324 return false;
1325
Richard Smithb4e85ed2012-01-06 16:39:00 +00001326 // Extract most-derived object and corresponding type.
1327 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1328 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1329 return false;
1330
1331 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001332 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1333 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001334 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001335 return true;
1336}
1337
1338/// Update LVal to refer to the given field, which must be a member of the type
1339/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001341 const FieldDecl *FD,
1342 const ASTRecordLayout *RL = 0) {
1343 if (!RL)
1344 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1345
1346 unsigned I = FD->getFieldIndex();
1347 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001348 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001349}
1350
Richard Smithd9b02e72012-01-25 22:15:11 +00001351/// Update LVal to refer to the given indirect field.
1352static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1353 LValue &LVal,
1354 const IndirectFieldDecl *IFD) {
1355 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356 CE = IFD->chain_end(); C != CE; ++C)
1357 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1358}
1359
Richard Smith180f4792011-11-10 06:34:14 +00001360/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001361static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1362 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001363 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1364 // extension.
1365 if (Type->isVoidType() || Type->isFunctionType()) {
1366 Size = CharUnits::One();
1367 return true;
1368 }
1369
1370 if (!Type->isConstantSizeType()) {
1371 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001372 // FIXME: Better diagnostic.
1373 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001374 return false;
1375 }
1376
1377 Size = Info.Ctx.getTypeSizeInChars(Type);
1378 return true;
1379}
1380
1381/// Update a pointer value to model pointer arithmetic.
1382/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001383/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001384/// \param LVal - The pointer value to be updated.
1385/// \param EltTy - The pointee type represented by LVal.
1386/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001387static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1388 LValue &LVal, QualType EltTy,
1389 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001390 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001391 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001392 return false;
1393
1394 // Compute the new offset in the appropriate width.
1395 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001396 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001397 return true;
1398}
1399
Richard Smith86024012012-02-18 22:04:06 +00001400/// Update an lvalue to refer to a component of a complex number.
1401/// \param Info - Information about the ongoing evaluation.
1402/// \param LVal - The lvalue to be updated.
1403/// \param EltTy - The complex number's component type.
1404/// \param Imag - False for the real component, true for the imaginary.
1405static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1406 LValue &LVal, QualType EltTy,
1407 bool Imag) {
1408 if (Imag) {
1409 CharUnits SizeOfComponent;
1410 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1411 return false;
1412 LVal.Offset += SizeOfComponent;
1413 }
1414 LVal.addComplex(Info, E, EltTy, Imag);
1415 return true;
1416}
1417
Richard Smith03f96112011-10-24 17:54:18 +00001418/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001419static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1420 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001421 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001422 // If this is a parameter to an active constexpr function call, perform
1423 // argument substitution.
1424 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001425 // Assume arguments of a potential constant expression are unknown
1426 // constant expressions.
1427 if (Info.CheckingPotentialConstantExpression)
1428 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001429 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001430 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001431 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001432 }
Richard Smith177dce72011-11-01 16:57:24 +00001433 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1434 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001435 }
Richard Smith03f96112011-10-24 17:54:18 +00001436
Richard Smith099e7f62011-12-19 06:19:21 +00001437 // Dig out the initializer, and use the declaration which it's attached to.
1438 const Expr *Init = VD->getAnyInitializer(VD);
1439 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001440 // If we're checking a potential constant expression, the variable could be
1441 // initialized later.
1442 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001443 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001444 return false;
1445 }
1446
Richard Smith180f4792011-11-10 06:34:14 +00001447 // If we're currently evaluating the initializer of this declaration, use that
1448 // in-flight value.
1449 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001450 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001451 return !Result.isUninit();
1452 }
1453
Richard Smith65ac5982011-11-01 21:06:14 +00001454 // Never evaluate the initializer of a weak variable. We can't be sure that
1455 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001456 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001457 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001458 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001459 }
Richard Smith65ac5982011-11-01 21:06:14 +00001460
Richard Smith099e7f62011-12-19 06:19:21 +00001461 // Check that we can fold the initializer. In C++, we will have already done
1462 // this in the cases where it matters for conformance.
1463 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1464 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001465 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001466 Notes.size() + 1) << VD;
1467 Info.Note(VD->getLocation(), diag::note_declared_at);
1468 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001469 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001470 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001471 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001472 Notes.size() + 1) << VD;
1473 Info.Note(VD->getLocation(), diag::note_declared_at);
1474 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001475 }
Richard Smith03f96112011-10-24 17:54:18 +00001476
Richard Smith1aa0be82012-03-03 22:46:17 +00001477 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001478 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001479}
1480
Richard Smithc49bd112011-10-28 17:51:58 +00001481static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001482 Qualifiers Quals = T.getQualifiers();
1483 return Quals.hasConst() && !Quals.hasVolatile();
1484}
1485
Richard Smith59efe262011-11-11 04:05:33 +00001486/// Get the base index of the given base class within an APValue representing
1487/// the given derived class.
1488static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1489 const CXXRecordDecl *Base) {
1490 Base = Base->getCanonicalDecl();
1491 unsigned Index = 0;
1492 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1493 E = Derived->bases_end(); I != E; ++I, ++Index) {
1494 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1495 return Index;
1496 }
1497
1498 llvm_unreachable("base class missing from derived class's bases list");
1499}
1500
Richard Smithf3908f22012-02-17 03:35:37 +00001501/// Extract the value of a character from a string literal.
1502static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1503 uint64_t Index) {
1504 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1505 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1506 assert(S && "unexpected string literal expression kind");
1507
1508 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1509 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1510 if (Index < S->getLength())
1511 Value = S->getCodeUnit(Index);
1512 return Value;
1513}
1514
Richard Smithcc5d4f62011-11-07 09:22:26 +00001515/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001516static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001517 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001518 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001519 if (Sub.Invalid)
1520 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001521 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001522 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001523 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001524 (unsigned)diag::note_constexpr_read_past_end :
1525 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001526 return false;
1527 }
Richard Smithf64699e2011-11-11 08:28:03 +00001528 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001530 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1531 // This object might be initialized later.
1532 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001533
Richard Smith0069b842012-03-10 00:28:11 +00001534 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001535 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001538 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001540 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001542 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001543 // Note, it should not be possible to form a pointer with a valid
1544 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001545 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001546 (unsigned)diag::note_constexpr_read_past_end :
1547 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001549 }
Richard Smithf3908f22012-02-17 03:35:37 +00001550 // An array object is represented as either an Array APValue or as an
1551 // LValue which refers to a string literal.
1552 if (O->isLValue()) {
1553 assert(I == N - 1 && "extracting subobject of character?");
1554 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001555 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001556 Info, O->getLValueBase().get<const Expr*>(), Index));
1557 return true;
1558 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001559 O = &O->getArrayInitializedElt(Index);
1560 else
1561 O = &O->getArrayFiller();
1562 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001563 } else if (ObjType->isAnyComplexType()) {
1564 // Next subobject is a complex number.
1565 uint64_t Index = Sub.Entries[I].ArrayIndex;
1566 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001567 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001568 (unsigned)diag::note_constexpr_read_past_end :
1569 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1570 return false;
1571 }
1572 assert(I == N - 1 && "extracting subobject of scalar?");
1573 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001574 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001575 : O->getComplexIntReal());
1576 } else {
1577 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001578 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001579 : O->getComplexFloatReal());
1580 }
1581 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001582 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001583 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001584 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001585 << Field;
1586 Info.Note(Field->getLocation(), diag::note_declared_at);
1587 return false;
1588 }
1589
Richard Smith180f4792011-11-10 06:34:14 +00001590 // Next subobject is a class, struct or union field.
1591 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1592 if (RD->isUnion()) {
1593 const FieldDecl *UnionField = O->getUnionField();
1594 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001595 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001596 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001597 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001598 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001599 }
Richard Smith180f4792011-11-10 06:34:14 +00001600 O = &O->getUnionValue();
1601 } else
1602 O = &O->getStructField(Field->getFieldIndex());
1603 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001604
1605 if (ObjType.isVolatileQualified()) {
1606 if (Info.getLangOpts().CPlusPlus) {
1607 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001608 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001609 << 2 << Field;
1610 Info.Note(Field->getLocation(), diag::note_declared_at);
1611 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001612 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001613 }
1614 return false;
1615 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001616 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001617 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001618 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1619 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1620 O = &O->getStructBase(getBaseIndex(Derived, Base));
1621 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 }
Richard Smith180f4792011-11-10 06:34:14 +00001623
Richard Smithf48fdb02011-12-09 22:58:01 +00001624 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001625 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001626 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001627 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001628 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001629 }
1630
Richard Smith0069b842012-03-10 00:28:11 +00001631 // This may look super-stupid, but it serves an important purpose: if we just
1632 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1633 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1634 // object, which is destroyed by Tmp's destructor.
1635 APValue Tmp;
1636 O->swap(Tmp);
1637 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001638 return true;
1639}
1640
Richard Smithf15fda02012-02-02 01:16:57 +00001641/// Find the position where two subobject designators diverge, or equivalently
1642/// the length of the common initial subsequence.
1643static unsigned FindDesignatorMismatch(QualType ObjType,
1644 const SubobjectDesignator &A,
1645 const SubobjectDesignator &B,
1646 bool &WasArrayIndex) {
1647 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1648 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001649 if (!ObjType.isNull() &&
1650 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001651 // Next subobject is an array element.
1652 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1653 WasArrayIndex = true;
1654 return I;
1655 }
Richard Smith86024012012-02-18 22:04:06 +00001656 if (ObjType->isAnyComplexType())
1657 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1658 else
1659 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001660 } else {
1661 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1662 WasArrayIndex = false;
1663 return I;
1664 }
1665 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1666 // Next subobject is a field.
1667 ObjType = FD->getType();
1668 else
1669 // Next subobject is a base class.
1670 ObjType = QualType();
1671 }
1672 }
1673 WasArrayIndex = false;
1674 return I;
1675}
1676
1677/// Determine whether the given subobject designators refer to elements of the
1678/// same array object.
1679static bool AreElementsOfSameArray(QualType ObjType,
1680 const SubobjectDesignator &A,
1681 const SubobjectDesignator &B) {
1682 if (A.Entries.size() != B.Entries.size())
1683 return false;
1684
1685 bool IsArray = A.MostDerivedArraySize != 0;
1686 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1687 // A is a subobject of the array element.
1688 return false;
1689
1690 // If A (and B) designates an array element, the last entry will be the array
1691 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1692 // of length 1' case, and the entire path must match.
1693 bool WasArrayIndex;
1694 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1695 return CommonLength >= A.Entries.size() - IsArray;
1696}
1697
Richard Smith180f4792011-11-10 06:34:14 +00001698/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1699/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1700/// for looking up the glvalue referred to by an entity of reference type.
1701///
1702/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001703/// \param Conv - The expression for which we are performing the conversion.
1704/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001705/// \param Type - The type we expect this conversion to produce, before
1706/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001707/// \param LVal - The glvalue on which we are attempting to perform this action.
1708/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001709static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1710 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001711 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001712 if (LVal.Designator.Invalid)
1713 // A diagnostic will have already been produced.
1714 return false;
1715
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001716 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001717
Richard Smithf48fdb02011-12-09 22:58:01 +00001718 if (!LVal.Base) {
1719 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001720 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001721 return false;
1722 }
1723
Richard Smith83587db2012-02-15 02:18:13 +00001724 CallStackFrame *Frame = 0;
1725 if (LVal.CallIndex) {
1726 Frame = Info.getCallFrame(LVal.CallIndex);
1727 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001728 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001729 NoteLValueLocation(Info, LVal.Base);
1730 return false;
1731 }
1732 }
1733
Richard Smith7098cbd2011-12-21 05:04:46 +00001734 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1735 // is not a constant expression (even if the object is non-volatile). We also
1736 // apply this rule to C++98, in order to conform to the expected 'volatile'
1737 // semantics.
1738 if (Type.isVolatileQualified()) {
1739 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001740 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001741 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001742 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001743 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001744 }
Richard Smithc49bd112011-10-28 17:51:58 +00001745
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001746 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001747 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1748 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001749 // expressions are constant expressions too. Inside constexpr functions,
1750 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001751 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001752 const VarDecl *VD = dyn_cast<VarDecl>(D);
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001753 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
Richard Smithf15fda02012-02-02 01:16:57 +00001754 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001755 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001756 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001757 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001758 }
1759
Richard Smith7098cbd2011-12-21 05:04:46 +00001760 // DR1313: If the object is volatile-qualified but the glvalue was not,
1761 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001762 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 if (VT.isVolatileQualified()) {
1764 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001765 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001766 Info.Note(VD->getLocation(), diag::note_declared_at);
1767 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001768 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001769 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001770 return false;
1771 }
1772
1773 if (!isa<ParmVarDecl>(VD)) {
1774 if (VD->isConstexpr()) {
1775 // OK, we can read this variable.
1776 } else if (VT->isIntegralOrEnumerationType()) {
1777 if (!VT.isConstQualified()) {
1778 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001779 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 Info.Note(VD->getLocation(), diag::note_declared_at);
1781 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001782 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001783 }
1784 return false;
1785 }
1786 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1787 // We support folding of const floating-point types, in order to make
1788 // static const data members of such types (supported as an extension)
1789 // more useful.
1790 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001791 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001792 Info.Note(VD->getLocation(), diag::note_declared_at);
1793 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001794 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001795 }
1796 } else {
1797 // FIXME: Allow folding of values of any literal type in all languages.
1798 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001804 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001806 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001807
Richard Smithf48fdb02011-12-09 22:58:01 +00001808 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001809 return false;
1810
Richard Smith47a1eed2011-10-29 20:57:55 +00001811 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001812 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001813
1814 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1815 // conversion. This happens when the declaration and the lvalue should be
1816 // considered synonymous, for instance when initializing an array of char
1817 // from a string literal. Continue as if the initializer lvalue was the
1818 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001819 assert(RVal.getLValueOffset().isZero() &&
1820 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001821 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001822
1823 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1824 Frame = Info.getCallFrame(CallIndex);
1825 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001826 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001827 NoteLValueLocation(Info, RVal.getLValueBase());
1828 return false;
1829 }
1830 } else {
1831 Frame = 0;
1832 }
Richard Smithc49bd112011-10-28 17:51:58 +00001833 }
1834
Richard Smith7098cbd2011-12-21 05:04:46 +00001835 // Volatile temporary objects cannot be read in constant expressions.
1836 if (Base->getType().isVolatileQualified()) {
1837 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001838 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001839 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1840 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001841 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001842 }
1843 return false;
1844 }
1845
Richard Smithcc5d4f62011-11-07 09:22:26 +00001846 if (Frame) {
1847 // If this is a temporary expression with a nontrivial initializer, grab the
1848 // value from the relevant stack frame.
1849 RVal = Frame->Temporaries[Base];
1850 } else if (const CompoundLiteralExpr *CLE
1851 = dyn_cast<CompoundLiteralExpr>(Base)) {
1852 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1853 // initializer until now for such expressions. Such an expression can't be
1854 // an ICE in C, so this only matters for fold.
1855 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1856 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1857 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001858 } else if (isa<StringLiteral>(Base)) {
1859 // We represent a string literal array as an lvalue pointing at the
1860 // corresponding expression, rather than building an array of chars.
1861 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001862 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001863 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001864 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001865 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001866 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001867
Richard Smithf48fdb02011-12-09 22:58:01 +00001868 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1869 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001870}
1871
Richard Smith59efe262011-11-11 04:05:33 +00001872/// Build an lvalue for the object argument of a member function call.
1873static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1874 LValue &This) {
1875 if (Object->getType()->isPointerType())
1876 return EvaluatePointer(Object, This, Info);
1877
1878 if (Object->isGLValue())
1879 return EvaluateLValue(Object, This, Info);
1880
Richard Smithe24f5fc2011-11-17 22:56:20 +00001881 if (Object->getType()->isLiteralType())
1882 return EvaluateTemporary(Object, This, Info);
1883
1884 return false;
1885}
1886
1887/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1888/// lvalue referring to the result.
1889///
1890/// \param Info - Information about the ongoing evaluation.
1891/// \param BO - The member pointer access operation.
1892/// \param LV - Filled in with a reference to the resulting object.
1893/// \param IncludeMember - Specifies whether the member itself is included in
1894/// the resulting LValue subobject designator. This is not possible when
1895/// creating a bound member function.
1896/// \return The field or method declaration to which the member pointer refers,
1897/// or 0 if evaluation fails.
1898static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1899 const BinaryOperator *BO,
1900 LValue &LV,
1901 bool IncludeMember = true) {
1902 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1903
Richard Smith745f5142012-01-27 01:14:48 +00001904 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1905 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001906 return 0;
1907
1908 MemberPtr MemPtr;
1909 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1910 return 0;
1911
1912 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1913 // member value, the behavior is undefined.
1914 if (!MemPtr.getDecl())
1915 return 0;
1916
Richard Smith745f5142012-01-27 01:14:48 +00001917 if (!EvalObjOK)
1918 return 0;
1919
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 if (MemPtr.isDerivedMember()) {
1921 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001922 // The end of the derived-to-base path for the base object must match the
1923 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001924 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001925 LV.Designator.Entries.size())
1926 return 0;
1927 unsigned PathLengthToMember =
1928 LV.Designator.Entries.size() - MemPtr.Path.size();
1929 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1930 const CXXRecordDecl *LVDecl = getAsBaseClass(
1931 LV.Designator.Entries[PathLengthToMember + I]);
1932 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1933 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1934 return 0;
1935 }
1936
1937 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1939 PathLengthToMember))
1940 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001941 } else if (!MemPtr.Path.empty()) {
1942 // Extend the LValue path with the member pointer's path.
1943 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1944 MemPtr.Path.size() + IncludeMember);
1945
1946 // Walk down to the appropriate base class.
1947 QualType LVType = BO->getLHS()->getType();
1948 if (const PointerType *PT = LVType->getAs<PointerType>())
1949 LVType = PT->getPointeeType();
1950 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1951 assert(RD && "member pointer access on non-class-type expression");
1952 // The first class in the path is that of the lvalue.
1953 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1954 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001955 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001956 RD = Base;
1957 }
1958 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001959 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001960 }
1961
1962 // Add the member. Note that we cannot build bound member functions here.
1963 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001964 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1965 HandleLValueMember(Info, BO, LV, FD);
1966 else if (const IndirectFieldDecl *IFD =
1967 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1968 HandleLValueIndirectMember(Info, BO, LV, IFD);
1969 else
1970 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001971 }
1972
1973 return MemPtr.getDecl();
1974}
1975
1976/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1977/// the provided lvalue, which currently refers to the base object.
1978static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1979 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001980 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001981 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001982 return false;
1983
Richard Smithb4e85ed2012-01-06 16:39:00 +00001984 QualType TargetQT = E->getType();
1985 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1986 TargetQT = PT->getPointeeType();
1987
1988 // Check this cast lands within the final derived-to-base subobject path.
1989 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001990 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001991 << D.MostDerivedType << TargetQT;
1992 return false;
1993 }
1994
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 // Check the type of the final cast. We don't need to check the path,
1996 // since a cast can only be formed if the path is unique.
1997 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001998 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1999 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002000 if (NewEntriesSize == D.MostDerivedPathLength)
2001 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2002 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002003 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002005 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002007 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002008 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002009
2010 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002011 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002012}
2013
Mike Stumpc4c90452009-10-27 22:09:17 +00002014namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002015enum EvalStmtResult {
2016 /// Evaluation failed.
2017 ESR_Failed,
2018 /// Hit a 'return' statement.
2019 ESR_Returned,
2020 /// Evaluation succeeded.
2021 ESR_Succeeded
2022};
2023}
2024
2025// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002026static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002027 const Stmt *S) {
2028 switch (S->getStmtClass()) {
2029 default:
2030 return ESR_Failed;
2031
2032 case Stmt::NullStmtClass:
2033 case Stmt::DeclStmtClass:
2034 return ESR_Succeeded;
2035
Richard Smithc1c5f272011-12-13 06:39:58 +00002036 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002037 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002038 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002039 return ESR_Failed;
2040 return ESR_Returned;
2041 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002042
2043 case Stmt::CompoundStmtClass: {
2044 const CompoundStmt *CS = cast<CompoundStmt>(S);
2045 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2046 BE = CS->body_end(); BI != BE; ++BI) {
2047 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2048 if (ESR != ESR_Succeeded)
2049 return ESR;
2050 }
2051 return ESR_Succeeded;
2052 }
2053 }
2054}
2055
Richard Smith61802452011-12-22 02:22:31 +00002056/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2057/// default constructor. If so, we'll fold it whether or not it's marked as
2058/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2059/// so we need special handling.
2060static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002061 const CXXConstructorDecl *CD,
2062 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002063 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2064 return false;
2065
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002066 // Value-initialization does not call a trivial default constructor, so such a
2067 // call is a core constant expression whether or not the constructor is
2068 // constexpr.
2069 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002070 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002071 // FIXME: If DiagDecl is an implicitly-declared special member function,
2072 // we should be much more explicit about why it's not constexpr.
2073 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2074 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2075 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002076 } else {
2077 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2078 }
2079 }
2080 return true;
2081}
2082
Richard Smithc1c5f272011-12-13 06:39:58 +00002083/// CheckConstexprFunction - Check that a function can be called in a constant
2084/// expression.
2085static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2086 const FunctionDecl *Declaration,
2087 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002088 // Potential constant expressions can contain calls to declared, but not yet
2089 // defined, constexpr functions.
2090 if (Info.CheckingPotentialConstantExpression && !Definition &&
2091 Declaration->isConstexpr())
2092 return false;
2093
Richard Smithc1c5f272011-12-13 06:39:58 +00002094 // Can we evaluate this function call?
2095 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2096 return true;
2097
2098 if (Info.getLangOpts().CPlusPlus0x) {
2099 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002100 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2101 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002102 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2103 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2104 << DiagDecl;
2105 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2106 } else {
2107 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2108 }
2109 return false;
2110}
2111
Richard Smith180f4792011-11-10 06:34:14 +00002112namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002113typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002114}
2115
2116/// EvaluateArgs - Evaluate the arguments to a function call.
2117static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2118 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002119 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002120 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002121 I != E; ++I) {
2122 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2123 // If we're checking for a potential constant expression, evaluate all
2124 // initializers even if some of them fail.
2125 if (!Info.keepEvaluatingAfterFailure())
2126 return false;
2127 Success = false;
2128 }
2129 }
2130 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002131}
2132
Richard Smithd0dccea2011-10-28 22:34:42 +00002133/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002134static bool HandleFunctionCall(SourceLocation CallLoc,
2135 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002136 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002137 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002138 ArgVector ArgValues(Args.size());
2139 if (!EvaluateArgs(Args, ArgValues, Info))
2140 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002141
Richard Smith745f5142012-01-27 01:14:48 +00002142 if (!Info.CheckCallLimit(CallLoc))
2143 return false;
2144
2145 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002146 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2147}
2148
Richard Smith180f4792011-11-10 06:34:14 +00002149/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002150static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002151 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002152 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002153 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002154 ArgVector ArgValues(Args.size());
2155 if (!EvaluateArgs(Args, ArgValues, Info))
2156 return false;
2157
Richard Smith745f5142012-01-27 01:14:48 +00002158 if (!Info.CheckCallLimit(CallLoc))
2159 return false;
2160
Richard Smith86c3ae42012-02-13 03:54:03 +00002161 const CXXRecordDecl *RD = Definition->getParent();
2162 if (RD->getNumVBases()) {
2163 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2164 return false;
2165 }
2166
Richard Smith745f5142012-01-27 01:14:48 +00002167 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002168
2169 // If it's a delegating constructor, just delegate.
2170 if (Definition->isDelegatingConstructor()) {
2171 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002172 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002173 }
2174
Richard Smith610a60c2012-01-10 04:32:03 +00002175 // For a trivial copy or move constructor, perform an APValue copy. This is
2176 // essential for unions, where the operations performed by the constructor
2177 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002178 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002179 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2180 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002181 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002182 RHS.setFrom(Info.Ctx, ArgValues[0]);
2183 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2184 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002185 }
2186
2187 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002188 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002189 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2190 std::distance(RD->field_begin(), RD->field_end()));
2191
2192 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2193
Richard Smith745f5142012-01-27 01:14:48 +00002194 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002195 unsigned BasesSeen = 0;
2196#ifndef NDEBUG
2197 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2198#endif
2199 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2200 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002201 LValue Subobject = This;
2202 APValue *Value = &Result;
2203
2204 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002205 if ((*I)->isBaseInitializer()) {
2206 QualType BaseType((*I)->getBaseClass(), 0);
2207#ifndef NDEBUG
2208 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002209 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002210 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2211 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2212 "base class initializers not in expected order");
2213 ++BaseIt;
2214#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002215 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002216 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002217 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002218 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002219 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002220 if (RD->isUnion()) {
2221 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002222 Value = &Result.getUnionValue();
2223 } else {
2224 Value = &Result.getStructField(FD->getFieldIndex());
2225 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002226 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002227 // Walk the indirect field decl's chain to find the object to initialize,
2228 // and make sure we've initialized every step along it.
2229 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2230 CE = IFD->chain_end();
2231 C != CE; ++C) {
2232 FieldDecl *FD = cast<FieldDecl>(*C);
2233 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2234 // Switch the union field if it differs. This happens if we had
2235 // preceding zero-initialization, and we're now initializing a union
2236 // subobject other than the first.
2237 // FIXME: In this case, the values of the other subobjects are
2238 // specified, since zero-initialization sets all padding bits to zero.
2239 if (Value->isUninit() ||
2240 (Value->isUnion() && Value->getUnionField() != FD)) {
2241 if (CD->isUnion())
2242 *Value = APValue(FD);
2243 else
2244 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2245 std::distance(CD->field_begin(), CD->field_end()));
2246 }
Richard Smith745f5142012-01-27 01:14:48 +00002247 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002248 if (CD->isUnion())
2249 Value = &Value->getUnionValue();
2250 else
2251 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002252 }
Richard Smith180f4792011-11-10 06:34:14 +00002253 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002254 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002255 }
Richard Smith745f5142012-01-27 01:14:48 +00002256
Richard Smith83587db2012-02-15 02:18:13 +00002257 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2258 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002259 ? CCEK_Constant : CCEK_MemberInit)) {
2260 // If we're checking for a potential constant expression, evaluate all
2261 // initializers even if some of them fail.
2262 if (!Info.keepEvaluatingAfterFailure())
2263 return false;
2264 Success = false;
2265 }
Richard Smith180f4792011-11-10 06:34:14 +00002266 }
2267
Richard Smith745f5142012-01-27 01:14:48 +00002268 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002269}
2270
Richard Smithd0dccea2011-10-28 22:34:42 +00002271namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002272class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002273 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002274 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002275public:
2276
Richard Smith1e12c592011-10-16 21:26:27 +00002277 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002278
2279 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002280 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002281 return true;
2282 }
2283
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002284 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2285 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002286 return Visit(E->getResultExpr());
2287 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002288 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002289 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002290 return true;
2291 return false;
2292 }
John McCallf85e1932011-06-15 23:02:42 +00002293 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002294 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002295 return true;
2296 return false;
2297 }
John McCallf85e1932011-06-15 23:02:42 +00002298
Mike Stumpc4c90452009-10-27 22:09:17 +00002299 // We don't want to evaluate BlockExprs multiple times, as they generate
2300 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002301 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2302 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2303 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002304 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2306 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2307 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2308 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2309 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2310 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002311 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002312 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002313 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002315 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002316 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2317 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2318 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2319 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002320 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002321 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2322 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2323 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2324 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2325 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002326 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002327 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002328 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002329 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002330 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002331
2332 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002334 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2335 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002337 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002338 return false;
2339 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002340
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002341 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002342};
2343
John McCall56ca35d2011-02-17 10:25:35 +00002344class OpaqueValueEvaluation {
2345 EvalInfo &info;
2346 OpaqueValueExpr *opaqueValue;
2347
2348public:
2349 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2350 Expr *value)
2351 : info(info), opaqueValue(opaqueValue) {
2352
2353 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002354 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002355 this->opaqueValue = 0;
2356 return;
2357 }
John McCall56ca35d2011-02-17 10:25:35 +00002358 }
2359
2360 bool hasError() const { return opaqueValue == 0; }
2361
2362 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002363 // FIXME: For a recursive constexpr call, an outer stack frame might have
2364 // been using this opaque value too, and will now have to re-evaluate the
2365 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002366 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2367 }
2368};
2369
Mike Stumpc4c90452009-10-27 22:09:17 +00002370} // end anonymous namespace
2371
Eli Friedman4efaa272008-11-12 09:44:48 +00002372//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002373// Generic Evaluation
2374//===----------------------------------------------------------------------===//
2375namespace {
2376
Richard Smithf48fdb02011-12-09 22:58:01 +00002377// FIXME: RetTy is always bool. Remove it.
2378template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379class ExprEvaluatorBase
2380 : public ConstStmtVisitor<Derived, RetTy> {
2381private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002382 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002383 return static_cast<Derived*>(this)->Success(V, E);
2384 }
Richard Smith51201882011-12-30 21:15:51 +00002385 RetTy DerivedZeroInitialization(const Expr *E) {
2386 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002387 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002388
Richard Smith74e1ad92012-02-16 02:46:34 +00002389 // Check whether a conditional operator with a non-constant condition is a
2390 // potential constant expression. If neither arm is a potential constant
2391 // expression, then the conditional operator is not either.
2392 template<typename ConditionalOperator>
2393 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2394 assert(Info.CheckingPotentialConstantExpression);
2395
2396 // Speculatively evaluate both arms.
2397 {
2398 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2399 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2400
2401 StmtVisitorTy::Visit(E->getFalseExpr());
2402 if (Diag.empty())
2403 return;
2404
2405 Diag.clear();
2406 StmtVisitorTy::Visit(E->getTrueExpr());
2407 if (Diag.empty())
2408 return;
2409 }
2410
2411 Error(E, diag::note_constexpr_conditional_never_const);
2412 }
2413
2414
2415 template<typename ConditionalOperator>
2416 bool HandleConditionalOperator(const ConditionalOperator *E) {
2417 bool BoolResult;
2418 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2419 if (Info.CheckingPotentialConstantExpression)
2420 CheckPotentialConstantConditional(E);
2421 return false;
2422 }
2423
2424 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2425 return StmtVisitorTy::Visit(EvalExpr);
2426 }
2427
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002428protected:
2429 EvalInfo &Info;
2430 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2431 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2432
Richard Smithdd1f29b2011-12-12 09:28:41 +00002433 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002434 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002435 }
2436
2437 /// Report an evaluation error. This should only be called when an error is
2438 /// first discovered. When propagating an error, just return false.
2439 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002440 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return false;
2442 }
2443 bool Error(const Expr *E) {
2444 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2445 }
2446
Richard Smith51201882011-12-30 21:15:51 +00002447 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002448
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449public:
2450 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2451
2452 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002453 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454 }
2455 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002456 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002457 }
2458
2459 RetTy VisitParenExpr(const ParenExpr *E)
2460 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2461 RetTy VisitUnaryExtension(const UnaryOperator *E)
2462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2463 RetTy VisitUnaryPlus(const UnaryOperator *E)
2464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2465 RetTy VisitChooseExpr(const ChooseExpr *E)
2466 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2467 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2468 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002469 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2470 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002471 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2472 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002473 // We cannot create any objects for which cleanups are required, so there is
2474 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2475 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2476 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002477
Richard Smithc216a012011-12-12 12:46:16 +00002478 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2479 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2480 return static_cast<Derived*>(this)->VisitCastExpr(E);
2481 }
2482 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2483 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2484 return static_cast<Derived*>(this)->VisitCastExpr(E);
2485 }
2486
Richard Smithe24f5fc2011-11-17 22:56:20 +00002487 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2488 switch (E->getOpcode()) {
2489 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002490 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491
2492 case BO_Comma:
2493 VisitIgnoredValue(E->getLHS());
2494 return StmtVisitorTy::Visit(E->getRHS());
2495
2496 case BO_PtrMemD:
2497 case BO_PtrMemI: {
2498 LValue Obj;
2499 if (!HandleMemberPointerAccess(Info, E, Obj))
2500 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002501 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503 return false;
2504 return DerivedSuccess(Result, E);
2505 }
2506 }
2507 }
2508
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002510 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2512 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002514
Richard Smith74e1ad92012-02-16 02:46:34 +00002515 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002516 }
2517
2518 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002519 bool IsBcpCall = false;
2520 // If the condition (ignoring parens) is a __builtin_constant_p call,
2521 // the result is a constant expression if it can be folded without
2522 // side-effects. This is an important GNU extension. See GCC PR38377
2523 // for discussion.
2524 if (const CallExpr *CallCE =
2525 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2526 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2527 IsBcpCall = true;
2528
2529 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2530 // constant expression; we can't check whether it's potentially foldable.
2531 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2532 return false;
2533
2534 FoldConstant Fold(Info);
2535
Richard Smith74e1ad92012-02-16 02:46:34 +00002536 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002537 return false;
2538
2539 if (IsBcpCall)
2540 Fold.Fold(Info);
2541
2542 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002543 }
2544
2545 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002546 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002547 if (!Value) {
2548 const Expr *Source = E->getSourceExpr();
2549 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002551 if (Source == E) { // sanity checking.
2552 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002553 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002554 }
2555 return StmtVisitorTy::Visit(Source);
2556 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002557 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002558 }
Richard Smithf10d9172011-10-11 21:43:33 +00002559
Richard Smithd0dccea2011-10-28 22:34:42 +00002560 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002561 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002562 QualType CalleeType = Callee->getType();
2563
Richard Smithd0dccea2011-10-28 22:34:42 +00002564 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002565 LValue *This = 0, ThisVal;
2566 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002567 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002568
Richard Smith59efe262011-11-11 04:05:33 +00002569 // Extract function decl and 'this' pointer from the callee.
2570 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002571 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2573 // Explicit bound member calls, such as x.f() or p->g();
2574 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002575 return false;
2576 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002577 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002578 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002579 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2580 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002581 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2582 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002583 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002584 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002585 return Error(Callee);
2586
2587 FD = dyn_cast<FunctionDecl>(Member);
2588 if (!FD)
2589 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002590 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002591 LValue Call;
2592 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002594
Richard Smithb4e85ed2012-01-06 16:39:00 +00002595 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002596 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002597 FD = dyn_cast_or_null<FunctionDecl>(
2598 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002599 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002600 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002601
2602 // Overloaded operator calls to member functions are represented as normal
2603 // calls with '*this' as the first argument.
2604 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2605 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002606 // FIXME: When selecting an implicit conversion for an overloaded
2607 // operator delete, we sometimes try to evaluate calls to conversion
2608 // operators without a 'this' parameter!
2609 if (Args.empty())
2610 return Error(E);
2611
Richard Smith59efe262011-11-11 04:05:33 +00002612 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2613 return false;
2614 This = &ThisVal;
2615 Args = Args.slice(1);
2616 }
2617
2618 // Don't call function pointers which have been cast to some other type.
2619 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002620 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002621 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002622 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002623
Richard Smithb04035a2012-02-01 02:39:43 +00002624 if (This && !This->checkSubobject(Info, E, CSK_This))
2625 return false;
2626
Richard Smith86c3ae42012-02-13 03:54:03 +00002627 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2628 // calls to such functions in constant expressions.
2629 if (This && !HasQualifier &&
2630 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2631 return Error(E, diag::note_constexpr_virtual_call);
2632
Richard Smithc1c5f272011-12-13 06:39:58 +00002633 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002634 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002635 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002636
Richard Smithc1c5f272011-12-13 06:39:58 +00002637 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002638 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2639 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 return false;
2641
Richard Smith83587db2012-02-15 02:18:13 +00002642 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002643 }
2644
Richard Smithc49bd112011-10-28 17:51:58 +00002645 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2646 return StmtVisitorTy::Visit(E->getInitializer());
2647 }
Richard Smithf10d9172011-10-11 21:43:33 +00002648 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002649 if (E->getNumInits() == 0)
2650 return DerivedZeroInitialization(E);
2651 if (E->getNumInits() == 1)
2652 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002653 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002654 }
2655 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002656 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002657 }
2658 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002659 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002660 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002661 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002662 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002663 }
Richard Smithf10d9172011-10-11 21:43:33 +00002664
Richard Smith180f4792011-11-10 06:34:14 +00002665 /// A member expression where the object is a prvalue is itself a prvalue.
2666 RetTy VisitMemberExpr(const MemberExpr *E) {
2667 assert(!E->isArrow() && "missing call to bound member function?");
2668
Richard Smith1aa0be82012-03-03 22:46:17 +00002669 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002670 if (!Evaluate(Val, Info, E->getBase()))
2671 return false;
2672
2673 QualType BaseTy = E->getBase()->getType();
2674
2675 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002676 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002677 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2678 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2679 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2680
Richard Smithb4e85ed2012-01-06 16:39:00 +00002681 SubobjectDesignator Designator(BaseTy);
2682 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002683
Richard Smithf48fdb02011-12-09 22:58:01 +00002684 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002685 DerivedSuccess(Val, E);
2686 }
2687
Richard Smithc49bd112011-10-28 17:51:58 +00002688 RetTy VisitCastExpr(const CastExpr *E) {
2689 switch (E->getCastKind()) {
2690 default:
2691 break;
2692
David Chisnall7a7ee302012-01-16 17:27:18 +00002693 case CK_AtomicToNonAtomic:
2694 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002695 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002696 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002697 return StmtVisitorTy::Visit(E->getSubExpr());
2698
2699 case CK_LValueToRValue: {
2700 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002701 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2702 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002703 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002704 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2705 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2706 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002707 return false;
2708 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002709 }
2710 }
2711
Richard Smithf48fdb02011-12-09 22:58:01 +00002712 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002713 }
2714
Richard Smith8327fad2011-10-24 18:44:57 +00002715 /// Visit a value which is evaluated, but whose value is ignored.
2716 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002717 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002718 if (!Evaluate(Scratch, Info, E))
2719 Info.EvalStatus.HasSideEffects = true;
2720 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002721};
2722
2723}
2724
2725//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002726// Common base class for lvalue and temporary evaluation.
2727//===----------------------------------------------------------------------===//
2728namespace {
2729template<class Derived>
2730class LValueExprEvaluatorBase
2731 : public ExprEvaluatorBase<Derived, bool> {
2732protected:
2733 LValue &Result;
2734 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2735 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2736
2737 bool Success(APValue::LValueBase B) {
2738 Result.set(B);
2739 return true;
2740 }
2741
2742public:
2743 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2744 ExprEvaluatorBaseTy(Info), Result(Result) {}
2745
Richard Smith1aa0be82012-03-03 22:46:17 +00002746 bool Success(const APValue &V, const Expr *E) {
2747 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 return true;
2749 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002750
Richard Smithe24f5fc2011-11-17 22:56:20 +00002751 bool VisitMemberExpr(const MemberExpr *E) {
2752 // Handle non-static data members.
2753 QualType BaseTy;
2754 if (E->isArrow()) {
2755 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2756 return false;
2757 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002758 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002759 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002760 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2761 return false;
2762 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002763 } else {
2764 if (!this->Visit(E->getBase()))
2765 return false;
2766 BaseTy = E->getBase()->getType();
2767 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002768
Richard Smithd9b02e72012-01-25 22:15:11 +00002769 const ValueDecl *MD = E->getMemberDecl();
2770 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2771 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2772 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2773 (void)BaseTy;
2774 HandleLValueMember(this->Info, E, Result, FD);
2775 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2776 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2777 } else
2778 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002779
Richard Smithd9b02e72012-01-25 22:15:11 +00002780 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002781 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002782 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002783 RefValue))
2784 return false;
2785 return Success(RefValue, E);
2786 }
2787 return true;
2788 }
2789
2790 bool VisitBinaryOperator(const BinaryOperator *E) {
2791 switch (E->getOpcode()) {
2792 default:
2793 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2794
2795 case BO_PtrMemD:
2796 case BO_PtrMemI:
2797 return HandleMemberPointerAccess(this->Info, E, Result);
2798 }
2799 }
2800
2801 bool VisitCastExpr(const CastExpr *E) {
2802 switch (E->getCastKind()) {
2803 default:
2804 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2805
2806 case CK_DerivedToBase:
2807 case CK_UncheckedDerivedToBase: {
2808 if (!this->Visit(E->getSubExpr()))
2809 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002810
2811 // Now figure out the necessary offset to add to the base LV to get from
2812 // the derived class to the base class.
2813 QualType Type = E->getSubExpr()->getType();
2814
2815 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2816 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002817 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002818 *PathI))
2819 return false;
2820 Type = (*PathI)->getType();
2821 }
2822
2823 return true;
2824 }
2825 }
2826 }
2827};
2828}
2829
2830//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002831// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002832//
2833// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2834// function designators (in C), decl references to void objects (in C), and
2835// temporaries (if building with -Wno-address-of-temporary).
2836//
2837// LValue evaluation produces values comprising a base expression of one of the
2838// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002839// - Declarations
2840// * VarDecl
2841// * FunctionDecl
2842// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * CompoundLiteralExpr in C
2844// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002845// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002846// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002847// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002848// * ObjCEncodeExpr
2849// * AddrLabelExpr
2850// * BlockExpr
2851// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002853// * Any Expr, with a CallIndex indicating the function in which the temporary
2854// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002855// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002856//===----------------------------------------------------------------------===//
2857namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002858class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002859 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002860public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002861 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2862 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002863
Richard Smithc49bd112011-10-28 17:51:58 +00002864 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2865
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitDeclRefExpr(const DeclRefExpr *E);
2867 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002868 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002869 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2870 bool VisitMemberExpr(const MemberExpr *E);
2871 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2872 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002873 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002874 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2875 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002876 bool VisitUnaryReal(const UnaryOperator *E);
2877 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002878
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002879 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002880 switch (E->getCastKind()) {
2881 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002882 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002883
Eli Friedmandb924222011-10-11 00:13:24 +00002884 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002885 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002886 if (!Visit(E->getSubExpr()))
2887 return false;
2888 Result.Designator.setInvalid();
2889 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002890
Richard Smithe24f5fc2011-11-17 22:56:20 +00002891 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002892 if (!Visit(E->getSubExpr()))
2893 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002894 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002895 }
2896 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002897};
2898} // end anonymous namespace
2899
Richard Smithc49bd112011-10-28 17:51:58 +00002900/// Evaluate an expression as an lvalue. This can be legitimately called on
2901/// expressions which are not glvalues, in a few cases:
2902/// * function designators in C,
2903/// * "extern void" objects,
2904/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002905static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002906 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2907 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2908 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002909 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002910}
2911
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002912bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002913 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2914 return Success(FD);
2915 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002916 return VisitVarDecl(E, VD);
2917 return Error(E);
2918}
Richard Smith436c8892011-10-24 23:14:33 +00002919
Richard Smithc49bd112011-10-28 17:51:58 +00002920bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002921 if (!VD->getType()->isReferenceType()) {
2922 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002923 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002924 return true;
2925 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002926 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002927 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002928
Richard Smith1aa0be82012-03-03 22:46:17 +00002929 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002930 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2931 return false;
2932 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002933}
2934
Richard Smithbd552ef2011-10-31 05:52:43 +00002935bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2936 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002937 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002938 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002939 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2940
Richard Smith83587db2012-02-15 02:18:13 +00002941 Result.set(E, Info.CurrentCall->Index);
2942 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2943 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002944 }
2945
2946 // Materialization of an lvalue temporary occurs when we need to force a copy
2947 // (for instance, if it's a bitfield).
2948 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2949 if (!Visit(E->GetTemporaryExpr()))
2950 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002951 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002952 Info.CurrentCall->Temporaries[E]))
2953 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002954 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002955 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002956}
2957
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002958bool
2959LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002960 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2961 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2962 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002963 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002964}
2965
Richard Smith47d21452011-12-27 12:18:28 +00002966bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2967 if (E->isTypeOperand())
2968 return Success(E);
2969 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2970 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002971 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002972 << E->getExprOperand()->getType()
2973 << E->getExprOperand()->getSourceRange();
2974 return false;
2975 }
2976 return Success(E);
2977}
2978
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002979bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002980 // Handle static data members.
2981 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2982 VisitIgnoredValue(E->getBase());
2983 return VisitVarDecl(E, VD);
2984 }
2985
Richard Smithd0dccea2011-10-28 22:34:42 +00002986 // Handle static member functions.
2987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2988 if (MD->isStatic()) {
2989 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002990 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002991 }
2992 }
2993
Richard Smith180f4792011-11-10 06:34:14 +00002994 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002995 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002996}
2997
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002998bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002999 // FIXME: Deal with vectors as array subscript bases.
3000 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003001 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003002
Anders Carlsson3068d112008-11-16 19:01:22 +00003003 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003004 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Anders Carlsson3068d112008-11-16 19:01:22 +00003006 APSInt Index;
3007 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003008 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003009 int64_t IndexValue
3010 = Index.isSigned() ? Index.getSExtValue()
3011 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003012
Richard Smithb4e85ed2012-01-06 16:39:00 +00003013 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003014}
Eli Friedman4efaa272008-11-12 09:44:48 +00003015
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003016bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003017 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003018}
3019
Richard Smith86024012012-02-18 22:04:06 +00003020bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3021 if (!Visit(E->getSubExpr()))
3022 return false;
3023 // __real is a no-op on scalar lvalues.
3024 if (E->getSubExpr()->getType()->isAnyComplexType())
3025 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3026 return true;
3027}
3028
3029bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3030 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3031 "lvalue __imag__ on scalar?");
3032 if (!Visit(E->getSubExpr()))
3033 return false;
3034 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3035 return true;
3036}
3037
Eli Friedman4efaa272008-11-12 09:44:48 +00003038//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003039// Pointer Evaluation
3040//===----------------------------------------------------------------------===//
3041
Anders Carlssonc754aa62008-07-08 05:13:58 +00003042namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003043class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003045 LValue &Result;
3046
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003047 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003048 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003049 return true;
3050 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003051public:
Mike Stump1eb44332009-09-09 15:08:12 +00003052
John McCallefdb83e2010-05-07 21:00:08 +00003053 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003054 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003055
Richard Smith1aa0be82012-03-03 22:46:17 +00003056 bool Success(const APValue &V, const Expr *E) {
3057 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003058 return true;
3059 }
Richard Smith51201882011-12-30 21:15:51 +00003060 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003061 return Success((Expr*)0);
3062 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003063
John McCallefdb83e2010-05-07 21:00:08 +00003064 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003065 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003066 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003067 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003068 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003069 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3070 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003071 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003072 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003073 bool VisitCallExpr(const CallExpr *E);
3074 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003075 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003076 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003077 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003078 }
Richard Smith180f4792011-11-10 06:34:14 +00003079 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3080 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003081 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003082 Result = *Info.CurrentCall->This;
3083 return true;
3084 }
John McCall56ca35d2011-02-17 10:25:35 +00003085
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003086 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003087};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003088} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003089
John McCallefdb83e2010-05-07 21:00:08 +00003090static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003091 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003092 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003093}
3094
John McCallefdb83e2010-05-07 21:00:08 +00003095bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003096 if (E->getOpcode() != BO_Add &&
3097 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003098 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003099
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003100 const Expr *PExp = E->getLHS();
3101 const Expr *IExp = E->getRHS();
3102 if (IExp->getType()->isPointerType())
3103 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003104
Richard Smith745f5142012-01-27 01:14:48 +00003105 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3106 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003107 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003108
John McCallefdb83e2010-05-07 21:00:08 +00003109 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003110 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003111 return false;
3112 int64_t AdditionalOffset
3113 = Offset.isSigned() ? Offset.getSExtValue()
3114 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003115 if (E->getOpcode() == BO_Sub)
3116 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003117
Richard Smith180f4792011-11-10 06:34:14 +00003118 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003119 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3120 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003121}
Eli Friedman4efaa272008-11-12 09:44:48 +00003122
John McCallefdb83e2010-05-07 21:00:08 +00003123bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3124 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003125}
Mike Stump1eb44332009-09-09 15:08:12 +00003126
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003127bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3128 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003129
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003130 switch (E->getCastKind()) {
3131 default:
3132 break;
3133
John McCall2de56d12010-08-25 11:45:40 +00003134 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003135 case CK_CPointerToObjCPointerCast:
3136 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003137 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003138 if (!Visit(SubExpr))
3139 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003140 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3141 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3142 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003143 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003144 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003145 if (SubExpr->getType()->isVoidPointerType())
3146 CCEDiag(E, diag::note_constexpr_invalid_cast)
3147 << 3 << SubExpr->getType();
3148 else
3149 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3150 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003151 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003152
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003153 case CK_DerivedToBase:
3154 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003155 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003156 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003157 if (!Result.Base && Result.Offset.isZero())
3158 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003159
Richard Smith180f4792011-11-10 06:34:14 +00003160 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003162 QualType Type =
3163 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003164
Richard Smith180f4792011-11-10 06:34:14 +00003165 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003167 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3168 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003169 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003170 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003171 }
3172
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003173 return true;
3174 }
3175
Richard Smithe24f5fc2011-11-17 22:56:20 +00003176 case CK_BaseToDerived:
3177 if (!Visit(E->getSubExpr()))
3178 return false;
3179 if (!Result.Base && Result.Offset.isZero())
3180 return true;
3181 return HandleBaseToDerivedCast(Info, E, Result);
3182
Richard Smith47a1eed2011-10-29 20:57:55 +00003183 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003184 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003185
John McCall2de56d12010-08-25 11:45:40 +00003186 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003187 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3188
Richard Smith1aa0be82012-03-03 22:46:17 +00003189 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003190 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003191 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003192
John McCallefdb83e2010-05-07 21:00:08 +00003193 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003194 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3195 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003196 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003197 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003198 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003199 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003200 return true;
3201 } else {
3202 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003203 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003204 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003205 }
3206 }
John McCall2de56d12010-08-25 11:45:40 +00003207 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003208 if (SubExpr->isGLValue()) {
3209 if (!EvaluateLValue(SubExpr, Result, Info))
3210 return false;
3211 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003212 Result.set(SubExpr, Info.CurrentCall->Index);
3213 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3214 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003215 return false;
3216 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003217 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003218 if (const ConstantArrayType *CAT
3219 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3220 Result.addArray(Info, E, CAT);
3221 else
3222 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003223 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003224
John McCall2de56d12010-08-25 11:45:40 +00003225 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003226 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003227 }
3228
Richard Smithc49bd112011-10-28 17:51:58 +00003229 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003230}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003231
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003232bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003233 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003234 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003235
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003236 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003237}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003238
3239//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003240// Member Pointer Evaluation
3241//===----------------------------------------------------------------------===//
3242
3243namespace {
3244class MemberPointerExprEvaluator
3245 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3246 MemberPtr &Result;
3247
3248 bool Success(const ValueDecl *D) {
3249 Result = MemberPtr(D);
3250 return true;
3251 }
3252public:
3253
3254 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3255 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3256
Richard Smith1aa0be82012-03-03 22:46:17 +00003257 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003258 Result.setFrom(V);
3259 return true;
3260 }
Richard Smith51201882011-12-30 21:15:51 +00003261 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003262 return Success((const ValueDecl*)0);
3263 }
3264
3265 bool VisitCastExpr(const CastExpr *E);
3266 bool VisitUnaryAddrOf(const UnaryOperator *E);
3267};
3268} // end anonymous namespace
3269
3270static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3271 EvalInfo &Info) {
3272 assert(E->isRValue() && E->getType()->isMemberPointerType());
3273 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3274}
3275
3276bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3277 switch (E->getCastKind()) {
3278 default:
3279 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3280
3281 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003282 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003283
3284 case CK_BaseToDerivedMemberPointer: {
3285 if (!Visit(E->getSubExpr()))
3286 return false;
3287 if (E->path_empty())
3288 return true;
3289 // Base-to-derived member pointer casts store the path in derived-to-base
3290 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3291 // the wrong end of the derived->base arc, so stagger the path by one class.
3292 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3293 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3294 PathI != PathE; ++PathI) {
3295 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3296 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3297 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003298 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003299 }
3300 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3301 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003302 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003303 return true;
3304 }
3305
3306 case CK_DerivedToBaseMemberPointer:
3307 if (!Visit(E->getSubExpr()))
3308 return false;
3309 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3310 PathE = E->path_end(); PathI != PathE; ++PathI) {
3311 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3312 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3313 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003314 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003315 }
3316 return true;
3317 }
3318}
3319
3320bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3321 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3322 // member can be formed.
3323 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3324}
3325
3326//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003327// Record Evaluation
3328//===----------------------------------------------------------------------===//
3329
3330namespace {
3331 class RecordExprEvaluator
3332 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3333 const LValue &This;
3334 APValue &Result;
3335 public:
3336
3337 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3338 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3339
Richard Smith1aa0be82012-03-03 22:46:17 +00003340 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003341 Result = V;
3342 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003343 }
Richard Smith51201882011-12-30 21:15:51 +00003344 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003345
Richard Smith59efe262011-11-11 04:05:33 +00003346 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003347 bool VisitInitListExpr(const InitListExpr *E);
3348 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3349 };
3350}
3351
Richard Smith51201882011-12-30 21:15:51 +00003352/// Perform zero-initialization on an object of non-union class type.
3353/// C++11 [dcl.init]p5:
3354/// To zero-initialize an object or reference of type T means:
3355/// [...]
3356/// -- if T is a (possibly cv-qualified) non-union class type,
3357/// each non-static data member and each base-class subobject is
3358/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003359static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3360 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003361 const LValue &This, APValue &Result) {
3362 assert(!RD->isUnion() && "Expected non-union class type");
3363 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3364 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3365 std::distance(RD->field_begin(), RD->field_end()));
3366
3367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3368
3369 if (CD) {
3370 unsigned Index = 0;
3371 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003372 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003373 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3374 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003375 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3376 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003377 Result.getStructBase(Index)))
3378 return false;
3379 }
3380 }
3381
Richard Smithb4e85ed2012-01-06 16:39:00 +00003382 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3383 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003384 // -- if T is a reference type, no initialization is performed.
3385 if ((*I)->getType()->isReferenceType())
3386 continue;
3387
3388 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003389 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003390
3391 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003392 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003393 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3394 return false;
3395 }
3396
3397 return true;
3398}
3399
3400bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3401 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3402 if (RD->isUnion()) {
3403 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3404 // object's first non-static named data member is zero-initialized
3405 RecordDecl::field_iterator I = RD->field_begin();
3406 if (I == RD->field_end()) {
3407 Result = APValue((const FieldDecl*)0);
3408 return true;
3409 }
3410
3411 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003412 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003413 Result = APValue(*I);
3414 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003415 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003416 }
3417
Richard Smithce582fe2012-02-17 00:44:16 +00003418 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003419 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003420 return false;
3421 }
3422
Richard Smithb4e85ed2012-01-06 16:39:00 +00003423 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003424}
3425
Richard Smith59efe262011-11-11 04:05:33 +00003426bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3427 switch (E->getCastKind()) {
3428 default:
3429 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3430
3431 case CK_ConstructorConversion:
3432 return Visit(E->getSubExpr());
3433
3434 case CK_DerivedToBase:
3435 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003436 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003437 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003438 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003439 if (!DerivedObject.isStruct())
3440 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003441
3442 // Derived-to-base rvalue conversion: just slice off the derived part.
3443 APValue *Value = &DerivedObject;
3444 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3445 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3446 PathE = E->path_end(); PathI != PathE; ++PathI) {
3447 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3448 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3449 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3450 RD = Base;
3451 }
3452 Result = *Value;
3453 return true;
3454 }
3455 }
3456}
3457
Richard Smith180f4792011-11-10 06:34:14 +00003458bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003459 // Cannot constant-evaluate std::initializer_list inits.
3460 if (E->initializesStdInitializerList())
3461 return false;
3462
Richard Smith180f4792011-11-10 06:34:14 +00003463 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3464 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3465
3466 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003467 const FieldDecl *Field = E->getInitializedFieldInUnion();
3468 Result = APValue(Field);
3469 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003470 return true;
Richard Smithec789162012-01-12 18:54:33 +00003471
3472 // If the initializer list for a union does not contain any elements, the
3473 // first element of the union is value-initialized.
3474 ImplicitValueInitExpr VIE(Field->getType());
3475 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3476
Richard Smith180f4792011-11-10 06:34:14 +00003477 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003478 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003479 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003480 }
3481
3482 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3483 "initializer list for class with base classes");
3484 Result = APValue(APValue::UninitStruct(), 0,
3485 std::distance(RD->field_begin(), RD->field_end()));
3486 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003487 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003488 for (RecordDecl::field_iterator Field = RD->field_begin(),
3489 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3490 // Anonymous bit-fields are not considered members of the class for
3491 // purposes of aggregate initialization.
3492 if (Field->isUnnamedBitfield())
3493 continue;
3494
3495 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003496
Richard Smith745f5142012-01-27 01:14:48 +00003497 bool HaveInit = ElementNo < E->getNumInits();
3498
3499 // FIXME: Diagnostics here should point to the end of the initializer
3500 // list, not the start.
3501 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3502 *Field, &Layout);
3503
3504 // Perform an implicit value-initialization for members beyond the end of
3505 // the initializer list.
3506 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3507
Richard Smith83587db2012-02-15 02:18:13 +00003508 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003509 Result.getStructField((*Field)->getFieldIndex()),
3510 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3511 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003512 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003513 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003514 }
3515 }
3516
Richard Smith745f5142012-01-27 01:14:48 +00003517 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003518}
3519
3520bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3521 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003522 bool ZeroInit = E->requiresZeroInitialization();
3523 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003524 // If we've already performed zero-initialization, we're already done.
3525 if (!Result.isUninit())
3526 return true;
3527
Richard Smith51201882011-12-30 21:15:51 +00003528 if (ZeroInit)
3529 return ZeroInitialization(E);
3530
Richard Smith61802452011-12-22 02:22:31 +00003531 const CXXRecordDecl *RD = FD->getParent();
3532 if (RD->isUnion())
3533 Result = APValue((FieldDecl*)0);
3534 else
3535 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3536 std::distance(RD->field_begin(), RD->field_end()));
3537 return true;
3538 }
3539
Richard Smith180f4792011-11-10 06:34:14 +00003540 const FunctionDecl *Definition = 0;
3541 FD->getBody(Definition);
3542
Richard Smithc1c5f272011-12-13 06:39:58 +00003543 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3544 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003545
Richard Smith610a60c2012-01-10 04:32:03 +00003546 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003547 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003548 if (const MaterializeTemporaryExpr *ME
3549 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3550 return Visit(ME->GetTemporaryExpr());
3551
Richard Smith51201882011-12-30 21:15:51 +00003552 if (ZeroInit && !ZeroInitialization(E))
3553 return false;
3554
Richard Smith180f4792011-11-10 06:34:14 +00003555 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003556 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003557 cast<CXXConstructorDecl>(Definition), Info,
3558 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003559}
3560
3561static bool EvaluateRecord(const Expr *E, const LValue &This,
3562 APValue &Result, EvalInfo &Info) {
3563 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003564 "can't evaluate expression as a record rvalue");
3565 return RecordExprEvaluator(Info, This, Result).Visit(E);
3566}
3567
3568//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003569// Temporary Evaluation
3570//
3571// Temporaries are represented in the AST as rvalues, but generally behave like
3572// lvalues. The full-object of which the temporary is a subobject is implicitly
3573// materialized so that a reference can bind to it.
3574//===----------------------------------------------------------------------===//
3575namespace {
3576class TemporaryExprEvaluator
3577 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3578public:
3579 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3580 LValueExprEvaluatorBaseTy(Info, Result) {}
3581
3582 /// Visit an expression which constructs the value of this temporary.
3583 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003584 Result.set(E, Info.CurrentCall->Index);
3585 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003586 }
3587
3588 bool VisitCastExpr(const CastExpr *E) {
3589 switch (E->getCastKind()) {
3590 default:
3591 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3592
3593 case CK_ConstructorConversion:
3594 return VisitConstructExpr(E->getSubExpr());
3595 }
3596 }
3597 bool VisitInitListExpr(const InitListExpr *E) {
3598 return VisitConstructExpr(E);
3599 }
3600 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3601 return VisitConstructExpr(E);
3602 }
3603 bool VisitCallExpr(const CallExpr *E) {
3604 return VisitConstructExpr(E);
3605 }
3606};
3607} // end anonymous namespace
3608
3609/// Evaluate an expression of record type as a temporary.
3610static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003611 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003612 return TemporaryExprEvaluator(Info, Result).Visit(E);
3613}
3614
3615//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003616// Vector Evaluation
3617//===----------------------------------------------------------------------===//
3618
3619namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003620 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003621 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3622 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003623 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Richard Smith07fc6572011-10-22 21:10:00 +00003625 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3626 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Richard Smith07fc6572011-10-22 21:10:00 +00003628 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3629 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3630 // FIXME: remove this APValue copy.
3631 Result = APValue(V.data(), V.size());
3632 return true;
3633 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003634 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003635 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003636 Result = V;
3637 return true;
3638 }
Richard Smith51201882011-12-30 21:15:51 +00003639 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003640
Richard Smith07fc6572011-10-22 21:10:00 +00003641 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003642 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003643 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003644 bool VisitInitListExpr(const InitListExpr *E);
3645 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003646 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003647 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003648 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003649 };
3650} // end anonymous namespace
3651
3652static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003653 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003654 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003655}
3656
Richard Smith07fc6572011-10-22 21:10:00 +00003657bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3658 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003659 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003660
Richard Smithd62ca372011-12-06 22:44:34 +00003661 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003662 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003663
Eli Friedman46a52322011-03-25 00:43:55 +00003664 switch (E->getCastKind()) {
3665 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003666 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003667 if (SETy->isIntegerType()) {
3668 APSInt IntResult;
3669 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003670 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003671 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003672 } else if (SETy->isRealFloatingType()) {
3673 APFloat F(0.0);
3674 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003675 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003676 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003677 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003678 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003679 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003680
3681 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003682 SmallVector<APValue, 4> Elts(NElts, Val);
3683 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003684 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003685 case CK_BitCast: {
3686 // Evaluate the operand into an APInt we can extract from.
3687 llvm::APInt SValInt;
3688 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3689 return false;
3690 // Extract the elements
3691 QualType EltTy = VTy->getElementType();
3692 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3693 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3694 SmallVector<APValue, 4> Elts;
3695 if (EltTy->isRealFloatingType()) {
3696 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3697 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3698 unsigned FloatEltSize = EltSize;
3699 if (&Sem == &APFloat::x87DoubleExtended)
3700 FloatEltSize = 80;
3701 for (unsigned i = 0; i < NElts; i++) {
3702 llvm::APInt Elt;
3703 if (BigEndian)
3704 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3705 else
3706 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3707 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3708 }
3709 } else if (EltTy->isIntegerType()) {
3710 for (unsigned i = 0; i < NElts; i++) {
3711 llvm::APInt Elt;
3712 if (BigEndian)
3713 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3714 else
3715 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3716 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3717 }
3718 } else {
3719 return Error(E);
3720 }
3721 return Success(Elts, E);
3722 }
Eli Friedman46a52322011-03-25 00:43:55 +00003723 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003724 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003725 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003726}
3727
Richard Smith07fc6572011-10-22 21:10:00 +00003728bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003729VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003730 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003731 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003732 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Nate Begeman59b5da62009-01-18 03:20:47 +00003734 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003735 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003736
Eli Friedman3edd5a92012-01-03 23:24:20 +00003737 // The number of initializers can be less than the number of
3738 // vector elements. For OpenCL, this can be due to nested vector
3739 // initialization. For GCC compatibility, missing trailing elements
3740 // should be initialized with zeroes.
3741 unsigned CountInits = 0, CountElts = 0;
3742 while (CountElts < NumElements) {
3743 // Handle nested vector initialization.
3744 if (CountInits < NumInits
3745 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3746 APValue v;
3747 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3748 return Error(E);
3749 unsigned vlen = v.getVectorLength();
3750 for (unsigned j = 0; j < vlen; j++)
3751 Elements.push_back(v.getVectorElt(j));
3752 CountElts += vlen;
3753 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003754 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003755 if (CountInits < NumInits) {
3756 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003757 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003758 } else // trailing integer zero.
3759 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3760 Elements.push_back(APValue(sInt));
3761 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003762 } else {
3763 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003764 if (CountInits < NumInits) {
3765 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003766 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003767 } else // trailing float zero.
3768 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3769 Elements.push_back(APValue(f));
3770 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003771 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003772 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003773 }
Richard Smith07fc6572011-10-22 21:10:00 +00003774 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003775}
3776
Richard Smith07fc6572011-10-22 21:10:00 +00003777bool
Richard Smith51201882011-12-30 21:15:51 +00003778VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003779 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003780 QualType EltTy = VT->getElementType();
3781 APValue ZeroElement;
3782 if (EltTy->isIntegerType())
3783 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3784 else
3785 ZeroElement =
3786 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3787
Chris Lattner5f9e2722011-07-23 10:55:15 +00003788 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003789 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003790}
3791
Richard Smith07fc6572011-10-22 21:10:00 +00003792bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003793 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003794 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003795}
3796
Nate Begeman59b5da62009-01-18 03:20:47 +00003797//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003798// Array Evaluation
3799//===----------------------------------------------------------------------===//
3800
3801namespace {
3802 class ArrayExprEvaluator
3803 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003804 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805 APValue &Result;
3806 public:
3807
Richard Smith180f4792011-11-10 06:34:14 +00003808 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3809 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003810
3811 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003812 assert((V.isArray() || V.isLValue()) &&
3813 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003814 Result = V;
3815 return true;
3816 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003817
Richard Smith51201882011-12-30 21:15:51 +00003818 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003819 const ConstantArrayType *CAT =
3820 Info.Ctx.getAsConstantArrayType(E->getType());
3821 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003822 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003823
3824 Result = APValue(APValue::UninitArray(), 0,
3825 CAT->getSize().getZExtValue());
3826 if (!Result.hasArrayFiller()) return true;
3827
Richard Smith51201882011-12-30 21:15:51 +00003828 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003829 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003830 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003831 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003832 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003833 }
3834
Richard Smithcc5d4f62011-11-07 09:22:26 +00003835 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003836 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003837 };
3838} // end anonymous namespace
3839
Richard Smith180f4792011-11-10 06:34:14 +00003840static bool EvaluateArray(const Expr *E, const LValue &This,
3841 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003842 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003843 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003844}
3845
3846bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3847 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3848 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003849 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003850
Richard Smith974c5f92011-12-22 01:07:19 +00003851 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3852 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003853 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003854 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3855 LValue LV;
3856 if (!EvaluateLValue(E->getInit(0), LV, Info))
3857 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003858 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003859 LV.moveInto(Val);
3860 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003861 }
3862
Richard Smith745f5142012-01-27 01:14:48 +00003863 bool Success = true;
3864
Richard Smithcc5d4f62011-11-07 09:22:26 +00003865 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3866 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003867 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003868 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003869 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003870 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003871 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003872 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3873 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003874 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3875 CAT->getElementType(), 1)) {
3876 if (!Info.keepEvaluatingAfterFailure())
3877 return false;
3878 Success = false;
3879 }
Richard Smith180f4792011-11-10 06:34:14 +00003880 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003881
Richard Smith745f5142012-01-27 01:14:48 +00003882 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003883 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003884 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3885 // but sometimes does:
3886 // struct S { constexpr S() : p(&p) {} void *p; };
3887 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003888 return EvaluateInPlace(Result.getArrayFiller(), Info,
3889 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003890}
3891
Richard Smithe24f5fc2011-11-17 22:56:20 +00003892bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3893 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3894 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003895 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003896
Richard Smithec789162012-01-12 18:54:33 +00003897 bool HadZeroInit = !Result.isUninit();
3898 if (!HadZeroInit)
3899 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003900 if (!Result.hasArrayFiller())
3901 return true;
3902
3903 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003904
Richard Smith51201882011-12-30 21:15:51 +00003905 bool ZeroInit = E->requiresZeroInitialization();
3906 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003907 if (HadZeroInit)
3908 return true;
3909
Richard Smith51201882011-12-30 21:15:51 +00003910 if (ZeroInit) {
3911 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003912 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003913 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003914 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003915 }
3916
Richard Smith61802452011-12-22 02:22:31 +00003917 const CXXRecordDecl *RD = FD->getParent();
3918 if (RD->isUnion())
3919 Result.getArrayFiller() = APValue((FieldDecl*)0);
3920 else
3921 Result.getArrayFiller() =
3922 APValue(APValue::UninitStruct(), RD->getNumBases(),
3923 std::distance(RD->field_begin(), RD->field_end()));
3924 return true;
3925 }
3926
Richard Smithe24f5fc2011-11-17 22:56:20 +00003927 const FunctionDecl *Definition = 0;
3928 FD->getBody(Definition);
3929
Richard Smithc1c5f272011-12-13 06:39:58 +00003930 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3931 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003932
3933 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3934 // but sometimes does:
3935 // struct S { constexpr S() : p(&p) {} void *p; };
3936 // S s[10];
3937 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003938 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003939
Richard Smithec789162012-01-12 18:54:33 +00003940 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003941 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003942 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003943 return false;
3944 }
3945
Richard Smithe24f5fc2011-11-17 22:56:20 +00003946 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003947 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003948 cast<CXXConstructorDecl>(Definition),
3949 Info, Result.getArrayFiller());
3950}
3951
Richard Smithcc5d4f62011-11-07 09:22:26 +00003952//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003953// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003954//
3955// As a GNU extension, we support casting pointers to sufficiently-wide integer
3956// types and back in constant folding. Integer values are thus represented
3957// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003958//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003959
3960namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003961class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003962 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003963 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003964public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003965 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003966 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003967
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003968 bool Success(const llvm::APSInt &SI, const Expr *E) {
3969 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003970 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003971 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003972 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003973 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003974 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003975 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003976 return true;
3977 }
3978
Daniel Dunbar131eb432009-02-19 09:06:44 +00003979 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003980 assert(E->getType()->isIntegralOrEnumerationType() &&
3981 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003982 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003983 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003984 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003985 Result.getInt().setIsUnsigned(
3986 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003987 return true;
3988 }
3989
3990 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003991 assert(E->getType()->isIntegralOrEnumerationType() &&
3992 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003993 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003994 return true;
3995 }
3996
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003997 bool Success(CharUnits Size, const Expr *E) {
3998 return Success(Size.getQuantity(), E);
3999 }
4000
Richard Smith1aa0be82012-03-03 22:46:17 +00004001 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004002 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004003 Result = V;
4004 return true;
4005 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004006 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004007 }
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Richard Smith51201882011-12-30 21:15:51 +00004009 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004010
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +00004011 // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4012 bool Visit(const Expr *E) {
4013 SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4014 Info.IntExprEvaluatorDepth+1);
4015 const unsigned MaxDepth = 512;
4016 if (Depth.get() > MaxDepth) {
4017 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4018 diag::err_intexpr_depth_limit_exceeded);
4019 return false;
4020 }
4021
4022 return ExprEvaluatorBaseTy::Visit(E);
4023 }
4024
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004025 //===--------------------------------------------------------------------===//
4026 // Visitor Methods
4027 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004028
Chris Lattner4c4867e2008-07-12 00:38:25 +00004029 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004030 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004031 }
4032 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004033 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004034 }
Eli Friedman04309752009-11-24 05:28:59 +00004035
4036 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4037 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004038 if (CheckReferencedDecl(E, E->getDecl()))
4039 return true;
4040
4041 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004042 }
4043 bool VisitMemberExpr(const MemberExpr *E) {
4044 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004045 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004046 return true;
4047 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004048
4049 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004050 }
4051
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004052 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004053 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004054 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004055 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004056
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004057 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004058 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004059
Anders Carlsson3068d112008-11-16 19:01:22 +00004060 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004061 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004062 }
Mike Stump1eb44332009-09-09 15:08:12 +00004063
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004064 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4065 return Success(E->getValue(), E);
4066 }
4067
Richard Smithf10d9172011-10-11 21:43:33 +00004068 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004069 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004070 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004071 }
4072
Sebastian Redl64b45f72009-01-05 20:52:13 +00004073 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004074 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004075 }
4076
Francois Pichet6ad6f282010-12-07 00:08:36 +00004077 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4078 return Success(E->getValue(), E);
4079 }
4080
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004081 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4082 return Success(E->getValue(), E);
4083 }
4084
John Wiegley21ff2e52011-04-28 00:16:57 +00004085 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4086 return Success(E->getValue(), E);
4087 }
4088
John Wiegley55262202011-04-25 06:54:41 +00004089 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4090 return Success(E->getValue(), E);
4091 }
4092
Eli Friedman722c7172009-02-28 03:59:05 +00004093 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004094 bool VisitUnaryImag(const UnaryOperator *E);
4095
Sebastian Redl295995c2010-09-10 20:55:47 +00004096 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004097 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004098
Chris Lattnerfcee0012008-07-11 21:24:13 +00004099private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004100 CharUnits GetAlignOfExpr(const Expr *E);
4101 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004102 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004103 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004104 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004105};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004106} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004107
Richard Smithc49bd112011-10-28 17:51:58 +00004108/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4109/// produce either the integer value or a pointer.
4110///
4111/// GCC has a heinous extension which folds casts between pointer types and
4112/// pointer-sized integral types. We support this by allowing the evaluation of
4113/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4114/// Some simple arithmetic on such values is supported (they are treated much
4115/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004116static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004117 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004118 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004119 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004120}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004121
Richard Smithf48fdb02011-12-09 22:58:01 +00004122static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004123 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004124 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004125 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004126 if (!Val.isInt()) {
4127 // FIXME: It would be better to produce the diagnostic for casting
4128 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004129 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004130 return false;
4131 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004132 Result = Val.getInt();
4133 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004134}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004135
Richard Smithf48fdb02011-12-09 22:58:01 +00004136/// Check whether the given declaration can be directly converted to an integral
4137/// rvalue. If not, no diagnostic is produced; there are other things we can
4138/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004139bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004140 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004141 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004142 // Check for signedness/width mismatches between E type and ECD value.
4143 bool SameSign = (ECD->getInitVal().isSigned()
4144 == E->getType()->isSignedIntegerOrEnumerationType());
4145 bool SameWidth = (ECD->getInitVal().getBitWidth()
4146 == Info.Ctx.getIntWidth(E->getType()));
4147 if (SameSign && SameWidth)
4148 return Success(ECD->getInitVal(), E);
4149 else {
4150 // Get rid of mismatch (otherwise Success assertions will fail)
4151 // by computing a new value matching the type of E.
4152 llvm::APSInt Val = ECD->getInitVal();
4153 if (!SameSign)
4154 Val.setIsSigned(!ECD->getInitVal().isSigned());
4155 if (!SameWidth)
4156 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4157 return Success(Val, E);
4158 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004159 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004160 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004161}
4162
Chris Lattnera4d55d82008-10-06 06:40:35 +00004163/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4164/// as GCC.
4165static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4166 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004167 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004168 enum gcc_type_class {
4169 no_type_class = -1,
4170 void_type_class, integer_type_class, char_type_class,
4171 enumeral_type_class, boolean_type_class,
4172 pointer_type_class, reference_type_class, offset_type_class,
4173 real_type_class, complex_type_class,
4174 function_type_class, method_type_class,
4175 record_type_class, union_type_class,
4176 array_type_class, string_type_class,
4177 lang_type_class
4178 };
Mike Stump1eb44332009-09-09 15:08:12 +00004179
4180 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004181 // ideal, however it is what gcc does.
4182 if (E->getNumArgs() == 0)
4183 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004184
Chris Lattnera4d55d82008-10-06 06:40:35 +00004185 QualType ArgTy = E->getArg(0)->getType();
4186 if (ArgTy->isVoidType())
4187 return void_type_class;
4188 else if (ArgTy->isEnumeralType())
4189 return enumeral_type_class;
4190 else if (ArgTy->isBooleanType())
4191 return boolean_type_class;
4192 else if (ArgTy->isCharType())
4193 return string_type_class; // gcc doesn't appear to use char_type_class
4194 else if (ArgTy->isIntegerType())
4195 return integer_type_class;
4196 else if (ArgTy->isPointerType())
4197 return pointer_type_class;
4198 else if (ArgTy->isReferenceType())
4199 return reference_type_class;
4200 else if (ArgTy->isRealType())
4201 return real_type_class;
4202 else if (ArgTy->isComplexType())
4203 return complex_type_class;
4204 else if (ArgTy->isFunctionType())
4205 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004206 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004207 return record_type_class;
4208 else if (ArgTy->isUnionType())
4209 return union_type_class;
4210 else if (ArgTy->isArrayType())
4211 return array_type_class;
4212 else if (ArgTy->isUnionType())
4213 return union_type_class;
4214 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004215 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004216}
4217
Richard Smith80d4b552011-12-28 19:48:30 +00004218/// EvaluateBuiltinConstantPForLValue - Determine the result of
4219/// __builtin_constant_p when applied to the given lvalue.
4220///
4221/// An lvalue is only "constant" if it is a pointer or reference to the first
4222/// character of a string literal.
4223template<typename LValue>
4224static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004225 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004226 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4227}
4228
4229/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4230/// GCC as we can manage.
4231static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4232 QualType ArgType = Arg->getType();
4233
4234 // __builtin_constant_p always has one operand. The rules which gcc follows
4235 // are not precisely documented, but are as follows:
4236 //
4237 // - If the operand is of integral, floating, complex or enumeration type,
4238 // and can be folded to a known value of that type, it returns 1.
4239 // - If the operand and can be folded to a pointer to the first character
4240 // of a string literal (or such a pointer cast to an integral type), it
4241 // returns 1.
4242 //
4243 // Otherwise, it returns 0.
4244 //
4245 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4246 // its support for this does not currently work.
4247 if (ArgType->isIntegralOrEnumerationType()) {
4248 Expr::EvalResult Result;
4249 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4250 return false;
4251
4252 APValue &V = Result.Val;
4253 if (V.getKind() == APValue::Int)
4254 return true;
4255
4256 return EvaluateBuiltinConstantPForLValue(V);
4257 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4258 return Arg->isEvaluatable(Ctx);
4259 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4260 LValue LV;
4261 Expr::EvalStatus Status;
4262 EvalInfo Info(Ctx, Status);
4263 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4264 : EvaluatePointer(Arg, LV, Info)) &&
4265 !Status.HasSideEffects)
4266 return EvaluateBuiltinConstantPForLValue(LV);
4267 }
4268
4269 // Anything else isn't considered to be sufficiently constant.
4270 return false;
4271}
4272
John McCall42c8f872010-05-10 23:27:23 +00004273/// Retrieves the "underlying object type" of the given expression,
4274/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004275QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4276 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4277 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004278 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004279 } else if (const Expr *E = B.get<const Expr*>()) {
4280 if (isa<CompoundLiteralExpr>(E))
4281 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004282 }
4283
4284 return QualType();
4285}
4286
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004287bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004288 // TODO: Perhaps we should let LLVM lower this?
4289 LValue Base;
4290 if (!EvaluatePointer(E->getArg(0), Base, Info))
4291 return false;
4292
4293 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004294 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004295
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004296 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004297 if (T.isNull() ||
4298 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004299 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004300 T->isVariablyModifiedType() ||
4301 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004302 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004303
4304 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4305 CharUnits Offset = Base.getLValueOffset();
4306
4307 if (!Offset.isNegative() && Offset <= Size)
4308 Size -= Offset;
4309 else
4310 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004311 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004312}
4313
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004314bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004315 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004316 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004317 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004318
4319 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004320 if (TryEvaluateBuiltinObjectSize(E))
4321 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004322
Eric Christopherb2aaf512010-01-19 22:58:35 +00004323 // If evaluating the argument has side-effects we can't determine
4324 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004325 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004326 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004327 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004328 return Success(0, E);
4329 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004330
Richard Smithf48fdb02011-12-09 22:58:01 +00004331 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004332 }
4333
Chris Lattner019f4e82008-10-06 05:28:25 +00004334 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004335 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004336
Richard Smith80d4b552011-12-28 19:48:30 +00004337 case Builtin::BI__builtin_constant_p:
4338 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004339
Chris Lattner21fb98e2009-09-23 06:06:36 +00004340 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004341 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004342 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004343 return Success(Operand, E);
4344 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004345
4346 case Builtin::BI__builtin_expect:
4347 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004348
Douglas Gregor5726d402010-09-10 06:27:15 +00004349 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004350 // A call to strlen is not a constant expression.
4351 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004352 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004353 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4354 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004355 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004356 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004357 case Builtin::BI__builtin_strlen:
4358 // As an extension, we support strlen() and __builtin_strlen() as constant
4359 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004360 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004361 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4362 // The string literal may have embedded null characters. Find the first
4363 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004364 StringRef Str = S->getString();
4365 StringRef::size_type Pos = Str.find(0);
4366 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004367 Str = Str.substr(0, Pos);
4368
4369 return Success(Str.size(), E);
4370 }
4371
Richard Smithf48fdb02011-12-09 22:58:01 +00004372 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004373
4374 case Builtin::BI__atomic_is_lock_free: {
4375 APSInt SizeVal;
4376 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4377 return false;
4378
4379 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4380 // of two less than the maximum inline atomic width, we know it is
4381 // lock-free. If the size isn't a power of two, or greater than the
4382 // maximum alignment where we promote atomics, we know it is not lock-free
4383 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4384 // the answer can only be determined at runtime; for example, 16-byte
4385 // atomics have lock-free implementations on some, but not all,
4386 // x86-64 processors.
4387
4388 // Check power-of-two.
4389 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4390 if (!Size.isPowerOfTwo())
4391#if 0
4392 // FIXME: Suppress this folding until the ABI for the promotion width
4393 // settles.
4394 return Success(0, E);
4395#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004396 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004397#endif
4398
4399#if 0
4400 // Check against promotion width.
4401 // FIXME: Suppress this folding until the ABI for the promotion width
4402 // settles.
4403 unsigned PromoteWidthBits =
4404 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4405 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4406 return Success(0, E);
4407#endif
4408
4409 // Check against inlining width.
4410 unsigned InlineWidthBits =
4411 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4412 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4413 return Success(1, E);
4414
Richard Smithf48fdb02011-12-09 22:58:01 +00004415 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004416 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004417 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004418}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004419
Richard Smith625b8072011-10-31 01:37:14 +00004420static bool HasSameBase(const LValue &A, const LValue &B) {
4421 if (!A.getLValueBase())
4422 return !B.getLValueBase();
4423 if (!B.getLValueBase())
4424 return false;
4425
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004426 if (A.getLValueBase().getOpaqueValue() !=
4427 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004428 const Decl *ADecl = GetLValueBaseDecl(A);
4429 if (!ADecl)
4430 return false;
4431 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004432 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004433 return false;
4434 }
4435
4436 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004437 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004438}
4439
Richard Smith7b48a292012-02-01 05:53:12 +00004440/// Perform the given integer operation, which is known to need at most BitWidth
4441/// bits, and check for overflow in the original type (if that type was not an
4442/// unsigned type).
4443template<typename Operation>
4444static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4445 const APSInt &LHS, const APSInt &RHS,
4446 unsigned BitWidth, Operation Op) {
4447 if (LHS.isUnsigned())
4448 return Op(LHS, RHS);
4449
4450 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4451 APSInt Result = Value.trunc(LHS.getBitWidth());
4452 if (Result.extend(BitWidth) != Value)
4453 HandleOverflow(Info, E, Value, E->getType());
4454 return Result;
4455}
4456
Chris Lattnerb542afe2008-07-11 19:10:17 +00004457bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004458 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004459 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004460
John McCall2de56d12010-08-25 11:45:40 +00004461 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004462 VisitIgnoredValue(E->getLHS());
4463 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004464 }
4465
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004466 if (E->isLogicalOp()) {
4467 // These need to be handled specially because the operands aren't
4468 // necessarily integral nor evaluated.
4469 bool lhsResult, rhsResult;
4470
4471 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4472 // We were able to evaluate the LHS, see if we can get away with not
4473 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4474 if (lhsResult == (E->getOpcode() == BO_LOr))
4475 return Success(lhsResult, E);
4476
4477 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4478 if (E->getOpcode() == BO_LOr)
4479 return Success(lhsResult || rhsResult, E);
4480 else
4481 return Success(lhsResult && rhsResult, E);
4482 }
4483 } else {
4484 // Since we weren't able to evaluate the left hand side, it
4485 // must have had side effects.
4486 Info.EvalStatus.HasSideEffects = true;
4487
4488 // Suppress diagnostics from this arm.
4489 SpeculativeEvaluationRAII Speculative(Info);
4490 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4491 // We can't evaluate the LHS; however, sometimes the result
4492 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4493 if (rhsResult == (E->getOpcode() == BO_LOr))
4494 return Success(rhsResult, E);
4495 }
4496 }
4497
4498 return false;
4499 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004500
Anders Carlsson286f85e2008-11-16 07:17:21 +00004501 QualType LHSTy = E->getLHS()->getType();
4502 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004503
4504 if (LHSTy->isAnyComplexType()) {
4505 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004506 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004507
Richard Smith745f5142012-01-27 01:14:48 +00004508 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4509 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004510 return false;
4511
Richard Smith745f5142012-01-27 01:14:48 +00004512 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004513 return false;
4514
4515 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004516 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004517 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004518 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004519 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4520
John McCall2de56d12010-08-25 11:45:40 +00004521 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004522 return Success((CR_r == APFloat::cmpEqual &&
4523 CR_i == APFloat::cmpEqual), E);
4524 else {
John McCall2de56d12010-08-25 11:45:40 +00004525 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004526 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004527 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004528 CR_r == APFloat::cmpLessThan ||
4529 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004530 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004531 CR_i == APFloat::cmpLessThan ||
4532 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004533 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004534 } else {
John McCall2de56d12010-08-25 11:45:40 +00004535 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004536 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4537 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4538 else {
John McCall2de56d12010-08-25 11:45:40 +00004539 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004540 "Invalid compex comparison.");
4541 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4542 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4543 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004544 }
4545 }
Mike Stump1eb44332009-09-09 15:08:12 +00004546
Anders Carlsson286f85e2008-11-16 07:17:21 +00004547 if (LHSTy->isRealFloatingType() &&
4548 RHSTy->isRealFloatingType()) {
4549 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004550
Richard Smith745f5142012-01-27 01:14:48 +00004551 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4552 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004553 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004554
Richard Smith745f5142012-01-27 01:14:48 +00004555 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004556 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004557
Anders Carlsson286f85e2008-11-16 07:17:21 +00004558 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004559
Anders Carlsson286f85e2008-11-16 07:17:21 +00004560 switch (E->getOpcode()) {
4561 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004562 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004563 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004564 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004565 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004566 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004567 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004568 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004569 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004570 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004571 E);
John McCall2de56d12010-08-25 11:45:40 +00004572 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004573 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004574 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004575 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004576 || CR == APFloat::cmpLessThan
4577 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004578 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004579 }
Mike Stump1eb44332009-09-09 15:08:12 +00004580
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004581 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004582 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004583 LValue LHSValue, RHSValue;
4584
4585 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4586 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004587 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004588
Richard Smith745f5142012-01-27 01:14:48 +00004589 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004590 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004591
Richard Smith625b8072011-10-31 01:37:14 +00004592 // Reject differing bases from the normal codepath; we special-case
4593 // comparisons to null.
4594 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004595 if (E->getOpcode() == BO_Sub) {
4596 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004597 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4598 return false;
4599 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4600 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4601 if (!LHSExpr || !RHSExpr)
4602 return false;
4603 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4604 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4605 if (!LHSAddrExpr || !RHSAddrExpr)
4606 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004607 // Make sure both labels come from the same function.
4608 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4609 RHSAddrExpr->getLabel()->getDeclContext())
4610 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004611 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004612 return true;
4613 }
Richard Smith9e36b532011-10-31 05:11:32 +00004614 // Inequalities and subtractions between unrelated pointers have
4615 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004616 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004617 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004618 // A constant address may compare equal to the address of a symbol.
4619 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004620 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004621 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4622 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004623 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004624 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004625 // distinct addresses. In clang, the result of such a comparison is
4626 // unspecified, so it is not a constant expression. However, we do know
4627 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004628 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4629 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004630 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004631 // We can't tell whether weak symbols will end up pointing to the same
4632 // object.
4633 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004634 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004635 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004636 // (Note that clang defaults to -fmerge-all-constants, which can
4637 // lead to inconsistent results for comparisons involving the address
4638 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004639 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004640 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004641
Richard Smith15efc4d2012-02-01 08:10:20 +00004642 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4643 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4644
Richard Smithf15fda02012-02-02 01:16:57 +00004645 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4646 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4647
John McCall2de56d12010-08-25 11:45:40 +00004648 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004649 // C++11 [expr.add]p6:
4650 // Unless both pointers point to elements of the same array object, or
4651 // one past the last element of the array object, the behavior is
4652 // undefined.
4653 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4654 !AreElementsOfSameArray(getType(LHSValue.Base),
4655 LHSDesignator, RHSDesignator))
4656 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4657
Chris Lattner4992bdd2010-04-20 17:13:14 +00004658 QualType Type = E->getLHS()->getType();
4659 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004660
Richard Smith180f4792011-11-10 06:34:14 +00004661 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004662 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004663 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004664
Richard Smith15efc4d2012-02-01 08:10:20 +00004665 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4666 // and produce incorrect results when it overflows. Such behavior
4667 // appears to be non-conforming, but is common, so perhaps we should
4668 // assume the standard intended for such cases to be undefined behavior
4669 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004670
Richard Smith15efc4d2012-02-01 08:10:20 +00004671 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4672 // overflow in the final conversion to ptrdiff_t.
4673 APSInt LHS(
4674 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4675 APSInt RHS(
4676 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4677 APSInt ElemSize(
4678 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4679 APSInt TrueResult = (LHS - RHS) / ElemSize;
4680 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4681
4682 if (Result.extend(65) != TrueResult)
4683 HandleOverflow(Info, E, TrueResult, E->getType());
4684 return Success(Result, E);
4685 }
Richard Smith82f28582012-01-31 06:41:30 +00004686
4687 // C++11 [expr.rel]p3:
4688 // Pointers to void (after pointer conversions) can be compared, with a
4689 // result defined as follows: If both pointers represent the same
4690 // address or are both the null pointer value, the result is true if the
4691 // operator is <= or >= and false otherwise; otherwise the result is
4692 // unspecified.
4693 // We interpret this as applying to pointers to *cv* void.
4694 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004695 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004696 CCEDiag(E, diag::note_constexpr_void_comparison);
4697
Richard Smithf15fda02012-02-02 01:16:57 +00004698 // C++11 [expr.rel]p2:
4699 // - If two pointers point to non-static data members of the same object,
4700 // or to subobjects or array elements fo such members, recursively, the
4701 // pointer to the later declared member compares greater provided the
4702 // two members have the same access control and provided their class is
4703 // not a union.
4704 // [...]
4705 // - Otherwise pointer comparisons are unspecified.
4706 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4707 E->isRelationalOp()) {
4708 bool WasArrayIndex;
4709 unsigned Mismatch =
4710 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4711 RHSDesignator, WasArrayIndex);
4712 // At the point where the designators diverge, the comparison has a
4713 // specified value if:
4714 // - we are comparing array indices
4715 // - we are comparing fields of a union, or fields with the same access
4716 // Otherwise, the result is unspecified and thus the comparison is not a
4717 // constant expression.
4718 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4719 Mismatch < RHSDesignator.Entries.size()) {
4720 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4721 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4722 if (!LF && !RF)
4723 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4724 else if (!LF)
4725 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4726 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4727 << RF->getParent() << RF;
4728 else if (!RF)
4729 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4730 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4731 << LF->getParent() << LF;
4732 else if (!LF->getParent()->isUnion() &&
4733 LF->getAccess() != RF->getAccess())
4734 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4735 << LF << LF->getAccess() << RF << RF->getAccess()
4736 << LF->getParent();
4737 }
4738 }
4739
Richard Smith625b8072011-10-31 01:37:14 +00004740 switch (E->getOpcode()) {
4741 default: llvm_unreachable("missing comparison operator");
4742 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4743 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4744 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4745 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4746 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4747 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004748 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004749 }
4750 }
Richard Smithb02e4622012-02-01 01:42:44 +00004751
4752 if (LHSTy->isMemberPointerType()) {
4753 assert(E->isEqualityOp() && "unexpected member pointer operation");
4754 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4755
4756 MemberPtr LHSValue, RHSValue;
4757
4758 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4759 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4760 return false;
4761
4762 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4763 return false;
4764
4765 // C++11 [expr.eq]p2:
4766 // If both operands are null, they compare equal. Otherwise if only one is
4767 // null, they compare unequal.
4768 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4769 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4770 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4771 }
4772
4773 // Otherwise if either is a pointer to a virtual member function, the
4774 // result is unspecified.
4775 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4776 if (MD->isVirtual())
4777 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4778 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4779 if (MD->isVirtual())
4780 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4781
4782 // Otherwise they compare equal if and only if they would refer to the
4783 // same member of the same most derived object or the same subobject if
4784 // they were dereferenced with a hypothetical object of the associated
4785 // class type.
4786 bool Equal = LHSValue == RHSValue;
4787 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4788 }
4789
Richard Smith26f2cac2012-02-14 22:35:28 +00004790 if (LHSTy->isNullPtrType()) {
4791 assert(E->isComparisonOp() && "unexpected nullptr operation");
4792 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4793 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4794 // are compared, the result is true of the operator is <=, >= or ==, and
4795 // false otherwise.
4796 BinaryOperator::Opcode Opcode = E->getOpcode();
4797 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4798 }
4799
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004800 if (!LHSTy->isIntegralOrEnumerationType() ||
4801 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004802 // We can't continue from here for non-integral types.
4803 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004804 }
4805
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004806 // The LHS of a constant expr is always evaluated and needed.
Richard Smith1aa0be82012-03-03 22:46:17 +00004807 APValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004808
4809 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4810 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004811 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004812
Richard Smith745f5142012-01-27 01:14:48 +00004813 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004814 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004815
Richard Smith1aa0be82012-03-03 22:46:17 +00004816 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004817
4818 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004819 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004820 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4821 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004822 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004823 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004824 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004825 LHSVal.getLValueOffset() -= AdditionalOffset;
4826 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004827 return true;
4828 }
4829
4830 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004831 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004832 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004833 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4834 LHSVal.getInt().getZExtValue());
4835 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004836 return true;
4837 }
4838
Eli Friedman65639282012-01-04 23:13:47 +00004839 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4840 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004841 if (!LHSVal.getLValueOffset().isZero() ||
4842 !RHSVal.getLValueOffset().isZero())
4843 return false;
4844 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4845 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4846 if (!LHSExpr || !RHSExpr)
4847 return false;
4848 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4849 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4850 if (!LHSAddrExpr || !RHSAddrExpr)
4851 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004852 // Make sure both labels come from the same function.
4853 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4854 RHSAddrExpr->getLabel()->getDeclContext())
4855 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004856 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004857 return true;
4858 }
4859
Eli Friedman42edd0d2009-03-24 01:14:50 +00004860 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004861 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004862 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004863
Richard Smithc49bd112011-10-28 17:51:58 +00004864 APSInt &LHS = LHSVal.getInt();
4865 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004866
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004867 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004868 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004869 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004870 case BO_Mul:
4871 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4872 LHS.getBitWidth() * 2,
4873 std::multiplies<APSInt>()), E);
4874 case BO_Add:
4875 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4876 LHS.getBitWidth() + 1,
4877 std::plus<APSInt>()), E);
4878 case BO_Sub:
4879 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4880 LHS.getBitWidth() + 1,
4881 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004882 case BO_And: return Success(LHS & RHS, E);
4883 case BO_Xor: return Success(LHS ^ RHS, E);
4884 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004885 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004886 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004887 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004888 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004889 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4890 // actually undefined behavior in C++11 due to a language defect.
4891 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4892 LHS.isSigned() && LHS.isMinSignedValue())
4893 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4894 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004895 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004896 // During constant-folding, a negative shift is an opposite shift. Such a
4897 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004898 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004899 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004900 RHS = -RHS;
4901 goto shift_right;
4902 }
4903
4904 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004905 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4906 // shifted type.
4907 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4908 if (SA != RHS) {
4909 CCEDiag(E, diag::note_constexpr_large_shift)
4910 << RHS << E->getType() << LHS.getBitWidth();
4911 } else if (LHS.isSigned()) {
4912 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004913 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004914 if (LHS.isNegative())
4915 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004916 else if (LHS.countLeadingZeros() < SA)
4917 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004918 }
4919
Richard Smithc49bd112011-10-28 17:51:58 +00004920 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004921 }
John McCall2de56d12010-08-25 11:45:40 +00004922 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004923 // During constant-folding, a negative shift is an opposite shift. Such a
4924 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004925 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004926 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004927 RHS = -RHS;
4928 goto shift_left;
4929 }
4930
4931 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004932 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4933 // shifted type.
4934 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4935 if (SA != RHS)
4936 CCEDiag(E, diag::note_constexpr_large_shift)
4937 << RHS << E->getType() << LHS.getBitWidth();
4938
Richard Smithc49bd112011-10-28 17:51:58 +00004939 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Richard Smithc49bd112011-10-28 17:51:58 +00004942 case BO_LT: return Success(LHS < RHS, E);
4943 case BO_GT: return Success(LHS > RHS, E);
4944 case BO_LE: return Success(LHS <= RHS, E);
4945 case BO_GE: return Success(LHS >= RHS, E);
4946 case BO_EQ: return Success(LHS == RHS, E);
4947 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004948 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004949}
4950
Ken Dyck8b752f12010-01-27 17:10:57 +00004951CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004952 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4953 // result shall be the alignment of the referenced type."
4954 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4955 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004956
4957 // __alignof is defined to return the preferred alignment.
4958 return Info.Ctx.toCharUnitsFromBits(
4959 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004960}
4961
Ken Dyck8b752f12010-01-27 17:10:57 +00004962CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004963 E = E->IgnoreParens();
4964
4965 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004966 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004968 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4969 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004970
Chris Lattneraf707ab2009-01-24 21:53:27 +00004971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004972 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4973 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004974
Chris Lattnere9feb472009-01-24 21:09:06 +00004975 return GetAlignOfType(E->getType());
4976}
4977
4978
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004979/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4980/// a result as the expression's type.
4981bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4982 const UnaryExprOrTypeTraitExpr *E) {
4983 switch(E->getKind()) {
4984 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004985 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004986 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004987 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004988 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004989 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004990
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004991 case UETT_VecStep: {
4992 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004993
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004994 if (Ty->isVectorType()) {
4995 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004996
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004997 // The vec_step built-in functions that take a 3-component
4998 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4999 if (n == 3)
5000 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005001
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005002 return Success(n, E);
5003 } else
5004 return Success(1, E);
5005 }
5006
5007 case UETT_SizeOf: {
5008 QualType SrcTy = E->getTypeOfArgument();
5009 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5010 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005011 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5012 SrcTy = Ref->getPointeeType();
5013
Richard Smith180f4792011-11-10 06:34:14 +00005014 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005015 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005016 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005017 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005018 }
5019 }
5020
5021 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005022}
5023
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005024bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005025 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005026 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005027 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005028 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005029 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005030 for (unsigned i = 0; i != n; ++i) {
5031 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5032 switch (ON.getKind()) {
5033 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005034 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005035 APSInt IdxResult;
5036 if (!EvaluateInteger(Idx, IdxResult, Info))
5037 return false;
5038 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5039 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005040 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005041 CurrentType = AT->getElementType();
5042 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5043 Result += IdxResult.getSExtValue() * ElementSize;
5044 break;
5045 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005046
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005047 case OffsetOfExpr::OffsetOfNode::Field: {
5048 FieldDecl *MemberDecl = ON.getField();
5049 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005050 if (!RT)
5051 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005052 RecordDecl *RD = RT->getDecl();
5053 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005054 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005055 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005056 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005057 CurrentType = MemberDecl->getType().getNonReferenceType();
5058 break;
5059 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005060
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005061 case OffsetOfExpr::OffsetOfNode::Identifier:
5062 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005063
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005064 case OffsetOfExpr::OffsetOfNode::Base: {
5065 CXXBaseSpecifier *BaseSpec = ON.getBase();
5066 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005067 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005068
5069 // Find the layout of the class whose base we are looking into.
5070 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005071 if (!RT)
5072 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005073 RecordDecl *RD = RT->getDecl();
5074 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5075
5076 // Find the base class itself.
5077 CurrentType = BaseSpec->getType();
5078 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5079 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005080 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005081
5082 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005083 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005084 break;
5085 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005086 }
5087 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005088 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005089}
5090
Chris Lattnerb542afe2008-07-11 19:10:17 +00005091bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005092 switch (E->getOpcode()) {
5093 default:
5094 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5095 // See C99 6.6p3.
5096 return Error(E);
5097 case UO_Extension:
5098 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5099 // If so, we could clear the diagnostic ID.
5100 return Visit(E->getSubExpr());
5101 case UO_Plus:
5102 // The result is just the value.
5103 return Visit(E->getSubExpr());
5104 case UO_Minus: {
5105 if (!Visit(E->getSubExpr()))
5106 return false;
5107 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005108 const APSInt &Value = Result.getInt();
5109 if (Value.isSigned() && Value.isMinSignedValue())
5110 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5111 E->getType());
5112 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005113 }
5114 case UO_Not: {
5115 if (!Visit(E->getSubExpr()))
5116 return false;
5117 if (!Result.isInt()) return Error(E);
5118 return Success(~Result.getInt(), E);
5119 }
5120 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005121 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005122 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005123 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005124 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005125 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005126 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005127}
Mike Stump1eb44332009-09-09 15:08:12 +00005128
Chris Lattner732b2232008-07-12 01:15:53 +00005129/// HandleCast - This is used to evaluate implicit or explicit casts where the
5130/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005131bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5132 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005133 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005134 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005135
Eli Friedman46a52322011-03-25 00:43:55 +00005136 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005137 case CK_BaseToDerived:
5138 case CK_DerivedToBase:
5139 case CK_UncheckedDerivedToBase:
5140 case CK_Dynamic:
5141 case CK_ToUnion:
5142 case CK_ArrayToPointerDecay:
5143 case CK_FunctionToPointerDecay:
5144 case CK_NullToPointer:
5145 case CK_NullToMemberPointer:
5146 case CK_BaseToDerivedMemberPointer:
5147 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005148 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005149 case CK_ConstructorConversion:
5150 case CK_IntegralToPointer:
5151 case CK_ToVoid:
5152 case CK_VectorSplat:
5153 case CK_IntegralToFloating:
5154 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005155 case CK_CPointerToObjCPointerCast:
5156 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005157 case CK_AnyPointerToBlockPointerCast:
5158 case CK_ObjCObjectLValueCast:
5159 case CK_FloatingRealToComplex:
5160 case CK_FloatingComplexToReal:
5161 case CK_FloatingComplexCast:
5162 case CK_FloatingComplexToIntegralComplex:
5163 case CK_IntegralRealToComplex:
5164 case CK_IntegralComplexCast:
5165 case CK_IntegralComplexToFloatingComplex:
5166 llvm_unreachable("invalid cast kind for integral value");
5167
Eli Friedmane50c2972011-03-25 19:07:11 +00005168 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005169 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005170 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005171 case CK_ARCProduceObject:
5172 case CK_ARCConsumeObject:
5173 case CK_ARCReclaimReturnedObject:
5174 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005175 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005176 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005177
Richard Smith7d580a42012-01-17 21:17:26 +00005178 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005179 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005180 case CK_AtomicToNonAtomic:
5181 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005182 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005183 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005184
5185 case CK_MemberPointerToBoolean:
5186 case CK_PointerToBoolean:
5187 case CK_IntegralToBoolean:
5188 case CK_FloatingToBoolean:
5189 case CK_FloatingComplexToBoolean:
5190 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005191 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005192 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005193 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005194 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005195 }
5196
Eli Friedman46a52322011-03-25 00:43:55 +00005197 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005198 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005199 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005200
Eli Friedmanbe265702009-02-20 01:15:07 +00005201 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005202 // Allow casts of address-of-label differences if they are no-ops
5203 // or narrowing. (The narrowing case isn't actually guaranteed to
5204 // be constant-evaluatable except in some narrow cases which are hard
5205 // to detect here. We let it through on the assumption the user knows
5206 // what they are doing.)
5207 if (Result.isAddrLabelDiff())
5208 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005209 // Only allow casts of lvalues if they are lossless.
5210 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5211 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005212
Richard Smithf72fccf2012-01-30 22:27:01 +00005213 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5214 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005215 }
Mike Stump1eb44332009-09-09 15:08:12 +00005216
Eli Friedman46a52322011-03-25 00:43:55 +00005217 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005218 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5219
John McCallefdb83e2010-05-07 21:00:08 +00005220 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005221 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005222 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005223
Daniel Dunbardd211642009-02-19 22:24:01 +00005224 if (LV.getLValueBase()) {
5225 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005226 // FIXME: Allow a larger integer size than the pointer size, and allow
5227 // narrowing back down to pointer width in subsequent integral casts.
5228 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005229 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005230 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005231
Richard Smithb755a9d2011-11-16 07:18:12 +00005232 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005233 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005234 return true;
5235 }
5236
Ken Dycka7305832010-01-15 12:37:54 +00005237 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5238 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005239 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005240 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005241
Eli Friedman46a52322011-03-25 00:43:55 +00005242 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005243 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005244 if (!EvaluateComplex(SubExpr, C, Info))
5245 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005246 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005247 }
Eli Friedman2217c872009-02-22 11:46:18 +00005248
Eli Friedman46a52322011-03-25 00:43:55 +00005249 case CK_FloatingToIntegral: {
5250 APFloat F(0.0);
5251 if (!EvaluateFloat(SubExpr, F, Info))
5252 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005253
Richard Smithc1c5f272011-12-13 06:39:58 +00005254 APSInt Value;
5255 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5256 return false;
5257 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005258 }
5259 }
Mike Stump1eb44332009-09-09 15:08:12 +00005260
Eli Friedman46a52322011-03-25 00:43:55 +00005261 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005262}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005263
Eli Friedman722c7172009-02-28 03:59:05 +00005264bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5265 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005266 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005267 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5268 return false;
5269 if (!LV.isComplexInt())
5270 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005271 return Success(LV.getComplexIntReal(), E);
5272 }
5273
5274 return Visit(E->getSubExpr());
5275}
5276
Eli Friedman664a1042009-02-27 04:45:43 +00005277bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005278 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005279 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005280 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5281 return false;
5282 if (!LV.isComplexInt())
5283 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005284 return Success(LV.getComplexIntImag(), E);
5285 }
5286
Richard Smith8327fad2011-10-24 18:44:57 +00005287 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005288 return Success(0, E);
5289}
5290
Douglas Gregoree8aff02011-01-04 17:33:58 +00005291bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5292 return Success(E->getPackLength(), E);
5293}
5294
Sebastian Redl295995c2010-09-10 20:55:47 +00005295bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5296 return Success(E->getValue(), E);
5297}
5298
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005299//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005300// Float Evaluation
5301//===----------------------------------------------------------------------===//
5302
5303namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005304class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005305 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005306 APFloat &Result;
5307public:
5308 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005309 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005310
Richard Smith1aa0be82012-03-03 22:46:17 +00005311 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005312 Result = V.getFloat();
5313 return true;
5314 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005315
Richard Smith51201882011-12-30 21:15:51 +00005316 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005317 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5318 return true;
5319 }
5320
Chris Lattner019f4e82008-10-06 05:28:25 +00005321 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005322
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005323 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005324 bool VisitBinaryOperator(const BinaryOperator *E);
5325 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005326 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005327
John McCallabd3a852010-05-07 22:08:54 +00005328 bool VisitUnaryReal(const UnaryOperator *E);
5329 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005330
Richard Smith51201882011-12-30 21:15:51 +00005331 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005332};
5333} // end anonymous namespace
5334
5335static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005336 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005337 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005338}
5339
Jay Foad4ba2a172011-01-12 09:06:06 +00005340static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005341 QualType ResultTy,
5342 const Expr *Arg,
5343 bool SNaN,
5344 llvm::APFloat &Result) {
5345 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5346 if (!S) return false;
5347
5348 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5349
5350 llvm::APInt fill;
5351
5352 // Treat empty strings as if they were zero.
5353 if (S->getString().empty())
5354 fill = llvm::APInt(32, 0);
5355 else if (S->getString().getAsInteger(0, fill))
5356 return false;
5357
5358 if (SNaN)
5359 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5360 else
5361 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5362 return true;
5363}
5364
Chris Lattner019f4e82008-10-06 05:28:25 +00005365bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005366 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005367 default:
5368 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5369
Chris Lattner019f4e82008-10-06 05:28:25 +00005370 case Builtin::BI__builtin_huge_val:
5371 case Builtin::BI__builtin_huge_valf:
5372 case Builtin::BI__builtin_huge_vall:
5373 case Builtin::BI__builtin_inf:
5374 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005375 case Builtin::BI__builtin_infl: {
5376 const llvm::fltSemantics &Sem =
5377 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005378 Result = llvm::APFloat::getInf(Sem);
5379 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005380 }
Mike Stump1eb44332009-09-09 15:08:12 +00005381
John McCalldb7b72a2010-02-28 13:00:19 +00005382 case Builtin::BI__builtin_nans:
5383 case Builtin::BI__builtin_nansf:
5384 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005385 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5386 true, Result))
5387 return Error(E);
5388 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005389
Chris Lattner9e621712008-10-06 06:31:58 +00005390 case Builtin::BI__builtin_nan:
5391 case Builtin::BI__builtin_nanf:
5392 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005393 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005394 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005395 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5396 false, Result))
5397 return Error(E);
5398 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005399
5400 case Builtin::BI__builtin_fabs:
5401 case Builtin::BI__builtin_fabsf:
5402 case Builtin::BI__builtin_fabsl:
5403 if (!EvaluateFloat(E->getArg(0), Result, Info))
5404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005405
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005406 if (Result.isNegative())
5407 Result.changeSign();
5408 return true;
5409
Mike Stump1eb44332009-09-09 15:08:12 +00005410 case Builtin::BI__builtin_copysign:
5411 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005412 case Builtin::BI__builtin_copysignl: {
5413 APFloat RHS(0.);
5414 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5415 !EvaluateFloat(E->getArg(1), RHS, Info))
5416 return false;
5417 Result.copySign(RHS);
5418 return true;
5419 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005420 }
5421}
5422
John McCallabd3a852010-05-07 22:08:54 +00005423bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005424 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5425 ComplexValue CV;
5426 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5427 return false;
5428 Result = CV.FloatReal;
5429 return true;
5430 }
5431
5432 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005433}
5434
5435bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005436 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5437 ComplexValue CV;
5438 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5439 return false;
5440 Result = CV.FloatImag;
5441 return true;
5442 }
5443
Richard Smith8327fad2011-10-24 18:44:57 +00005444 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005445 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5446 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005447 return true;
5448}
5449
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005450bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005451 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005452 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005453 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005454 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005455 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005456 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5457 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005458 Result.changeSign();
5459 return true;
5460 }
5461}
Chris Lattner019f4e82008-10-06 05:28:25 +00005462
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005463bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005464 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5465 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005466
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005467 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005468 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5469 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005470 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005471 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005472 return false;
5473
5474 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005475 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005476 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005477 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005478 break;
John McCall2de56d12010-08-25 11:45:40 +00005479 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005480 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005481 break;
John McCall2de56d12010-08-25 11:45:40 +00005482 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005483 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005484 break;
John McCall2de56d12010-08-25 11:45:40 +00005485 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005486 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005487 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005488 }
Richard Smith7b48a292012-02-01 05:53:12 +00005489
5490 if (Result.isInfinity() || Result.isNaN())
5491 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5492 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005493}
5494
5495bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5496 Result = E->getValue();
5497 return true;
5498}
5499
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005500bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5501 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005502
Eli Friedman2a523ee2011-03-25 00:54:52 +00005503 switch (E->getCastKind()) {
5504 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005505 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005506
5507 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005508 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005509 return EvaluateInteger(SubExpr, IntResult, Info) &&
5510 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5511 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005512 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005513
5514 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005515 if (!Visit(SubExpr))
5516 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005517 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5518 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005519 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005520
Eli Friedman2a523ee2011-03-25 00:54:52 +00005521 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005522 ComplexValue V;
5523 if (!EvaluateComplex(SubExpr, V, Info))
5524 return false;
5525 Result = V.getComplexFloatReal();
5526 return true;
5527 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005528 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005529}
5530
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005531//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005532// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005533//===----------------------------------------------------------------------===//
5534
5535namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005536class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005537 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005538 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005539
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005540public:
John McCallf4cf1a12010-05-07 17:22:02 +00005541 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005542 : ExprEvaluatorBaseTy(info), Result(Result) {}
5543
Richard Smith1aa0be82012-03-03 22:46:17 +00005544 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005545 Result.setFrom(V);
5546 return true;
5547 }
Mike Stump1eb44332009-09-09 15:08:12 +00005548
Eli Friedman7ead5c72012-01-10 04:58:17 +00005549 bool ZeroInitialization(const Expr *E);
5550
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005551 //===--------------------------------------------------------------------===//
5552 // Visitor Methods
5553 //===--------------------------------------------------------------------===//
5554
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005555 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005556 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005557 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005558 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005559 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005560};
5561} // end anonymous namespace
5562
John McCallf4cf1a12010-05-07 17:22:02 +00005563static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5564 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005565 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005566 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005567}
5568
Eli Friedman7ead5c72012-01-10 04:58:17 +00005569bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005570 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005571 if (ElemTy->isRealFloatingType()) {
5572 Result.makeComplexFloat();
5573 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5574 Result.FloatReal = Zero;
5575 Result.FloatImag = Zero;
5576 } else {
5577 Result.makeComplexInt();
5578 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5579 Result.IntReal = Zero;
5580 Result.IntImag = Zero;
5581 }
5582 return true;
5583}
5584
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005585bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5586 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005587
5588 if (SubExpr->getType()->isRealFloatingType()) {
5589 Result.makeComplexFloat();
5590 APFloat &Imag = Result.FloatImag;
5591 if (!EvaluateFloat(SubExpr, Imag, Info))
5592 return false;
5593
5594 Result.FloatReal = APFloat(Imag.getSemantics());
5595 return true;
5596 } else {
5597 assert(SubExpr->getType()->isIntegerType() &&
5598 "Unexpected imaginary literal.");
5599
5600 Result.makeComplexInt();
5601 APSInt &Imag = Result.IntImag;
5602 if (!EvaluateInteger(SubExpr, Imag, Info))
5603 return false;
5604
5605 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5606 return true;
5607 }
5608}
5609
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005610bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005611
John McCall8786da72010-12-14 17:51:41 +00005612 switch (E->getCastKind()) {
5613 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005614 case CK_BaseToDerived:
5615 case CK_DerivedToBase:
5616 case CK_UncheckedDerivedToBase:
5617 case CK_Dynamic:
5618 case CK_ToUnion:
5619 case CK_ArrayToPointerDecay:
5620 case CK_FunctionToPointerDecay:
5621 case CK_NullToPointer:
5622 case CK_NullToMemberPointer:
5623 case CK_BaseToDerivedMemberPointer:
5624 case CK_DerivedToBaseMemberPointer:
5625 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005626 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005627 case CK_ConstructorConversion:
5628 case CK_IntegralToPointer:
5629 case CK_PointerToIntegral:
5630 case CK_PointerToBoolean:
5631 case CK_ToVoid:
5632 case CK_VectorSplat:
5633 case CK_IntegralCast:
5634 case CK_IntegralToBoolean:
5635 case CK_IntegralToFloating:
5636 case CK_FloatingToIntegral:
5637 case CK_FloatingToBoolean:
5638 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005639 case CK_CPointerToObjCPointerCast:
5640 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005641 case CK_AnyPointerToBlockPointerCast:
5642 case CK_ObjCObjectLValueCast:
5643 case CK_FloatingComplexToReal:
5644 case CK_FloatingComplexToBoolean:
5645 case CK_IntegralComplexToReal:
5646 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005647 case CK_ARCProduceObject:
5648 case CK_ARCConsumeObject:
5649 case CK_ARCReclaimReturnedObject:
5650 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005651 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005652 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005653
John McCall8786da72010-12-14 17:51:41 +00005654 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005655 case CK_AtomicToNonAtomic:
5656 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005657 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005658 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005659
5660 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005661 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005662 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005663 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005664
5665 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005666 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005667 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005668 return false;
5669
John McCall8786da72010-12-14 17:51:41 +00005670 Result.makeComplexFloat();
5671 Result.FloatImag = APFloat(Real.getSemantics());
5672 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005673 }
5674
John McCall8786da72010-12-14 17:51:41 +00005675 case CK_FloatingComplexCast: {
5676 if (!Visit(E->getSubExpr()))
5677 return false;
5678
5679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5680 QualType From
5681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5682
Richard Smithc1c5f272011-12-13 06:39:58 +00005683 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5684 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005685 }
5686
5687 case CK_FloatingComplexToIntegralComplex: {
5688 if (!Visit(E->getSubExpr()))
5689 return false;
5690
5691 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5692 QualType From
5693 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5694 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005695 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5696 To, Result.IntReal) &&
5697 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5698 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005699 }
5700
5701 case CK_IntegralRealToComplex: {
5702 APSInt &Real = Result.IntReal;
5703 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5704 return false;
5705
5706 Result.makeComplexInt();
5707 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5708 return true;
5709 }
5710
5711 case CK_IntegralComplexCast: {
5712 if (!Visit(E->getSubExpr()))
5713 return false;
5714
5715 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5716 QualType From
5717 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5718
Richard Smithf72fccf2012-01-30 22:27:01 +00005719 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5720 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005721 return true;
5722 }
5723
5724 case CK_IntegralComplexToFloatingComplex: {
5725 if (!Visit(E->getSubExpr()))
5726 return false;
5727
5728 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5729 QualType From
5730 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5731 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005732 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5733 To, Result.FloatReal) &&
5734 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5735 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005736 }
5737 }
5738
5739 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005740}
5741
John McCallf4cf1a12010-05-07 17:22:02 +00005742bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005743 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005744 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5745
Richard Smith745f5142012-01-27 01:14:48 +00005746 bool LHSOK = Visit(E->getLHS());
5747 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005748 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005749
John McCallf4cf1a12010-05-07 17:22:02 +00005750 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005751 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005752 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005753
Daniel Dunbar3f279872009-01-29 01:32:56 +00005754 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5755 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005756 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005757 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005758 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005759 if (Result.isComplexFloat()) {
5760 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5761 APFloat::rmNearestTiesToEven);
5762 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5763 APFloat::rmNearestTiesToEven);
5764 } else {
5765 Result.getComplexIntReal() += RHS.getComplexIntReal();
5766 Result.getComplexIntImag() += RHS.getComplexIntImag();
5767 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005768 break;
John McCall2de56d12010-08-25 11:45:40 +00005769 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005770 if (Result.isComplexFloat()) {
5771 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5772 APFloat::rmNearestTiesToEven);
5773 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5774 APFloat::rmNearestTiesToEven);
5775 } else {
5776 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5777 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5778 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005779 break;
John McCall2de56d12010-08-25 11:45:40 +00005780 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005781 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005782 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005783 APFloat &LHS_r = LHS.getComplexFloatReal();
5784 APFloat &LHS_i = LHS.getComplexFloatImag();
5785 APFloat &RHS_r = RHS.getComplexFloatReal();
5786 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005787
Daniel Dunbar3f279872009-01-29 01:32:56 +00005788 APFloat Tmp = LHS_r;
5789 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5790 Result.getComplexFloatReal() = Tmp;
5791 Tmp = LHS_i;
5792 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5793 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5794
5795 Tmp = LHS_r;
5796 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5797 Result.getComplexFloatImag() = Tmp;
5798 Tmp = LHS_i;
5799 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5800 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5801 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005802 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005803 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005804 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5805 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005806 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005807 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5808 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5809 }
5810 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005811 case BO_Div:
5812 if (Result.isComplexFloat()) {
5813 ComplexValue LHS = Result;
5814 APFloat &LHS_r = LHS.getComplexFloatReal();
5815 APFloat &LHS_i = LHS.getComplexFloatImag();
5816 APFloat &RHS_r = RHS.getComplexFloatReal();
5817 APFloat &RHS_i = RHS.getComplexFloatImag();
5818 APFloat &Res_r = Result.getComplexFloatReal();
5819 APFloat &Res_i = Result.getComplexFloatImag();
5820
5821 APFloat Den = RHS_r;
5822 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5823 APFloat Tmp = RHS_i;
5824 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5825 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5826
5827 Res_r = LHS_r;
5828 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5829 Tmp = LHS_i;
5830 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5831 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5832 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5833
5834 Res_i = LHS_i;
5835 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5836 Tmp = LHS_r;
5837 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5838 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5839 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5840 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005841 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5842 return Error(E, diag::note_expr_divide_by_zero);
5843
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005844 ComplexValue LHS = Result;
5845 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5846 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5847 Result.getComplexIntReal() =
5848 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5849 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5850 Result.getComplexIntImag() =
5851 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5852 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5853 }
5854 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005855 }
5856
John McCallf4cf1a12010-05-07 17:22:02 +00005857 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005858}
5859
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005860bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5861 // Get the operand value into 'Result'.
5862 if (!Visit(E->getSubExpr()))
5863 return false;
5864
5865 switch (E->getOpcode()) {
5866 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005867 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005868 case UO_Extension:
5869 return true;
5870 case UO_Plus:
5871 // The result is always just the subexpr.
5872 return true;
5873 case UO_Minus:
5874 if (Result.isComplexFloat()) {
5875 Result.getComplexFloatReal().changeSign();
5876 Result.getComplexFloatImag().changeSign();
5877 }
5878 else {
5879 Result.getComplexIntReal() = -Result.getComplexIntReal();
5880 Result.getComplexIntImag() = -Result.getComplexIntImag();
5881 }
5882 return true;
5883 case UO_Not:
5884 if (Result.isComplexFloat())
5885 Result.getComplexFloatImag().changeSign();
5886 else
5887 Result.getComplexIntImag() = -Result.getComplexIntImag();
5888 return true;
5889 }
5890}
5891
Eli Friedman7ead5c72012-01-10 04:58:17 +00005892bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5893 if (E->getNumInits() == 2) {
5894 if (E->getType()->isComplexType()) {
5895 Result.makeComplexFloat();
5896 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5897 return false;
5898 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5899 return false;
5900 } else {
5901 Result.makeComplexInt();
5902 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5903 return false;
5904 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5905 return false;
5906 }
5907 return true;
5908 }
5909 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5910}
5911
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005912//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005913// Void expression evaluation, primarily for a cast to void on the LHS of a
5914// comma operator
5915//===----------------------------------------------------------------------===//
5916
5917namespace {
5918class VoidExprEvaluator
5919 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5920public:
5921 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5922
Richard Smith1aa0be82012-03-03 22:46:17 +00005923 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005924
5925 bool VisitCastExpr(const CastExpr *E) {
5926 switch (E->getCastKind()) {
5927 default:
5928 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5929 case CK_ToVoid:
5930 VisitIgnoredValue(E->getSubExpr());
5931 return true;
5932 }
5933 }
5934};
5935} // end anonymous namespace
5936
5937static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5938 assert(E->isRValue() && E->getType()->isVoidType());
5939 return VoidExprEvaluator(Info).Visit(E);
5940}
5941
5942//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005943// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005944//===----------------------------------------------------------------------===//
5945
Richard Smith1aa0be82012-03-03 22:46:17 +00005946static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005947 // In C, function designators are not lvalues, but we evaluate them as if they
5948 // are.
5949 if (E->isGLValue() || E->getType()->isFunctionType()) {
5950 LValue LV;
5951 if (!EvaluateLValue(E, LV, Info))
5952 return false;
5953 LV.moveInto(Result);
5954 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005955 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005956 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005957 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005958 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005959 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005960 } else if (E->getType()->hasPointerRepresentation()) {
5961 LValue LV;
5962 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005963 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005964 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005965 } else if (E->getType()->isRealFloatingType()) {
5966 llvm::APFloat F(0.0);
5967 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005968 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005969 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005970 } else if (E->getType()->isAnyComplexType()) {
5971 ComplexValue C;
5972 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005973 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005974 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005975 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005976 MemberPtr P;
5977 if (!EvaluateMemberPointer(E, P, Info))
5978 return false;
5979 P.moveInto(Result);
5980 return true;
Richard Smith51201882011-12-30 21:15:51 +00005981 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005982 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005983 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005984 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005985 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005986 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005987 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005988 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005989 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005990 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5991 return false;
5992 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005993 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005994 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00005995 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00005996 << E->getType();
5997 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00005998 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005999 if (!EvaluateVoid(E, Info))
6000 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006001 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006002 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006003 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006004 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006005 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006006 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006007 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006008
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006009 return true;
6010}
6011
Richard Smith83587db2012-02-15 02:18:13 +00006012/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6013/// cases, the in-place evaluation is essential, since later initializers for
6014/// an object can indirectly refer to subobjects which were initialized earlier.
6015static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6016 const Expr *E, CheckConstantExpressionKind CCEK,
6017 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006018 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006019 return false;
6020
6021 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006022 // Evaluate arrays and record types in-place, so that later initializers can
6023 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006024 if (E->getType()->isArrayType())
6025 return EvaluateArray(E, This, Result, Info);
6026 else if (E->getType()->isRecordType())
6027 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006028 }
6029
6030 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006031 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006032}
6033
Richard Smithf48fdb02011-12-09 22:58:01 +00006034/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6035/// lvalue-to-rvalue cast if it is an lvalue.
6036static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006037 if (!CheckLiteralType(Info, E))
6038 return false;
6039
Richard Smith1aa0be82012-03-03 22:46:17 +00006040 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006041 return false;
6042
6043 if (E->isGLValue()) {
6044 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006045 LV.setFrom(Info.Ctx, Result);
6046 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006047 return false;
6048 }
6049
Richard Smith1aa0be82012-03-03 22:46:17 +00006050 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006051 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006052}
Richard Smithc49bd112011-10-28 17:51:58 +00006053
Richard Smith51f47082011-10-29 00:50:52 +00006054/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006055/// any crazy technique (that has nothing to do with language standards) that
6056/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006057/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6058/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006059bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006060 // Fast-path evaluations of integer literals, since we sometimes see files
6061 // containing vast quantities of these.
6062 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6063 Result.Val = APValue(APSInt(L->getValue(),
6064 L->getType()->isUnsignedIntegerType()));
6065 return true;
6066 }
6067
Richard Smith2d6a5672012-01-14 04:30:29 +00006068 // FIXME: Evaluating values of large array and record types can cause
6069 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006070 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006071 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006072 return false;
6073
Richard Smithf48fdb02011-12-09 22:58:01 +00006074 EvalInfo Info(Ctx, Result);
6075 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006076}
6077
Jay Foad4ba2a172011-01-12 09:06:06 +00006078bool Expr::EvaluateAsBooleanCondition(bool &Result,
6079 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006080 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006081 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006082 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006083}
6084
Richard Smith80d4b552011-12-28 19:48:30 +00006085bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6086 SideEffectsKind AllowSideEffects) const {
6087 if (!getType()->isIntegralOrEnumerationType())
6088 return false;
6089
Richard Smithc49bd112011-10-28 17:51:58 +00006090 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006091 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6092 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006093 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006094
Richard Smithc49bd112011-10-28 17:51:58 +00006095 Result = ExprResult.Val.getInt();
6096 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006097}
6098
Jay Foad4ba2a172011-01-12 09:06:06 +00006099bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006100 EvalInfo Info(Ctx, Result);
6101
John McCallefdb83e2010-05-07 21:00:08 +00006102 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006103 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6104 !CheckLValueConstantExpression(Info, getExprLoc(),
6105 Ctx.getLValueReferenceType(getType()), LV))
6106 return false;
6107
Richard Smith1aa0be82012-03-03 22:46:17 +00006108 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006109 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006110}
6111
Richard Smith099e7f62011-12-19 06:19:21 +00006112bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6113 const VarDecl *VD,
6114 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006115 // FIXME: Evaluating initializers for large array and record types can cause
6116 // performance problems. Only do so in C++11 for now.
6117 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006118 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006119 return false;
6120
Richard Smith099e7f62011-12-19 06:19:21 +00006121 Expr::EvalStatus EStatus;
6122 EStatus.Diag = &Notes;
6123
6124 EvalInfo InitInfo(Ctx, EStatus);
6125 InitInfo.setEvaluatingDecl(VD, Value);
6126
6127 LValue LVal;
6128 LVal.set(VD);
6129
Richard Smith51201882011-12-30 21:15:51 +00006130 // C++11 [basic.start.init]p2:
6131 // Variables with static storage duration or thread storage duration shall be
6132 // zero-initialized before any other initialization takes place.
6133 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006134 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006135 !VD->getType()->isReferenceType()) {
6136 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006137 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6138 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006139 return false;
6140 }
6141
Richard Smith83587db2012-02-15 02:18:13 +00006142 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6143 /*AllowNonLiteralTypes=*/true) ||
6144 EStatus.HasSideEffects)
6145 return false;
6146
6147 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6148 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006149}
6150
Richard Smith51f47082011-10-29 00:50:52 +00006151/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6152/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006153bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006154 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006155 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006156}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006157
Jay Foad4ba2a172011-01-12 09:06:06 +00006158bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006159 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006160}
6161
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006162APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006163 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006164 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006165 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006166 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006167 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006168
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006169 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006170}
John McCalld905f5a2010-05-07 05:32:02 +00006171
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006172 bool Expr::EvalResult::isGlobalLValue() const {
6173 assert(Val.isLValue());
6174 return IsGlobalLValue(Val.getLValueBase());
6175 }
6176
6177
John McCalld905f5a2010-05-07 05:32:02 +00006178/// isIntegerConstantExpr - this recursive routine will test if an expression is
6179/// an integer constant expression.
6180
6181/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6182/// comma, etc
6183///
6184/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6185/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6186/// cast+dereference.
6187
6188// CheckICE - This function does the fundamental ICE checking: the returned
6189// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6190// Note that to reduce code duplication, this helper does no evaluation
6191// itself; the caller checks whether the expression is evaluatable, and
6192// in the rare cases where CheckICE actually cares about the evaluated
6193// value, it calls into Evalute.
6194//
6195// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006196// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006197// 1: This expression is not an ICE, but if it isn't evaluated, it's
6198// a legal subexpression for an ICE. This return value is used to handle
6199// the comma operator in C99 mode.
6200// 2: This expression is not an ICE, and is not a legal subexpression for one.
6201
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006202namespace {
6203
John McCalld905f5a2010-05-07 05:32:02 +00006204struct ICEDiag {
6205 unsigned Val;
6206 SourceLocation Loc;
6207
6208 public:
6209 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6210 ICEDiag() : Val(0) {}
6211};
6212
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006213}
6214
6215static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006216
6217static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6218 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006219 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006220 !EVResult.Val.isInt()) {
6221 return ICEDiag(2, E->getLocStart());
6222 }
6223 return NoDiag();
6224}
6225
6226static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6227 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006228 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006229 return ICEDiag(2, E->getLocStart());
6230 }
6231
6232 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006233#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006234#define STMT(Node, Base) case Expr::Node##Class:
6235#define EXPR(Node, Base)
6236#include "clang/AST/StmtNodes.inc"
6237 case Expr::PredefinedExprClass:
6238 case Expr::FloatingLiteralClass:
6239 case Expr::ImaginaryLiteralClass:
6240 case Expr::StringLiteralClass:
6241 case Expr::ArraySubscriptExprClass:
6242 case Expr::MemberExprClass:
6243 case Expr::CompoundAssignOperatorClass:
6244 case Expr::CompoundLiteralExprClass:
6245 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006246 case Expr::DesignatedInitExprClass:
6247 case Expr::ImplicitValueInitExprClass:
6248 case Expr::ParenListExprClass:
6249 case Expr::VAArgExprClass:
6250 case Expr::AddrLabelExprClass:
6251 case Expr::StmtExprClass:
6252 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006253 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006254 case Expr::CXXDynamicCastExprClass:
6255 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006256 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006257 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006258 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006259 case Expr::CXXThisExprClass:
6260 case Expr::CXXThrowExprClass:
6261 case Expr::CXXNewExprClass:
6262 case Expr::CXXDeleteExprClass:
6263 case Expr::CXXPseudoDestructorExprClass:
6264 case Expr::UnresolvedLookupExprClass:
6265 case Expr::DependentScopeDeclRefExprClass:
6266 case Expr::CXXConstructExprClass:
6267 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006268 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006269 case Expr::CXXTemporaryObjectExprClass:
6270 case Expr::CXXUnresolvedConstructExprClass:
6271 case Expr::CXXDependentScopeMemberExprClass:
6272 case Expr::UnresolvedMemberExprClass:
6273 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006274 case Expr::ObjCNumericLiteralClass:
6275 case Expr::ObjCArrayLiteralClass:
6276 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006277 case Expr::ObjCEncodeExprClass:
6278 case Expr::ObjCMessageExprClass:
6279 case Expr::ObjCSelectorExprClass:
6280 case Expr::ObjCProtocolExprClass:
6281 case Expr::ObjCIvarRefExprClass:
6282 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006283 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006284 case Expr::ObjCIsaExprClass:
6285 case Expr::ShuffleVectorExprClass:
6286 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006287 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006288 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006289 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006290 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006291 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006292 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006293 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006294 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006295 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006296 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006297 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006298 return ICEDiag(2, E->getLocStart());
6299
Douglas Gregoree8aff02011-01-04 17:33:58 +00006300 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006301 case Expr::GNUNullExprClass:
6302 // GCC considers the GNU __null value to be an integral constant expression.
6303 return NoDiag();
6304
John McCall91a57552011-07-15 05:09:51 +00006305 case Expr::SubstNonTypeTemplateParmExprClass:
6306 return
6307 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6308
John McCalld905f5a2010-05-07 05:32:02 +00006309 case Expr::ParenExprClass:
6310 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006311 case Expr::GenericSelectionExprClass:
6312 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006313 case Expr::IntegerLiteralClass:
6314 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006315 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006316 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006317 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006318 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006319 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006320 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006321 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006322 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006323 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006324 return NoDiag();
6325 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006326 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006327 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6328 // constant expressions, but they can never be ICEs because an ICE cannot
6329 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006330 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006331 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006332 return CheckEvalInICE(E, Ctx);
6333 return ICEDiag(2, E->getLocStart());
6334 }
Richard Smith359c89d2012-02-24 22:12:32 +00006335 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006336 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6337 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006338 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006339 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006340 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006341 // Parameter variables are never constants. Without this check,
6342 // getAnyInitializer() can find a default argument, which leads
6343 // to chaos.
6344 if (isa<ParmVarDecl>(D))
6345 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6346
6347 // C++ 7.1.5.1p2
6348 // A variable of non-volatile const-qualified integral or enumeration
6349 // type initialized by an ICE can be used in ICEs.
6350 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006351 if (!Dcl->getType()->isIntegralOrEnumerationType())
6352 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6353
Richard Smith099e7f62011-12-19 06:19:21 +00006354 const VarDecl *VD;
6355 // Look for a declaration of this variable that has an initializer, and
6356 // check whether it is an ICE.
6357 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6358 return NoDiag();
6359 else
6360 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006361 }
6362 }
6363 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006364 }
John McCalld905f5a2010-05-07 05:32:02 +00006365 case Expr::UnaryOperatorClass: {
6366 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6367 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006368 case UO_PostInc:
6369 case UO_PostDec:
6370 case UO_PreInc:
6371 case UO_PreDec:
6372 case UO_AddrOf:
6373 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006374 // C99 6.6/3 allows increment and decrement within unevaluated
6375 // subexpressions of constant expressions, but they can never be ICEs
6376 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006377 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006378 case UO_Extension:
6379 case UO_LNot:
6380 case UO_Plus:
6381 case UO_Minus:
6382 case UO_Not:
6383 case UO_Real:
6384 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006385 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006386 }
6387
6388 // OffsetOf falls through here.
6389 }
6390 case Expr::OffsetOfExprClass: {
6391 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006392 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006393 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006394 // compliance: we should warn earlier for offsetof expressions with
6395 // array subscripts that aren't ICEs, and if the array subscripts
6396 // are ICEs, the value of the offsetof must be an integer constant.
6397 return CheckEvalInICE(E, Ctx);
6398 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006399 case Expr::UnaryExprOrTypeTraitExprClass: {
6400 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6401 if ((Exp->getKind() == UETT_SizeOf) &&
6402 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006403 return ICEDiag(2, E->getLocStart());
6404 return NoDiag();
6405 }
6406 case Expr::BinaryOperatorClass: {
6407 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6408 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006409 case BO_PtrMemD:
6410 case BO_PtrMemI:
6411 case BO_Assign:
6412 case BO_MulAssign:
6413 case BO_DivAssign:
6414 case BO_RemAssign:
6415 case BO_AddAssign:
6416 case BO_SubAssign:
6417 case BO_ShlAssign:
6418 case BO_ShrAssign:
6419 case BO_AndAssign:
6420 case BO_XorAssign:
6421 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006422 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6423 // constant expressions, but they can never be ICEs because an ICE cannot
6424 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006425 return ICEDiag(2, E->getLocStart());
6426
John McCall2de56d12010-08-25 11:45:40 +00006427 case BO_Mul:
6428 case BO_Div:
6429 case BO_Rem:
6430 case BO_Add:
6431 case BO_Sub:
6432 case BO_Shl:
6433 case BO_Shr:
6434 case BO_LT:
6435 case BO_GT:
6436 case BO_LE:
6437 case BO_GE:
6438 case BO_EQ:
6439 case BO_NE:
6440 case BO_And:
6441 case BO_Xor:
6442 case BO_Or:
6443 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006444 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6445 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006446 if (Exp->getOpcode() == BO_Div ||
6447 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006448 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006449 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006450 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006451 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006452 if (REval == 0)
6453 return ICEDiag(1, E->getLocStart());
6454 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006455 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006456 if (LEval.isMinSignedValue())
6457 return ICEDiag(1, E->getLocStart());
6458 }
6459 }
6460 }
John McCall2de56d12010-08-25 11:45:40 +00006461 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006462 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006463 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6464 // if it isn't evaluated.
6465 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6466 return ICEDiag(1, E->getLocStart());
6467 } else {
6468 // In both C89 and C++, commas in ICEs are illegal.
6469 return ICEDiag(2, E->getLocStart());
6470 }
6471 }
6472 if (LHSResult.Val >= RHSResult.Val)
6473 return LHSResult;
6474 return RHSResult;
6475 }
John McCall2de56d12010-08-25 11:45:40 +00006476 case BO_LAnd:
6477 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006478 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6479 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6480 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6481 // Rare case where the RHS has a comma "side-effect"; we need
6482 // to actually check the condition to see whether the side
6483 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006484 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006485 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006486 return RHSResult;
6487 return NoDiag();
6488 }
6489
6490 if (LHSResult.Val >= RHSResult.Val)
6491 return LHSResult;
6492 return RHSResult;
6493 }
6494 }
6495 }
6496 case Expr::ImplicitCastExprClass:
6497 case Expr::CStyleCastExprClass:
6498 case Expr::CXXFunctionalCastExprClass:
6499 case Expr::CXXStaticCastExprClass:
6500 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006501 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006502 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006503 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006504 if (isa<ExplicitCastExpr>(E)) {
6505 if (const FloatingLiteral *FL
6506 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6507 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6508 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6509 APSInt IgnoredVal(DestWidth, !DestSigned);
6510 bool Ignored;
6511 // If the value does not fit in the destination type, the behavior is
6512 // undefined, so we are not required to treat it as a constant
6513 // expression.
6514 if (FL->getValue().convertToInteger(IgnoredVal,
6515 llvm::APFloat::rmTowardZero,
6516 &Ignored) & APFloat::opInvalidOp)
6517 return ICEDiag(2, E->getLocStart());
6518 return NoDiag();
6519 }
6520 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006521 switch (cast<CastExpr>(E)->getCastKind()) {
6522 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006523 case CK_AtomicToNonAtomic:
6524 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006525 case CK_NoOp:
6526 case CK_IntegralToBoolean:
6527 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006528 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006529 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006530 return ICEDiag(2, E->getLocStart());
6531 }
John McCalld905f5a2010-05-07 05:32:02 +00006532 }
John McCall56ca35d2011-02-17 10:25:35 +00006533 case Expr::BinaryConditionalOperatorClass: {
6534 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6535 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6536 if (CommonResult.Val == 2) return CommonResult;
6537 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6538 if (FalseResult.Val == 2) return FalseResult;
6539 if (CommonResult.Val == 1) return CommonResult;
6540 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006541 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006542 return FalseResult;
6543 }
John McCalld905f5a2010-05-07 05:32:02 +00006544 case Expr::ConditionalOperatorClass: {
6545 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6546 // If the condition (ignoring parens) is a __builtin_constant_p call,
6547 // then only the true side is actually considered in an integer constant
6548 // expression, and it is fully evaluated. This is an important GNU
6549 // extension. See GCC PR38377 for discussion.
6550 if (const CallExpr *CallCE
6551 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006552 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6553 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006554 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006555 if (CondResult.Val == 2)
6556 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006557
Richard Smithf48fdb02011-12-09 22:58:01 +00006558 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6559 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006560
John McCalld905f5a2010-05-07 05:32:02 +00006561 if (TrueResult.Val == 2)
6562 return TrueResult;
6563 if (FalseResult.Val == 2)
6564 return FalseResult;
6565 if (CondResult.Val == 1)
6566 return CondResult;
6567 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6568 return NoDiag();
6569 // Rare case where the diagnostics depend on which side is evaluated
6570 // Note that if we get here, CondResult is 0, and at least one of
6571 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006572 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006573 return FalseResult;
6574 }
6575 return TrueResult;
6576 }
6577 case Expr::CXXDefaultArgExprClass:
6578 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6579 case Expr::ChooseExprClass: {
6580 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6581 }
6582 }
6583
David Blaikie30263482012-01-20 21:50:17 +00006584 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006585}
6586
Richard Smithf48fdb02011-12-09 22:58:01 +00006587/// Evaluate an expression as a C++11 integral constant expression.
6588static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6589 const Expr *E,
6590 llvm::APSInt *Value,
6591 SourceLocation *Loc) {
6592 if (!E->getType()->isIntegralOrEnumerationType()) {
6593 if (Loc) *Loc = E->getExprLoc();
6594 return false;
6595 }
6596
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006597 APValue Result;
6598 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006599 return false;
6600
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006601 assert(Result.isInt() && "pointer cast to int is not an ICE");
6602 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006603 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006604}
6605
Richard Smithdd1f29b2011-12-12 09:28:41 +00006606bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006607 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006608 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6609
John McCalld905f5a2010-05-07 05:32:02 +00006610 ICEDiag d = CheckICE(this, Ctx);
6611 if (d.Val != 0) {
6612 if (Loc) *Loc = d.Loc;
6613 return false;
6614 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006615 return true;
6616}
6617
6618bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6619 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006620 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006621 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6622
6623 if (!isIntegerConstantExpr(Ctx, Loc))
6624 return false;
6625 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006626 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006627 return true;
6628}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006629
Richard Smith70488e22012-02-14 21:38:30 +00006630bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6631 return CheckICE(this, Ctx).Val == 0;
6632}
6633
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006634bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6635 SourceLocation *Loc) const {
6636 // We support this checking in C++98 mode in order to diagnose compatibility
6637 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006638 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006639
Richard Smith70488e22012-02-14 21:38:30 +00006640 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006641 Expr::EvalStatus Status;
6642 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6643 Status.Diag = &Diags;
6644 EvalInfo Info(Ctx, Status);
6645
6646 APValue Scratch;
6647 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6648
6649 if (!Diags.empty()) {
6650 IsConstExpr = false;
6651 if (Loc) *Loc = Diags[0].first;
6652 } else if (!IsConstExpr) {
6653 // FIXME: This shouldn't happen.
6654 if (Loc) *Loc = getExprLoc();
6655 }
6656
6657 return IsConstExpr;
6658}
Richard Smith745f5142012-01-27 01:14:48 +00006659
6660bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6661 llvm::SmallVectorImpl<
6662 PartialDiagnosticAt> &Diags) {
6663 // FIXME: It would be useful to check constexpr function templates, but at the
6664 // moment the constant expression evaluator cannot cope with the non-rigorous
6665 // ASTs which we build for dependent expressions.
6666 if (FD->isDependentContext())
6667 return true;
6668
6669 Expr::EvalStatus Status;
6670 Status.Diag = &Diags;
6671
6672 EvalInfo Info(FD->getASTContext(), Status);
6673 Info.CheckingPotentialConstantExpression = true;
6674
6675 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6676 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6677
6678 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6679 // is a temporary being used as the 'this' pointer.
6680 LValue This;
6681 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006682 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006683
Richard Smith745f5142012-01-27 01:14:48 +00006684 ArrayRef<const Expr*> Args;
6685
6686 SourceLocation Loc = FD->getLocation();
6687
Richard Smith1aa0be82012-03-03 22:46:17 +00006688 APValue Scratch;
6689 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006690 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006691 else
Richard Smith745f5142012-01-27 01:14:48 +00006692 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6693 Args, FD->getBody(), Info, Scratch);
6694
6695 return Diags.empty();
6696}