blob: 2a2b6fb3736396a348721ac128a5868e1c200987 [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
Richard Smithc18c4232011-11-21 19:36:32 +0000415 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
416
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
483 /// Diagnose that the evaluation does not produce a C++11 core constant
484 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000485 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
486 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000487 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000488 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000489 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
490 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000492 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000493 return Diag(Loc, DiagId, ExtraNotes);
494 }
495
496 /// Add a note to a prior diagnostic.
497 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
498 if (!HasActiveDiagnostic)
499 return OptionalDiagnostic();
500 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000501 }
Richard Smith099e7f62011-12-19 06:19:21 +0000502
503 /// Add a stack of notes to a prior diagnostic.
504 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
505 if (HasActiveDiagnostic) {
506 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
507 Diags.begin(), Diags.end());
508 }
509 }
Richard Smith745f5142012-01-27 01:14:48 +0000510
511 /// Should we continue evaluation as much as possible after encountering a
512 /// construct which can't be folded?
513 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000514 return CheckingPotentialConstantExpression &&
515 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000516 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000517 };
Richard Smithf15fda02012-02-02 01:16:57 +0000518
519 /// Object used to treat all foldable expressions as constant expressions.
520 struct FoldConstant {
521 bool Enabled;
522
523 explicit FoldConstant(EvalInfo &Info)
524 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
525 !Info.EvalStatus.HasSideEffects) {
526 }
527 // Treat the value we've computed since this object was created as constant.
528 void Fold(EvalInfo &Info) {
529 if (Enabled && !Info.EvalStatus.Diag->empty() &&
530 !Info.EvalStatus.HasSideEffects)
531 Info.EvalStatus.Diag->clear();
532 }
533 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000534
535 /// RAII object used to suppress diagnostics and side-effects from a
536 /// speculative evaluation.
537 class SpeculativeEvaluationRAII {
538 EvalInfo &Info;
539 Expr::EvalStatus Old;
540
541 public:
542 SpeculativeEvaluationRAII(EvalInfo &Info,
543 llvm::SmallVectorImpl<PartialDiagnosticAt>
544 *NewDiag = 0)
545 : Info(Info), Old(Info.EvalStatus) {
546 Info.EvalStatus.Diag = NewDiag;
547 }
548 ~SpeculativeEvaluationRAII() {
549 Info.EvalStatus = Old;
550 }
551 };
Richard Smith08d6e032011-12-16 19:06:07 +0000552}
Richard Smithbd552ef2011-10-31 05:52:43 +0000553
Richard Smithb4e85ed2012-01-06 16:39:00 +0000554bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
555 CheckSubobjectKind CSK) {
556 if (Invalid)
557 return false;
558 if (isOnePastTheEnd()) {
559 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
560 << CSK;
561 setInvalid();
562 return false;
563 }
564 return true;
565}
566
567void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
568 const Expr *E, uint64_t N) {
569 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
570 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
571 << static_cast<int>(N) << /*array*/ 0
572 << static_cast<unsigned>(MostDerivedArraySize);
573 else
574 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
575 << static_cast<int>(N) << /*non-array*/ 1;
576 setInvalid();
577}
578
Richard Smith08d6e032011-12-16 19:06:07 +0000579CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
580 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000581 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000582 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000583 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000584 Info.CurrentCall = this;
585 ++Info.CallStackDepth;
586}
587
588CallStackFrame::~CallStackFrame() {
589 assert(Info.CurrentCall == this && "calls retired out of order");
590 --Info.CallStackDepth;
591 Info.CurrentCall = Caller;
592}
593
594/// Produce a string describing the given constexpr call.
595static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
596 unsigned ArgIndex = 0;
597 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000598 !isa<CXXConstructorDecl>(Frame->Callee) &&
599 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000600
601 if (!IsMemberCall)
602 Out << *Frame->Callee << '(';
603
604 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
605 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000606 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000607 Out << ", ";
608
609 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000610 const APValue &Arg = Frame->Arguments[ArgIndex];
611 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000612
613 if (ArgIndex == 0 && IsMemberCall)
614 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000615 }
616
Richard Smith08d6e032011-12-16 19:06:07 +0000617 Out << ')';
618}
619
620void EvalInfo::addCallStack(unsigned Limit) {
621 // Determine which calls to skip, if any.
622 unsigned ActiveCalls = CallStackDepth - 1;
623 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
624 if (Limit && Limit < ActiveCalls) {
625 SkipStart = Limit / 2 + Limit % 2;
626 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000627 }
628
Richard Smith08d6e032011-12-16 19:06:07 +0000629 // Walk the call stack and add the diagnostics.
630 unsigned CallIdx = 0;
631 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
632 Frame = Frame->Caller, ++CallIdx) {
633 // Skip this call?
634 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
635 if (CallIdx == SkipStart) {
636 // Note that we're skipping calls.
637 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
638 << unsigned(ActiveCalls - Limit);
639 }
640 continue;
641 }
642
643 llvm::SmallVector<char, 128> Buffer;
644 llvm::raw_svector_ostream Out(Buffer);
645 describeCall(Frame, Out);
646 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
647 }
648}
649
650namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000651 struct ComplexValue {
652 private:
653 bool IsInt;
654
655 public:
656 APSInt IntReal, IntImag;
657 APFloat FloatReal, FloatImag;
658
659 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
660
661 void makeComplexFloat() { IsInt = false; }
662 bool isComplexFloat() const { return !IsInt; }
663 APFloat &getComplexFloatReal() { return FloatReal; }
664 APFloat &getComplexFloatImag() { return FloatImag; }
665
666 void makeComplexInt() { IsInt = true; }
667 bool isComplexInt() const { return IsInt; }
668 APSInt &getComplexIntReal() { return IntReal; }
669 APSInt &getComplexIntImag() { return IntImag; }
670
Richard Smith1aa0be82012-03-03 22:46:17 +0000671 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000672 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000673 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000674 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000675 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000676 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000677 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000678 assert(v.isComplexFloat() || v.isComplexInt());
679 if (v.isComplexFloat()) {
680 makeComplexFloat();
681 FloatReal = v.getComplexFloatReal();
682 FloatImag = v.getComplexFloatImag();
683 } else {
684 makeComplexInt();
685 IntReal = v.getComplexIntReal();
686 IntImag = v.getComplexIntImag();
687 }
688 }
John McCallf4cf1a12010-05-07 17:22:02 +0000689 };
John McCallefdb83e2010-05-07 21:00:08 +0000690
691 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000692 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000693 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000694 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000695 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000696
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000697 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000698 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000699 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000700 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000701 SubobjectDesignator &getLValueDesignator() { return Designator; }
702 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000703
Richard Smith1aa0be82012-03-03 22:46:17 +0000704 void moveInto(APValue &V) const {
705 if (Designator.Invalid)
706 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
707 else
708 V = APValue(Base, Offset, Designator.Entries,
709 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000710 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000711 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000712 assert(V.isLValue());
713 Base = V.getLValueBase();
714 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000715 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000716 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000717 }
718
Richard Smith83587db2012-02-15 02:18:13 +0000719 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000720 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000721 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000722 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000723 Designator = SubobjectDesignator(getType(B));
724 }
725
726 // Check that this LValue is not based on a null pointer. If it is, produce
727 // a diagnostic and mark the designator as invalid.
728 bool checkNullPointer(EvalInfo &Info, const Expr *E,
729 CheckSubobjectKind CSK) {
730 if (Designator.Invalid)
731 return false;
732 if (!Base) {
733 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
734 << CSK;
735 Designator.setInvalid();
736 return false;
737 }
738 return true;
739 }
740
741 // Check this LValue refers to an object. If not, set the designator to be
742 // invalid and emit a diagnostic.
743 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
744 return checkNullPointer(Info, E, CSK) &&
745 Designator.checkSubobject(Info, E, CSK);
746 }
747
748 void addDecl(EvalInfo &Info, const Expr *E,
749 const Decl *D, bool Virtual = false) {
750 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
751 Designator.addDeclUnchecked(D, Virtual);
752 }
753 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
754 checkSubobject(Info, E, CSK_ArrayToPointer);
755 Designator.addArrayUnchecked(CAT);
756 }
Richard Smith86024012012-02-18 22:04:06 +0000757 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
758 checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real);
759 Designator.addComplexUnchecked(EltTy, Imag);
760 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000761 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
762 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
763 return;
764 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000765 }
John McCallefdb83e2010-05-07 21:00:08 +0000766 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000767
768 struct MemberPtr {
769 MemberPtr() {}
770 explicit MemberPtr(const ValueDecl *Decl) :
771 DeclAndIsDerivedMember(Decl, false), Path() {}
772
773 /// The member or (direct or indirect) field referred to by this member
774 /// pointer, or 0 if this is a null member pointer.
775 const ValueDecl *getDecl() const {
776 return DeclAndIsDerivedMember.getPointer();
777 }
778 /// Is this actually a member of some type derived from the relevant class?
779 bool isDerivedMember() const {
780 return DeclAndIsDerivedMember.getInt();
781 }
782 /// Get the class which the declaration actually lives in.
783 const CXXRecordDecl *getContainingRecord() const {
784 return cast<CXXRecordDecl>(
785 DeclAndIsDerivedMember.getPointer()->getDeclContext());
786 }
787
Richard Smith1aa0be82012-03-03 22:46:17 +0000788 void moveInto(APValue &V) const {
789 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000790 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000791 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000792 assert(V.isMemberPointer());
793 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
794 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
795 Path.clear();
796 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
797 Path.insert(Path.end(), P.begin(), P.end());
798 }
799
800 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
801 /// whether the member is a member of some class derived from the class type
802 /// of the member pointer.
803 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
804 /// Path - The path of base/derived classes from the member declaration's
805 /// class (exclusive) to the class type of the member pointer (inclusive).
806 SmallVector<const CXXRecordDecl*, 4> Path;
807
808 /// Perform a cast towards the class of the Decl (either up or down the
809 /// hierarchy).
810 bool castBack(const CXXRecordDecl *Class) {
811 assert(!Path.empty());
812 const CXXRecordDecl *Expected;
813 if (Path.size() >= 2)
814 Expected = Path[Path.size() - 2];
815 else
816 Expected = getContainingRecord();
817 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
818 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
819 // if B does not contain the original member and is not a base or
820 // derived class of the class containing the original member, the result
821 // of the cast is undefined.
822 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
823 // (D::*). We consider that to be a language defect.
824 return false;
825 }
826 Path.pop_back();
827 return true;
828 }
829 /// Perform a base-to-derived member pointer cast.
830 bool castToDerived(const CXXRecordDecl *Derived) {
831 if (!getDecl())
832 return true;
833 if (!isDerivedMember()) {
834 Path.push_back(Derived);
835 return true;
836 }
837 if (!castBack(Derived))
838 return false;
839 if (Path.empty())
840 DeclAndIsDerivedMember.setInt(false);
841 return true;
842 }
843 /// Perform a derived-to-base member pointer cast.
844 bool castToBase(const CXXRecordDecl *Base) {
845 if (!getDecl())
846 return true;
847 if (Path.empty())
848 DeclAndIsDerivedMember.setInt(true);
849 if (isDerivedMember()) {
850 Path.push_back(Base);
851 return true;
852 }
853 return castBack(Base);
854 }
855 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000856
Richard Smithb02e4622012-02-01 01:42:44 +0000857 /// Compare two member pointers, which are assumed to be of the same type.
858 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
859 if (!LHS.getDecl() || !RHS.getDecl())
860 return !LHS.getDecl() && !RHS.getDecl();
861 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
862 return false;
863 return LHS.Path == RHS.Path;
864 }
865
Richard Smithc1c5f272011-12-13 06:39:58 +0000866 /// Kinds of constant expression checking, for diagnostics.
867 enum CheckConstantExpressionKind {
868 CCEK_Constant, ///< A normal constant.
869 CCEK_ReturnValue, ///< A constexpr function return value.
870 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
871 };
John McCallf4cf1a12010-05-07 17:22:02 +0000872}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000873
Richard Smith1aa0be82012-03-03 22:46:17 +0000874static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000875static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
876 const LValue &This, const Expr *E,
877 CheckConstantExpressionKind CCEK = CCEK_Constant,
878 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000879static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
880static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000881static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
882 EvalInfo &Info);
883static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000884static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000885static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000886 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000887static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000888static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000889
890//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000891// Misc utilities
892//===----------------------------------------------------------------------===//
893
Richard Smith180f4792011-11-10 06:34:14 +0000894/// Should this call expression be treated as a string literal?
895static bool IsStringLiteralCall(const CallExpr *E) {
896 unsigned Builtin = E->isBuiltinCall();
897 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
898 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
899}
900
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000901static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000902 // C++11 [expr.const]p3 An address constant expression is a prvalue core
903 // constant expression of pointer type that evaluates to...
904
905 // ... a null pointer value, or a prvalue core constant expression of type
906 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000908
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000909 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
910 // ... the address of an object with static storage duration,
911 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
912 return VD->hasGlobalStorage();
913 // ... the address of a function,
914 return isa<FunctionDecl>(D);
915 }
916
917 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000918 switch (E->getStmtClass()) {
919 default:
920 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000921 case Expr::CompoundLiteralExprClass: {
922 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
923 return CLE->isFileScope() && CLE->isLValue();
924 }
Richard Smith180f4792011-11-10 06:34:14 +0000925 // A string literal has static storage duration.
926 case Expr::StringLiteralClass:
927 case Expr::PredefinedExprClass:
928 case Expr::ObjCStringLiteralClass:
929 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000930 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000931 return true;
932 case Expr::CallExprClass:
933 return IsStringLiteralCall(cast<CallExpr>(E));
934 // For GCC compatibility, &&label has static storage duration.
935 case Expr::AddrLabelExprClass:
936 return true;
937 // A Block literal expression may be used as the initialization value for
938 // Block variables at global or local static scope.
939 case Expr::BlockExprClass:
940 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000941 case Expr::ImplicitValueInitExprClass:
942 // FIXME:
943 // We can never form an lvalue with an implicit value initialization as its
944 // base through expression evaluation, so these only appear in one case: the
945 // implicit variable declaration we invent when checking whether a constexpr
946 // constructor can produce a constant expression. We must assume that such
947 // an expression might be a global lvalue.
948 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000949 }
John McCall42c8f872010-05-10 23:27:23 +0000950}
951
Richard Smith83587db2012-02-15 02:18:13 +0000952static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
953 assert(Base && "no location for a null lvalue");
954 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
955 if (VD)
956 Info.Note(VD->getLocation(), diag::note_declared_at);
957 else
958 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
959 diag::note_constexpr_temporary_here);
960}
961
Richard Smith9a17a682011-11-07 05:07:52 +0000962/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000963/// value for an address or reference constant expression. Return true if we
964/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000965static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
966 QualType Type, const LValue &LVal) {
967 bool IsReferenceType = Type->isReferenceType();
968
Richard Smithc1c5f272011-12-13 06:39:58 +0000969 APValue::LValueBase Base = LVal.getLValueBase();
970 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
971
Richard Smithb78ae972012-02-18 04:58:18 +0000972 // Check that the object is a global. Note that the fake 'this' object we
973 // manufacture when checking potential constant expressions is conservatively
974 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 if (!IsGlobalLValue(Base)) {
976 if (Info.getLangOpts().CPlusPlus0x) {
977 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000978 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
979 << IsReferenceType << !Designator.Entries.empty()
980 << !!VD << VD;
981 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000983 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000984 }
Richard Smith61e61622012-01-12 06:08:57 +0000985 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000986 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000987 }
Richard Smith83587db2012-02-15 02:18:13 +0000988 assert((Info.CheckingPotentialConstantExpression ||
989 LVal.getLValueCallIndex() == 0) &&
990 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000991
992 // Allow address constant expressions to be past-the-end pointers. This is
993 // an extension: the standard requires them to point to an object.
994 if (!IsReferenceType)
995 return true;
996
997 // A reference constant expression must refer to an object.
998 if (!Base) {
999 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001000 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001001 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001002 }
1003
Richard Smithc1c5f272011-12-13 06:39:58 +00001004 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001005 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001007 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001008 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001009 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 }
1011
Richard Smith9a17a682011-11-07 05:07:52 +00001012 return true;
1013}
1014
Richard Smith51201882011-12-30 21:15:51 +00001015/// Check that this core constant expression is of literal type, and if not,
1016/// produce an appropriate diagnostic.
1017static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1018 if (!E->isRValue() || E->getType()->isLiteralType())
1019 return true;
1020
1021 // Prvalue constant expressions must be of literal types.
1022 if (Info.getLangOpts().CPlusPlus0x)
1023 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1024 << E->getType();
1025 else
1026 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1027 return false;
1028}
1029
Richard Smith47a1eed2011-10-29 20:57:55 +00001030/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001031/// constant expression. If not, report an appropriate diagnostic. Does not
1032/// check that the expression is of literal type.
1033static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1034 QualType Type, const APValue &Value) {
1035 // Core issue 1454: For a literal constant expression of array or class type,
1036 // each subobject of its value shall have been initialized by a constant
1037 // expression.
1038 if (Value.isArray()) {
1039 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1040 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1041 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1042 Value.getArrayInitializedElt(I)))
1043 return false;
1044 }
1045 if (!Value.hasArrayFiller())
1046 return true;
1047 return CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001049 }
Richard Smith83587db2012-02-15 02:18:13 +00001050 if (Value.isUnion() && Value.getUnionField()) {
1051 return CheckConstantExpression(Info, DiagLoc,
1052 Value.getUnionField()->getType(),
1053 Value.getUnionValue());
1054 }
1055 if (Value.isStruct()) {
1056 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1057 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1058 unsigned BaseIndex = 0;
1059 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1060 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1061 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1062 Value.getStructBase(BaseIndex)))
1063 return false;
1064 }
1065 }
1066 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1067 I != E; ++I) {
1068 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1069 Value.getStructField((*I)->getFieldIndex())))
1070 return false;
1071 }
1072 }
1073
1074 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001075 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001076 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001077 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1078 }
1079
1080 // Everything else is fine.
1081 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001082}
1083
Richard Smith9e36b532011-10-31 05:11:32 +00001084const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001085 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001086}
1087
1088static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001089 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001090}
1091
Richard Smith65ac5982011-11-01 21:06:14 +00001092static bool IsWeakLValue(const LValue &Value) {
1093 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001094 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001095}
1096
Richard Smith1aa0be82012-03-03 22:46:17 +00001097static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001098 // A null base expression indicates a null pointer. These are always
1099 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001100 if (!Value.getLValueBase()) {
1101 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001102 return true;
1103 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001104
Richard Smithe24f5fc2011-11-17 22:56:20 +00001105 // We have a non-null base. These are generally known to be true, but if it's
1106 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001107 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001108 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001109 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001110}
1111
Richard Smith1aa0be82012-03-03 22:46:17 +00001112static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001113 switch (Val.getKind()) {
1114 case APValue::Uninitialized:
1115 return false;
1116 case APValue::Int:
1117 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001118 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001119 case APValue::Float:
1120 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001121 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001122 case APValue::ComplexInt:
1123 Result = Val.getComplexIntReal().getBoolValue() ||
1124 Val.getComplexIntImag().getBoolValue();
1125 return true;
1126 case APValue::ComplexFloat:
1127 Result = !Val.getComplexFloatReal().isZero() ||
1128 !Val.getComplexFloatImag().isZero();
1129 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001130 case APValue::LValue:
1131 return EvalPointerValueAsBool(Val, Result);
1132 case APValue::MemberPointer:
1133 Result = Val.getMemberPointerDecl();
1134 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001135 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001136 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001137 case APValue::Struct:
1138 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001139 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001140 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001141 }
1142
Richard Smithc49bd112011-10-28 17:51:58 +00001143 llvm_unreachable("unknown APValue kind");
1144}
1145
1146static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1147 EvalInfo &Info) {
1148 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001149 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001150 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001151 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001152 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001153}
1154
Richard Smithc1c5f272011-12-13 06:39:58 +00001155template<typename T>
1156static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1157 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001158 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001159 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001160 return false;
1161}
1162
1163static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1164 QualType SrcType, const APFloat &Value,
1165 QualType DestType, APSInt &Result) {
1166 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001167 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001168 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Richard Smithc1c5f272011-12-13 06:39:58 +00001170 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001171 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1173 & APFloat::opInvalidOp)
1174 return HandleOverflow(Info, E, Value, DestType);
1175 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001176}
1177
Richard Smithc1c5f272011-12-13 06:39:58 +00001178static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1179 QualType SrcType, QualType DestType,
1180 APFloat &Result) {
1181 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001182 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001183 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1184 APFloat::rmNearestTiesToEven, &ignored)
1185 & APFloat::opOverflow)
1186 return HandleOverflow(Info, E, Value, DestType);
1187 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188}
1189
Richard Smithf72fccf2012-01-30 22:27:01 +00001190static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1191 QualType DestType, QualType SrcType,
1192 APSInt &Value) {
1193 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194 APSInt Result = Value;
1195 // Figure out if this is a truncate, extend or noop cast.
1196 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001197 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001198 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001199 return Result;
1200}
1201
Richard Smithc1c5f272011-12-13 06:39:58 +00001202static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1203 QualType SrcType, const APSInt &Value,
1204 QualType DestType, APFloat &Result) {
1205 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1206 if (Result.convertFromAPInt(Value, Value.isSigned(),
1207 APFloat::rmNearestTiesToEven)
1208 & APFloat::opOverflow)
1209 return HandleOverflow(Info, E, Value, DestType);
1210 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001211}
1212
Eli Friedmane6a24e82011-12-22 03:51:45 +00001213static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1214 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001215 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001216 if (!Evaluate(SVal, Info, E))
1217 return false;
1218 if (SVal.isInt()) {
1219 Res = SVal.getInt();
1220 return true;
1221 }
1222 if (SVal.isFloat()) {
1223 Res = SVal.getFloat().bitcastToAPInt();
1224 return true;
1225 }
1226 if (SVal.isVector()) {
1227 QualType VecTy = E->getType();
1228 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1229 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1230 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1231 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1232 Res = llvm::APInt::getNullValue(VecSize);
1233 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1234 APValue &Elt = SVal.getVectorElt(i);
1235 llvm::APInt EltAsInt;
1236 if (Elt.isInt()) {
1237 EltAsInt = Elt.getInt();
1238 } else if (Elt.isFloat()) {
1239 EltAsInt = Elt.getFloat().bitcastToAPInt();
1240 } else {
1241 // Don't try to handle vectors of anything other than int or float
1242 // (not sure if it's possible to hit this case).
1243 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1244 return false;
1245 }
1246 unsigned BaseEltSize = EltAsInt.getBitWidth();
1247 if (BigEndian)
1248 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1249 else
1250 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1251 }
1252 return true;
1253 }
1254 // Give up if the input isn't an int, float, or vector. For example, we
1255 // reject "(v4i16)(intptr_t)&a".
1256 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1257 return false;
1258}
1259
Richard Smithb4e85ed2012-01-06 16:39:00 +00001260/// Cast an lvalue referring to a base subobject to a derived class, by
1261/// truncating the lvalue's path to the given length.
1262static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1263 const RecordDecl *TruncatedType,
1264 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001265 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266
1267 // Check we actually point to a derived class object.
1268 if (TruncatedElements == D.Entries.size())
1269 return true;
1270 assert(TruncatedElements >= D.MostDerivedPathLength &&
1271 "not casting to a derived class");
1272 if (!Result.checkSubobject(Info, E, CSK_Derived))
1273 return false;
1274
1275 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001276 const RecordDecl *RD = TruncatedType;
1277 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001278 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1279 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001280 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001281 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001282 else
Richard Smith180f4792011-11-10 06:34:14 +00001283 Result.Offset -= Layout.getBaseClassOffset(Base);
1284 RD = Base;
1285 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001287 return true;
1288}
1289
Richard Smithb4e85ed2012-01-06 16:39:00 +00001290static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001291 const CXXRecordDecl *Derived,
1292 const CXXRecordDecl *Base,
1293 const ASTRecordLayout *RL = 0) {
1294 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1295 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001297}
1298
Richard Smithb4e85ed2012-01-06 16:39:00 +00001299static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001300 const CXXRecordDecl *DerivedDecl,
1301 const CXXBaseSpecifier *Base) {
1302 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1303
1304 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001305 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001306 return true;
1307 }
1308
Richard Smithb4e85ed2012-01-06 16:39:00 +00001309 SubobjectDesignator &D = Obj.Designator;
1310 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001311 return false;
1312
Richard Smithb4e85ed2012-01-06 16:39:00 +00001313 // Extract most-derived object and corresponding type.
1314 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1315 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1316 return false;
1317
1318 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001319 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1320 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001321 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001322 return true;
1323}
1324
1325/// Update LVal to refer to the given field, which must be a member of the type
1326/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001328 const FieldDecl *FD,
1329 const ASTRecordLayout *RL = 0) {
1330 if (!RL)
1331 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1332
1333 unsigned I = FD->getFieldIndex();
1334 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001335 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001336}
1337
Richard Smithd9b02e72012-01-25 22:15:11 +00001338/// Update LVal to refer to the given indirect field.
1339static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1340 LValue &LVal,
1341 const IndirectFieldDecl *IFD) {
1342 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1343 CE = IFD->chain_end(); C != CE; ++C)
1344 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1345}
1346
Richard Smith180f4792011-11-10 06:34:14 +00001347/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001348static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1349 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001350 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1351 // extension.
1352 if (Type->isVoidType() || Type->isFunctionType()) {
1353 Size = CharUnits::One();
1354 return true;
1355 }
1356
1357 if (!Type->isConstantSizeType()) {
1358 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001359 // FIXME: Better diagnostic.
1360 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001361 return false;
1362 }
1363
1364 Size = Info.Ctx.getTypeSizeInChars(Type);
1365 return true;
1366}
1367
1368/// Update a pointer value to model pointer arithmetic.
1369/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001370/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001371/// \param LVal - The pointer value to be updated.
1372/// \param EltTy - The pointee type represented by LVal.
1373/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001374static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1375 LValue &LVal, QualType EltTy,
1376 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001377 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001378 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001379 return false;
1380
1381 // Compute the new offset in the appropriate width.
1382 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001383 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001384 return true;
1385}
1386
Richard Smith86024012012-02-18 22:04:06 +00001387/// Update an lvalue to refer to a component of a complex number.
1388/// \param Info - Information about the ongoing evaluation.
1389/// \param LVal - The lvalue to be updated.
1390/// \param EltTy - The complex number's component type.
1391/// \param Imag - False for the real component, true for the imaginary.
1392static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1393 LValue &LVal, QualType EltTy,
1394 bool Imag) {
1395 if (Imag) {
1396 CharUnits SizeOfComponent;
1397 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1398 return false;
1399 LVal.Offset += SizeOfComponent;
1400 }
1401 LVal.addComplex(Info, E, EltTy, Imag);
1402 return true;
1403}
1404
Richard Smith03f96112011-10-24 17:54:18 +00001405/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001406static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1407 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001408 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001409 // If this is a parameter to an active constexpr function call, perform
1410 // argument substitution.
1411 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001412 // Assume arguments of a potential constant expression are unknown
1413 // constant expressions.
1414 if (Info.CheckingPotentialConstantExpression)
1415 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001416 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001417 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001418 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001419 }
Richard Smith177dce72011-11-01 16:57:24 +00001420 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1421 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001422 }
Richard Smith03f96112011-10-24 17:54:18 +00001423
Richard Smith099e7f62011-12-19 06:19:21 +00001424 // Dig out the initializer, and use the declaration which it's attached to.
1425 const Expr *Init = VD->getAnyInitializer(VD);
1426 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001427 // If we're checking a potential constant expression, the variable could be
1428 // initialized later.
1429 if (!Info.CheckingPotentialConstantExpression)
1430 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001431 return false;
1432 }
1433
Richard Smith180f4792011-11-10 06:34:14 +00001434 // If we're currently evaluating the initializer of this declaration, use that
1435 // in-flight value.
1436 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001437 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001438 return !Result.isUninit();
1439 }
1440
Richard Smith65ac5982011-11-01 21:06:14 +00001441 // Never evaluate the initializer of a weak variable. We can't be sure that
1442 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001444 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001445 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001446 }
Richard Smith65ac5982011-11-01 21:06:14 +00001447
Richard Smith099e7f62011-12-19 06:19:21 +00001448 // Check that we can fold the initializer. In C++, we will have already done
1449 // this in the cases where it matters for conformance.
1450 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1451 if (!VD->evaluateValue(Notes)) {
1452 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1453 Notes.size() + 1) << VD;
1454 Info.Note(VD->getLocation(), diag::note_declared_at);
1455 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001456 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001457 } else if (!VD->checkInitIsICE()) {
1458 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1459 Notes.size() + 1) << VD;
1460 Info.Note(VD->getLocation(), diag::note_declared_at);
1461 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001462 }
Richard Smith03f96112011-10-24 17:54:18 +00001463
Richard Smith1aa0be82012-03-03 22:46:17 +00001464 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001465 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001466}
1467
Richard Smithc49bd112011-10-28 17:51:58 +00001468static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001469 Qualifiers Quals = T.getQualifiers();
1470 return Quals.hasConst() && !Quals.hasVolatile();
1471}
1472
Richard Smith59efe262011-11-11 04:05:33 +00001473/// Get the base index of the given base class within an APValue representing
1474/// the given derived class.
1475static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1476 const CXXRecordDecl *Base) {
1477 Base = Base->getCanonicalDecl();
1478 unsigned Index = 0;
1479 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1480 E = Derived->bases_end(); I != E; ++I, ++Index) {
1481 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1482 return Index;
1483 }
1484
1485 llvm_unreachable("base class missing from derived class's bases list");
1486}
1487
Richard Smithf3908f22012-02-17 03:35:37 +00001488/// Extract the value of a character from a string literal.
1489static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1490 uint64_t Index) {
1491 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1492 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1493 assert(S && "unexpected string literal expression kind");
1494
1495 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1496 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1497 if (Index < S->getLength())
1498 Value = S->getCodeUnit(Index);
1499 return Value;
1500}
1501
Richard Smithcc5d4f62011-11-07 09:22:26 +00001502/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001503static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001504 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001505 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001506 if (Sub.Invalid)
1507 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001509 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001510 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001511 (unsigned)diag::note_constexpr_read_past_end :
1512 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001513 return false;
1514 }
Richard Smithf64699e2011-11-11 08:28:03 +00001515 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001516 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001517 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1518 // This object might be initialized later.
1519 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001520
Richard Smith0069b842012-03-10 00:28:11 +00001521 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001522 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001523 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001525 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001527 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001528 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001529 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001530 // Note, it should not be possible to form a pointer with a valid
1531 // designator which points more than one past the end of the array.
1532 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001533 (unsigned)diag::note_constexpr_read_past_end :
1534 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001536 }
Richard Smithf3908f22012-02-17 03:35:37 +00001537 // An array object is represented as either an Array APValue or as an
1538 // LValue which refers to a string literal.
1539 if (O->isLValue()) {
1540 assert(I == N - 1 && "extracting subobject of character?");
1541 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001542 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001543 Info, O->getLValueBase().get<const Expr*>(), Index));
1544 return true;
1545 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001546 O = &O->getArrayInitializedElt(Index);
1547 else
1548 O = &O->getArrayFiller();
1549 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001550 } else if (ObjType->isAnyComplexType()) {
1551 // Next subobject is a complex number.
1552 uint64_t Index = Sub.Entries[I].ArrayIndex;
1553 if (Index > 1) {
1554 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1555 (unsigned)diag::note_constexpr_read_past_end :
1556 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1557 return false;
1558 }
1559 assert(I == N - 1 && "extracting subobject of scalar?");
1560 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001561 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001562 : O->getComplexIntReal());
1563 } else {
1564 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001565 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001566 : O->getComplexFloatReal());
1567 }
1568 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001569 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001570 if (Field->isMutable()) {
1571 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1572 << Field;
1573 Info.Note(Field->getLocation(), diag::note_declared_at);
1574 return false;
1575 }
1576
Richard Smith180f4792011-11-10 06:34:14 +00001577 // Next subobject is a class, struct or union field.
1578 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1579 if (RD->isUnion()) {
1580 const FieldDecl *UnionField = O->getUnionField();
1581 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001582 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001583 Info.Diag(E->getExprLoc(),
1584 diag::note_constexpr_read_inactive_union_member)
1585 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001586 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001587 }
Richard Smith180f4792011-11-10 06:34:14 +00001588 O = &O->getUnionValue();
1589 } else
1590 O = &O->getStructField(Field->getFieldIndex());
1591 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001592
1593 if (ObjType.isVolatileQualified()) {
1594 if (Info.getLangOpts().CPlusPlus) {
1595 // FIXME: Include a description of the path to the volatile subobject.
1596 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1597 << 2 << Field;
1598 Info.Note(Field->getLocation(), diag::note_declared_at);
1599 } else {
1600 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1601 }
1602 return false;
1603 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001604 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001605 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001606 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1607 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1608 O = &O->getStructBase(getBaseIndex(Derived, Base));
1609 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001610 }
Richard Smith180f4792011-11-10 06:34:14 +00001611
Richard Smithf48fdb02011-12-09 22:58:01 +00001612 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001613 if (!Info.CheckingPotentialConstantExpression)
1614 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001615 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001616 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001617 }
1618
Richard Smith0069b842012-03-10 00:28:11 +00001619 // This may look super-stupid, but it serves an important purpose: if we just
1620 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1621 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1622 // object, which is destroyed by Tmp's destructor.
1623 APValue Tmp;
1624 O->swap(Tmp);
1625 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001626 return true;
1627}
1628
Richard Smithf15fda02012-02-02 01:16:57 +00001629/// Find the position where two subobject designators diverge, or equivalently
1630/// the length of the common initial subsequence.
1631static unsigned FindDesignatorMismatch(QualType ObjType,
1632 const SubobjectDesignator &A,
1633 const SubobjectDesignator &B,
1634 bool &WasArrayIndex) {
1635 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1636 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001637 if (!ObjType.isNull() &&
1638 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001639 // Next subobject is an array element.
1640 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1641 WasArrayIndex = true;
1642 return I;
1643 }
Richard Smith86024012012-02-18 22:04:06 +00001644 if (ObjType->isAnyComplexType())
1645 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1646 else
1647 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001648 } else {
1649 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1650 WasArrayIndex = false;
1651 return I;
1652 }
1653 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1654 // Next subobject is a field.
1655 ObjType = FD->getType();
1656 else
1657 // Next subobject is a base class.
1658 ObjType = QualType();
1659 }
1660 }
1661 WasArrayIndex = false;
1662 return I;
1663}
1664
1665/// Determine whether the given subobject designators refer to elements of the
1666/// same array object.
1667static bool AreElementsOfSameArray(QualType ObjType,
1668 const SubobjectDesignator &A,
1669 const SubobjectDesignator &B) {
1670 if (A.Entries.size() != B.Entries.size())
1671 return false;
1672
1673 bool IsArray = A.MostDerivedArraySize != 0;
1674 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1675 // A is a subobject of the array element.
1676 return false;
1677
1678 // If A (and B) designates an array element, the last entry will be the array
1679 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1680 // of length 1' case, and the entire path must match.
1681 bool WasArrayIndex;
1682 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1683 return CommonLength >= A.Entries.size() - IsArray;
1684}
1685
Richard Smith180f4792011-11-10 06:34:14 +00001686/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1687/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1688/// for looking up the glvalue referred to by an entity of reference type.
1689///
1690/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001691/// \param Conv - The expression for which we are performing the conversion.
1692/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001693/// \param Type - The type we expect this conversion to produce, before
1694/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001695/// \param LVal - The glvalue on which we are attempting to perform this action.
1696/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001697static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1698 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001699 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001700 if (LVal.Designator.Invalid)
1701 // A diagnostic will have already been produced.
1702 return false;
1703
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001704 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001705 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001706
Richard Smithf48fdb02011-12-09 22:58:01 +00001707 if (!LVal.Base) {
1708 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001709 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1710 return false;
1711 }
1712
Richard Smith83587db2012-02-15 02:18:13 +00001713 CallStackFrame *Frame = 0;
1714 if (LVal.CallIndex) {
1715 Frame = Info.getCallFrame(LVal.CallIndex);
1716 if (!Frame) {
1717 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1718 NoteLValueLocation(Info, LVal.Base);
1719 return false;
1720 }
1721 }
1722
Richard Smith7098cbd2011-12-21 05:04:46 +00001723 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1724 // is not a constant expression (even if the object is non-volatile). We also
1725 // apply this rule to C++98, in order to conform to the expected 'volatile'
1726 // semantics.
1727 if (Type.isVolatileQualified()) {
1728 if (Info.getLangOpts().CPlusPlus)
1729 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1730 else
1731 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001732 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 }
Richard Smithc49bd112011-10-28 17:51:58 +00001734
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001735 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001736 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1737 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001738 // expressions are constant expressions too. Inside constexpr functions,
1739 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001740 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001741 const VarDecl *VD = dyn_cast<VarDecl>(D);
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001742 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
Richard Smithf15fda02012-02-02 01:16:57 +00001743 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001744 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001745 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001746 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001747 }
1748
Richard Smith7098cbd2011-12-21 05:04:46 +00001749 // DR1313: If the object is volatile-qualified but the glvalue was not,
1750 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001751 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001752 if (VT.isVolatileQualified()) {
1753 if (Info.getLangOpts().CPlusPlus) {
1754 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1755 Info.Note(VD->getLocation(), diag::note_declared_at);
1756 } else {
1757 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001758 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001759 return false;
1760 }
1761
1762 if (!isa<ParmVarDecl>(VD)) {
1763 if (VD->isConstexpr()) {
1764 // OK, we can read this variable.
1765 } else if (VT->isIntegralOrEnumerationType()) {
1766 if (!VT.isConstQualified()) {
1767 if (Info.getLangOpts().CPlusPlus) {
1768 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1769 Info.Note(VD->getLocation(), diag::note_declared_at);
1770 } else {
1771 Info.Diag(Loc);
1772 }
1773 return false;
1774 }
1775 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1776 // We support folding of const floating-point types, in order to make
1777 // static const data members of such types (supported as an extension)
1778 // more useful.
1779 if (Info.getLangOpts().CPlusPlus0x) {
1780 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1781 Info.Note(VD->getLocation(), diag::note_declared_at);
1782 } else {
1783 Info.CCEDiag(Loc);
1784 }
1785 } else {
1786 // FIXME: Allow folding of values of any literal type in all languages.
1787 if (Info.getLangOpts().CPlusPlus0x) {
1788 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1789 Info.Note(VD->getLocation(), diag::note_declared_at);
1790 } else {
1791 Info.Diag(Loc);
1792 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001793 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001794 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001795 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001796
Richard Smithf48fdb02011-12-09 22:58:01 +00001797 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001798 return false;
1799
Richard Smith47a1eed2011-10-29 20:57:55 +00001800 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001801 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001802
1803 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1804 // conversion. This happens when the declaration and the lvalue should be
1805 // considered synonymous, for instance when initializing an array of char
1806 // from a string literal. Continue as if the initializer lvalue was the
1807 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001808 assert(RVal.getLValueOffset().isZero() &&
1809 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001810 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001811
1812 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1813 Frame = Info.getCallFrame(CallIndex);
1814 if (!Frame) {
1815 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1816 NoteLValueLocation(Info, RVal.getLValueBase());
1817 return false;
1818 }
1819 } else {
1820 Frame = 0;
1821 }
Richard Smithc49bd112011-10-28 17:51:58 +00001822 }
1823
Richard Smith7098cbd2011-12-21 05:04:46 +00001824 // Volatile temporary objects cannot be read in constant expressions.
1825 if (Base->getType().isVolatileQualified()) {
1826 if (Info.getLangOpts().CPlusPlus) {
1827 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1828 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1829 } else {
1830 Info.Diag(Loc);
1831 }
1832 return false;
1833 }
1834
Richard Smithcc5d4f62011-11-07 09:22:26 +00001835 if (Frame) {
1836 // If this is a temporary expression with a nontrivial initializer, grab the
1837 // value from the relevant stack frame.
1838 RVal = Frame->Temporaries[Base];
1839 } else if (const CompoundLiteralExpr *CLE
1840 = dyn_cast<CompoundLiteralExpr>(Base)) {
1841 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1842 // initializer until now for such expressions. Such an expression can't be
1843 // an ICE in C, so this only matters for fold.
1844 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1845 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1846 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001847 } else if (isa<StringLiteral>(Base)) {
1848 // We represent a string literal array as an lvalue pointing at the
1849 // corresponding expression, rather than building an array of chars.
1850 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001851 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001852 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001853 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001854 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001855 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001856
Richard Smithf48fdb02011-12-09 22:58:01 +00001857 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1858 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001859}
1860
Richard Smith59efe262011-11-11 04:05:33 +00001861/// Build an lvalue for the object argument of a member function call.
1862static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1863 LValue &This) {
1864 if (Object->getType()->isPointerType())
1865 return EvaluatePointer(Object, This, Info);
1866
1867 if (Object->isGLValue())
1868 return EvaluateLValue(Object, This, Info);
1869
Richard Smithe24f5fc2011-11-17 22:56:20 +00001870 if (Object->getType()->isLiteralType())
1871 return EvaluateTemporary(Object, This, Info);
1872
1873 return false;
1874}
1875
1876/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1877/// lvalue referring to the result.
1878///
1879/// \param Info - Information about the ongoing evaluation.
1880/// \param BO - The member pointer access operation.
1881/// \param LV - Filled in with a reference to the resulting object.
1882/// \param IncludeMember - Specifies whether the member itself is included in
1883/// the resulting LValue subobject designator. This is not possible when
1884/// creating a bound member function.
1885/// \return The field or method declaration to which the member pointer refers,
1886/// or 0 if evaluation fails.
1887static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1888 const BinaryOperator *BO,
1889 LValue &LV,
1890 bool IncludeMember = true) {
1891 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1892
Richard Smith745f5142012-01-27 01:14:48 +00001893 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1894 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001895 return 0;
1896
1897 MemberPtr MemPtr;
1898 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1899 return 0;
1900
1901 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1902 // member value, the behavior is undefined.
1903 if (!MemPtr.getDecl())
1904 return 0;
1905
Richard Smith745f5142012-01-27 01:14:48 +00001906 if (!EvalObjOK)
1907 return 0;
1908
Richard Smithe24f5fc2011-11-17 22:56:20 +00001909 if (MemPtr.isDerivedMember()) {
1910 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001911 // The end of the derived-to-base path for the base object must match the
1912 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001913 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001914 LV.Designator.Entries.size())
1915 return 0;
1916 unsigned PathLengthToMember =
1917 LV.Designator.Entries.size() - MemPtr.Path.size();
1918 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1919 const CXXRecordDecl *LVDecl = getAsBaseClass(
1920 LV.Designator.Entries[PathLengthToMember + I]);
1921 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1922 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1923 return 0;
1924 }
1925
1926 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001927 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1928 PathLengthToMember))
1929 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 } else if (!MemPtr.Path.empty()) {
1931 // Extend the LValue path with the member pointer's path.
1932 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1933 MemPtr.Path.size() + IncludeMember);
1934
1935 // Walk down to the appropriate base class.
1936 QualType LVType = BO->getLHS()->getType();
1937 if (const PointerType *PT = LVType->getAs<PointerType>())
1938 LVType = PT->getPointeeType();
1939 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1940 assert(RD && "member pointer access on non-class-type expression");
1941 // The first class in the path is that of the lvalue.
1942 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1943 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001944 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001945 RD = Base;
1946 }
1947 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001948 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001949 }
1950
1951 // Add the member. Note that we cannot build bound member functions here.
1952 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001953 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1954 HandleLValueMember(Info, BO, LV, FD);
1955 else if (const IndirectFieldDecl *IFD =
1956 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1957 HandleLValueIndirectMember(Info, BO, LV, IFD);
1958 else
1959 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001960 }
1961
1962 return MemPtr.getDecl();
1963}
1964
1965/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1966/// the provided lvalue, which currently refers to the base object.
1967static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1968 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001969 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001970 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001971 return false;
1972
Richard Smithb4e85ed2012-01-06 16:39:00 +00001973 QualType TargetQT = E->getType();
1974 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1975 TargetQT = PT->getPointeeType();
1976
1977 // Check this cast lands within the final derived-to-base subobject path.
1978 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1979 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1980 << D.MostDerivedType << TargetQT;
1981 return false;
1982 }
1983
Richard Smithe24f5fc2011-11-17 22:56:20 +00001984 // Check the type of the final cast. We don't need to check the path,
1985 // since a cast can only be formed if the path is unique.
1986 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001987 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1988 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001989 if (NewEntriesSize == D.MostDerivedPathLength)
1990 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1991 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001992 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001993 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1994 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1995 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001998
1999 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002000 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002001}
2002
Mike Stumpc4c90452009-10-27 22:09:17 +00002003namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002004enum EvalStmtResult {
2005 /// Evaluation failed.
2006 ESR_Failed,
2007 /// Hit a 'return' statement.
2008 ESR_Returned,
2009 /// Evaluation succeeded.
2010 ESR_Succeeded
2011};
2012}
2013
2014// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002015static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002016 const Stmt *S) {
2017 switch (S->getStmtClass()) {
2018 default:
2019 return ESR_Failed;
2020
2021 case Stmt::NullStmtClass:
2022 case Stmt::DeclStmtClass:
2023 return ESR_Succeeded;
2024
Richard Smithc1c5f272011-12-13 06:39:58 +00002025 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002026 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002027 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002028 return ESR_Failed;
2029 return ESR_Returned;
2030 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002031
2032 case Stmt::CompoundStmtClass: {
2033 const CompoundStmt *CS = cast<CompoundStmt>(S);
2034 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2035 BE = CS->body_end(); BI != BE; ++BI) {
2036 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2037 if (ESR != ESR_Succeeded)
2038 return ESR;
2039 }
2040 return ESR_Succeeded;
2041 }
2042 }
2043}
2044
Richard Smith61802452011-12-22 02:22:31 +00002045/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2046/// default constructor. If so, we'll fold it whether or not it's marked as
2047/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2048/// so we need special handling.
2049static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002050 const CXXConstructorDecl *CD,
2051 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002052 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2053 return false;
2054
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002055 // Value-initialization does not call a trivial default constructor, so such a
2056 // call is a core constant expression whether or not the constructor is
2057 // constexpr.
2058 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002059 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002060 // FIXME: If DiagDecl is an implicitly-declared special member function,
2061 // we should be much more explicit about why it's not constexpr.
2062 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2063 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2064 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002065 } else {
2066 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2067 }
2068 }
2069 return true;
2070}
2071
Richard Smithc1c5f272011-12-13 06:39:58 +00002072/// CheckConstexprFunction - Check that a function can be called in a constant
2073/// expression.
2074static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2075 const FunctionDecl *Declaration,
2076 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002077 // Potential constant expressions can contain calls to declared, but not yet
2078 // defined, constexpr functions.
2079 if (Info.CheckingPotentialConstantExpression && !Definition &&
2080 Declaration->isConstexpr())
2081 return false;
2082
Richard Smithc1c5f272011-12-13 06:39:58 +00002083 // Can we evaluate this function call?
2084 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2085 return true;
2086
2087 if (Info.getLangOpts().CPlusPlus0x) {
2088 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002089 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2090 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002091 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2092 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2093 << DiagDecl;
2094 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2095 } else {
2096 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2097 }
2098 return false;
2099}
2100
Richard Smith180f4792011-11-10 06:34:14 +00002101namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002102typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002103}
2104
2105/// EvaluateArgs - Evaluate the arguments to a function call.
2106static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2107 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002108 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002109 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002110 I != E; ++I) {
2111 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2112 // If we're checking for a potential constant expression, evaluate all
2113 // initializers even if some of them fail.
2114 if (!Info.keepEvaluatingAfterFailure())
2115 return false;
2116 Success = false;
2117 }
2118 }
2119 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002120}
2121
Richard Smithd0dccea2011-10-28 22:34:42 +00002122/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002123static bool HandleFunctionCall(SourceLocation CallLoc,
2124 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002125 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002126 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002127 ArgVector ArgValues(Args.size());
2128 if (!EvaluateArgs(Args, ArgValues, Info))
2129 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002130
Richard Smith745f5142012-01-27 01:14:48 +00002131 if (!Info.CheckCallLimit(CallLoc))
2132 return false;
2133
2134 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002135 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2136}
2137
Richard Smith180f4792011-11-10 06:34:14 +00002138/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002139static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002140 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002141 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002142 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002143 ArgVector ArgValues(Args.size());
2144 if (!EvaluateArgs(Args, ArgValues, Info))
2145 return false;
2146
Richard Smith745f5142012-01-27 01:14:48 +00002147 if (!Info.CheckCallLimit(CallLoc))
2148 return false;
2149
Richard Smith86c3ae42012-02-13 03:54:03 +00002150 const CXXRecordDecl *RD = Definition->getParent();
2151 if (RD->getNumVBases()) {
2152 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2153 return false;
2154 }
2155
Richard Smith745f5142012-01-27 01:14:48 +00002156 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002157
2158 // If it's a delegating constructor, just delegate.
2159 if (Definition->isDelegatingConstructor()) {
2160 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002161 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002162 }
2163
Richard Smith610a60c2012-01-10 04:32:03 +00002164 // For a trivial copy or move constructor, perform an APValue copy. This is
2165 // essential for unions, where the operations performed by the constructor
2166 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002167 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002168 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2169 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002170 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002171 RHS.setFrom(Info.Ctx, ArgValues[0]);
2172 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2173 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002174 }
2175
2176 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002177 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002178 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2179 std::distance(RD->field_begin(), RD->field_end()));
2180
2181 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2182
Richard Smith745f5142012-01-27 01:14:48 +00002183 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002184 unsigned BasesSeen = 0;
2185#ifndef NDEBUG
2186 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2187#endif
2188 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2189 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002190 LValue Subobject = This;
2191 APValue *Value = &Result;
2192
2193 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002194 if ((*I)->isBaseInitializer()) {
2195 QualType BaseType((*I)->getBaseClass(), 0);
2196#ifndef NDEBUG
2197 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002198 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002199 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2200 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2201 "base class initializers not in expected order");
2202 ++BaseIt;
2203#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002204 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002205 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002206 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002207 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002208 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002209 if (RD->isUnion()) {
2210 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002211 Value = &Result.getUnionValue();
2212 } else {
2213 Value = &Result.getStructField(FD->getFieldIndex());
2214 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002215 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002216 // Walk the indirect field decl's chain to find the object to initialize,
2217 // and make sure we've initialized every step along it.
2218 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2219 CE = IFD->chain_end();
2220 C != CE; ++C) {
2221 FieldDecl *FD = cast<FieldDecl>(*C);
2222 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2223 // Switch the union field if it differs. This happens if we had
2224 // preceding zero-initialization, and we're now initializing a union
2225 // subobject other than the first.
2226 // FIXME: In this case, the values of the other subobjects are
2227 // specified, since zero-initialization sets all padding bits to zero.
2228 if (Value->isUninit() ||
2229 (Value->isUnion() && Value->getUnionField() != FD)) {
2230 if (CD->isUnion())
2231 *Value = APValue(FD);
2232 else
2233 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2234 std::distance(CD->field_begin(), CD->field_end()));
2235 }
Richard Smith745f5142012-01-27 01:14:48 +00002236 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002237 if (CD->isUnion())
2238 Value = &Value->getUnionValue();
2239 else
2240 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002241 }
Richard Smith180f4792011-11-10 06:34:14 +00002242 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002244 }
Richard Smith745f5142012-01-27 01:14:48 +00002245
Richard Smith83587db2012-02-15 02:18:13 +00002246 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2247 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002248 ? CCEK_Constant : CCEK_MemberInit)) {
2249 // If we're checking for a potential constant expression, evaluate all
2250 // initializers even if some of them fail.
2251 if (!Info.keepEvaluatingAfterFailure())
2252 return false;
2253 Success = false;
2254 }
Richard Smith180f4792011-11-10 06:34:14 +00002255 }
2256
Richard Smith745f5142012-01-27 01:14:48 +00002257 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002258}
2259
Richard Smithd0dccea2011-10-28 22:34:42 +00002260namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002261class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002262 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002263 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002264public:
2265
Richard Smith1e12c592011-10-16 21:26:27 +00002266 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002267
2268 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002269 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002270 return true;
2271 }
2272
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002273 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2274 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002275 return Visit(E->getResultExpr());
2276 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002278 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002279 return true;
2280 return false;
2281 }
John McCallf85e1932011-06-15 23:02:42 +00002282 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002283 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002284 return true;
2285 return false;
2286 }
John McCallf85e1932011-06-15 23:02:42 +00002287
Mike Stumpc4c90452009-10-27 22:09:17 +00002288 // We don't want to evaluate BlockExprs multiple times, as they generate
2289 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002290 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2291 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2292 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002293 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2295 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2296 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2297 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2298 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2299 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002300 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002301 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002302 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002304 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2306 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2307 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2308 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002309 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002310 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2311 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2312 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2313 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2314 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002315 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002316 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002317 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002318 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002319 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002320
2321 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002322 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002323 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2324 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002325 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002326 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002327 return false;
2328 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002329
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002330 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002331};
2332
John McCall56ca35d2011-02-17 10:25:35 +00002333class OpaqueValueEvaluation {
2334 EvalInfo &info;
2335 OpaqueValueExpr *opaqueValue;
2336
2337public:
2338 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2339 Expr *value)
2340 : info(info), opaqueValue(opaqueValue) {
2341
2342 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002343 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002344 this->opaqueValue = 0;
2345 return;
2346 }
John McCall56ca35d2011-02-17 10:25:35 +00002347 }
2348
2349 bool hasError() const { return opaqueValue == 0; }
2350
2351 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002352 // FIXME: For a recursive constexpr call, an outer stack frame might have
2353 // been using this opaque value too, and will now have to re-evaluate the
2354 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002355 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2356 }
2357};
2358
Mike Stumpc4c90452009-10-27 22:09:17 +00002359} // end anonymous namespace
2360
Eli Friedman4efaa272008-11-12 09:44:48 +00002361//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002362// Generic Evaluation
2363//===----------------------------------------------------------------------===//
2364namespace {
2365
Richard Smithf48fdb02011-12-09 22:58:01 +00002366// FIXME: RetTy is always bool. Remove it.
2367template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002368class ExprEvaluatorBase
2369 : public ConstStmtVisitor<Derived, RetTy> {
2370private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002371 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 return static_cast<Derived*>(this)->Success(V, E);
2373 }
Richard Smith51201882011-12-30 21:15:51 +00002374 RetTy DerivedZeroInitialization(const Expr *E) {
2375 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002376 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002377
Richard Smith74e1ad92012-02-16 02:46:34 +00002378 // Check whether a conditional operator with a non-constant condition is a
2379 // potential constant expression. If neither arm is a potential constant
2380 // expression, then the conditional operator is not either.
2381 template<typename ConditionalOperator>
2382 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2383 assert(Info.CheckingPotentialConstantExpression);
2384
2385 // Speculatively evaluate both arms.
2386 {
2387 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2388 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2389
2390 StmtVisitorTy::Visit(E->getFalseExpr());
2391 if (Diag.empty())
2392 return;
2393
2394 Diag.clear();
2395 StmtVisitorTy::Visit(E->getTrueExpr());
2396 if (Diag.empty())
2397 return;
2398 }
2399
2400 Error(E, diag::note_constexpr_conditional_never_const);
2401 }
2402
2403
2404 template<typename ConditionalOperator>
2405 bool HandleConditionalOperator(const ConditionalOperator *E) {
2406 bool BoolResult;
2407 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2408 if (Info.CheckingPotentialConstantExpression)
2409 CheckPotentialConstantConditional(E);
2410 return false;
2411 }
2412
2413 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2414 return StmtVisitorTy::Visit(EvalExpr);
2415 }
2416
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002417protected:
2418 EvalInfo &Info;
2419 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2420 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2421
Richard Smithdd1f29b2011-12-12 09:28:41 +00002422 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002423 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002424 }
2425
2426 /// Report an evaluation error. This should only be called when an error is
2427 /// first discovered. When propagating an error, just return false.
2428 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002429 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002430 return false;
2431 }
2432 bool Error(const Expr *E) {
2433 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2434 }
2435
Richard Smith51201882011-12-30 21:15:51 +00002436 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002437
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002438public:
2439 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2440
2441 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002442 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002443 }
2444 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002445 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002446 }
2447
2448 RetTy VisitParenExpr(const ParenExpr *E)
2449 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2450 RetTy VisitUnaryExtension(const UnaryOperator *E)
2451 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2452 RetTy VisitUnaryPlus(const UnaryOperator *E)
2453 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2454 RetTy VisitChooseExpr(const ChooseExpr *E)
2455 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2456 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2457 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002458 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2459 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002460 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2461 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002462 // We cannot create any objects for which cleanups are required, so there is
2463 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2464 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2465 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002466
Richard Smithc216a012011-12-12 12:46:16 +00002467 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2468 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2469 return static_cast<Derived*>(this)->VisitCastExpr(E);
2470 }
2471 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2472 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2473 return static_cast<Derived*>(this)->VisitCastExpr(E);
2474 }
2475
Richard Smithe24f5fc2011-11-17 22:56:20 +00002476 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2477 switch (E->getOpcode()) {
2478 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002479 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480
2481 case BO_Comma:
2482 VisitIgnoredValue(E->getLHS());
2483 return StmtVisitorTy::Visit(E->getRHS());
2484
2485 case BO_PtrMemD:
2486 case BO_PtrMemI: {
2487 LValue Obj;
2488 if (!HandleMemberPointerAccess(Info, E, Obj))
2489 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002490 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002491 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002492 return false;
2493 return DerivedSuccess(Result, E);
2494 }
2495 }
2496 }
2497
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002498 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002499 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002500 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2501 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002502 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503
Richard Smith74e1ad92012-02-16 02:46:34 +00002504 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002505 }
2506
2507 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002508 bool IsBcpCall = false;
2509 // If the condition (ignoring parens) is a __builtin_constant_p call,
2510 // the result is a constant expression if it can be folded without
2511 // side-effects. This is an important GNU extension. See GCC PR38377
2512 // for discussion.
2513 if (const CallExpr *CallCE =
2514 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2515 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2516 IsBcpCall = true;
2517
2518 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2519 // constant expression; we can't check whether it's potentially foldable.
2520 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2521 return false;
2522
2523 FoldConstant Fold(Info);
2524
Richard Smith74e1ad92012-02-16 02:46:34 +00002525 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002526 return false;
2527
2528 if (IsBcpCall)
2529 Fold.Fold(Info);
2530
2531 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002532 }
2533
2534 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002535 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002536 if (!Value) {
2537 const Expr *Source = E->getSourceExpr();
2538 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002539 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002540 if (Source == E) { // sanity checking.
2541 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002542 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002543 }
2544 return StmtVisitorTy::Visit(Source);
2545 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002546 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002547 }
Richard Smithf10d9172011-10-11 21:43:33 +00002548
Richard Smithd0dccea2011-10-28 22:34:42 +00002549 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002550 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002551 QualType CalleeType = Callee->getType();
2552
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002554 LValue *This = 0, ThisVal;
2555 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002556 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002557
Richard Smith59efe262011-11-11 04:05:33 +00002558 // Extract function decl and 'this' pointer from the callee.
2559 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002560 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002561 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2562 // Explicit bound member calls, such as x.f() or p->g();
2563 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002564 return false;
2565 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002566 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002567 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002568 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2569 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002570 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2571 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002573 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 return Error(Callee);
2575
2576 FD = dyn_cast<FunctionDecl>(Member);
2577 if (!FD)
2578 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002579 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002580 LValue Call;
2581 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002582 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002583
Richard Smithb4e85ed2012-01-06 16:39:00 +00002584 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002585 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002586 FD = dyn_cast_or_null<FunctionDecl>(
2587 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002588 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002589 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002590
2591 // Overloaded operator calls to member functions are represented as normal
2592 // calls with '*this' as the first argument.
2593 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2594 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 // FIXME: When selecting an implicit conversion for an overloaded
2596 // operator delete, we sometimes try to evaluate calls to conversion
2597 // operators without a 'this' parameter!
2598 if (Args.empty())
2599 return Error(E);
2600
Richard Smith59efe262011-11-11 04:05:33 +00002601 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2602 return false;
2603 This = &ThisVal;
2604 Args = Args.slice(1);
2605 }
2606
2607 // Don't call function pointers which have been cast to some other type.
2608 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002609 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002610 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002611 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002612
Richard Smithb04035a2012-02-01 02:39:43 +00002613 if (This && !This->checkSubobject(Info, E, CSK_This))
2614 return false;
2615
Richard Smith86c3ae42012-02-13 03:54:03 +00002616 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2617 // calls to such functions in constant expressions.
2618 if (This && !HasQualifier &&
2619 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2620 return Error(E, diag::note_constexpr_virtual_call);
2621
Richard Smithc1c5f272011-12-13 06:39:58 +00002622 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002623 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002624 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002625
Richard Smithc1c5f272011-12-13 06:39:58 +00002626 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002627 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2628 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002629 return false;
2630
Richard Smith83587db2012-02-15 02:18:13 +00002631 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002632 }
2633
Richard Smithc49bd112011-10-28 17:51:58 +00002634 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2635 return StmtVisitorTy::Visit(E->getInitializer());
2636 }
Richard Smithf10d9172011-10-11 21:43:33 +00002637 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002638 if (E->getNumInits() == 0)
2639 return DerivedZeroInitialization(E);
2640 if (E->getNumInits() == 1)
2641 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002642 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002643 }
2644 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002645 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002646 }
2647 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002648 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002649 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002650 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002651 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002652 }
Richard Smithf10d9172011-10-11 21:43:33 +00002653
Richard Smith180f4792011-11-10 06:34:14 +00002654 /// A member expression where the object is a prvalue is itself a prvalue.
2655 RetTy VisitMemberExpr(const MemberExpr *E) {
2656 assert(!E->isArrow() && "missing call to bound member function?");
2657
Richard Smith1aa0be82012-03-03 22:46:17 +00002658 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002659 if (!Evaluate(Val, Info, E->getBase()))
2660 return false;
2661
2662 QualType BaseTy = E->getBase()->getType();
2663
2664 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002665 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002666 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2667 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2668 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2669
Richard Smithb4e85ed2012-01-06 16:39:00 +00002670 SubobjectDesignator Designator(BaseTy);
2671 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002672
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002674 DerivedSuccess(Val, E);
2675 }
2676
Richard Smithc49bd112011-10-28 17:51:58 +00002677 RetTy VisitCastExpr(const CastExpr *E) {
2678 switch (E->getCastKind()) {
2679 default:
2680 break;
2681
David Chisnall7a7ee302012-01-16 17:27:18 +00002682 case CK_AtomicToNonAtomic:
2683 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002684 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002685 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002686 return StmtVisitorTy::Visit(E->getSubExpr());
2687
2688 case CK_LValueToRValue: {
2689 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002690 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2691 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002692 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002693 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2694 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2695 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002696 return false;
2697 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002698 }
2699 }
2700
Richard Smithf48fdb02011-12-09 22:58:01 +00002701 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002702 }
2703
Richard Smith8327fad2011-10-24 18:44:57 +00002704 /// Visit a value which is evaluated, but whose value is ignored.
2705 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002706 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002707 if (!Evaluate(Scratch, Info, E))
2708 Info.EvalStatus.HasSideEffects = true;
2709 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002710};
2711
2712}
2713
2714//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002715// Common base class for lvalue and temporary evaluation.
2716//===----------------------------------------------------------------------===//
2717namespace {
2718template<class Derived>
2719class LValueExprEvaluatorBase
2720 : public ExprEvaluatorBase<Derived, bool> {
2721protected:
2722 LValue &Result;
2723 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2724 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2725
2726 bool Success(APValue::LValueBase B) {
2727 Result.set(B);
2728 return true;
2729 }
2730
2731public:
2732 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2733 ExprEvaluatorBaseTy(Info), Result(Result) {}
2734
Richard Smith1aa0be82012-03-03 22:46:17 +00002735 bool Success(const APValue &V, const Expr *E) {
2736 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002737 return true;
2738 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739
Richard Smithe24f5fc2011-11-17 22:56:20 +00002740 bool VisitMemberExpr(const MemberExpr *E) {
2741 // Handle non-static data members.
2742 QualType BaseTy;
2743 if (E->isArrow()) {
2744 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2745 return false;
2746 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002747 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002748 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002749 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2750 return false;
2751 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002752 } else {
2753 if (!this->Visit(E->getBase()))
2754 return false;
2755 BaseTy = E->getBase()->getType();
2756 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002757
Richard Smithd9b02e72012-01-25 22:15:11 +00002758 const ValueDecl *MD = E->getMemberDecl();
2759 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2760 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2761 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2762 (void)BaseTy;
2763 HandleLValueMember(this->Info, E, Result, FD);
2764 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2765 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2766 } else
2767 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002768
Richard Smithd9b02e72012-01-25 22:15:11 +00002769 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002770 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002771 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 RefValue))
2773 return false;
2774 return Success(RefValue, E);
2775 }
2776 return true;
2777 }
2778
2779 bool VisitBinaryOperator(const BinaryOperator *E) {
2780 switch (E->getOpcode()) {
2781 default:
2782 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2783
2784 case BO_PtrMemD:
2785 case BO_PtrMemI:
2786 return HandleMemberPointerAccess(this->Info, E, Result);
2787 }
2788 }
2789
2790 bool VisitCastExpr(const CastExpr *E) {
2791 switch (E->getCastKind()) {
2792 default:
2793 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2794
2795 case CK_DerivedToBase:
2796 case CK_UncheckedDerivedToBase: {
2797 if (!this->Visit(E->getSubExpr()))
2798 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002799
2800 // Now figure out the necessary offset to add to the base LV to get from
2801 // the derived class to the base class.
2802 QualType Type = E->getSubExpr()->getType();
2803
2804 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2805 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002806 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807 *PathI))
2808 return false;
2809 Type = (*PathI)->getType();
2810 }
2811
2812 return true;
2813 }
2814 }
2815 }
2816};
2817}
2818
2819//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002820// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002821//
2822// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2823// function designators (in C), decl references to void objects (in C), and
2824// temporaries (if building with -Wno-address-of-temporary).
2825//
2826// LValue evaluation produces values comprising a base expression of one of the
2827// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002828// - Declarations
2829// * VarDecl
2830// * FunctionDecl
2831// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002832// * CompoundLiteralExpr in C
2833// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002834// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002835// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002836// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002837// * ObjCEncodeExpr
2838// * AddrLabelExpr
2839// * BlockExpr
2840// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002841// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002842// * Any Expr, with a CallIndex indicating the function in which the temporary
2843// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002844// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002845//===----------------------------------------------------------------------===//
2846namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002847class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002848 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002849public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2851 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Richard Smithc49bd112011-10-28 17:51:58 +00002853 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2854
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002855 bool VisitDeclRefExpr(const DeclRefExpr *E);
2856 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002857 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002858 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2859 bool VisitMemberExpr(const MemberExpr *E);
2860 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2861 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002862 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2864 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002865 bool VisitUnaryReal(const UnaryOperator *E);
2866 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002867
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002868 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002869 switch (E->getCastKind()) {
2870 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002871 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002872
Eli Friedmandb924222011-10-11 00:13:24 +00002873 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002874 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002875 if (!Visit(E->getSubExpr()))
2876 return false;
2877 Result.Designator.setInvalid();
2878 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002879
Richard Smithe24f5fc2011-11-17 22:56:20 +00002880 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002881 if (!Visit(E->getSubExpr()))
2882 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002884 }
2885 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002886};
2887} // end anonymous namespace
2888
Richard Smithc49bd112011-10-28 17:51:58 +00002889/// Evaluate an expression as an lvalue. This can be legitimately called on
2890/// expressions which are not glvalues, in a few cases:
2891/// * function designators in C,
2892/// * "extern void" objects,
2893/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002894static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002895 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2896 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2897 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002898 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002899}
2900
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002901bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002902 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2903 return Success(FD);
2904 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002905 return VisitVarDecl(E, VD);
2906 return Error(E);
2907}
Richard Smith436c8892011-10-24 23:14:33 +00002908
Richard Smithc49bd112011-10-28 17:51:58 +00002909bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002910 if (!VD->getType()->isReferenceType()) {
2911 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002912 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002913 return true;
2914 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002915 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002916 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002917
Richard Smith1aa0be82012-03-03 22:46:17 +00002918 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002919 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2920 return false;
2921 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002922}
2923
Richard Smithbd552ef2011-10-31 05:52:43 +00002924bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2925 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002926 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002927 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002928 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2929
Richard Smith83587db2012-02-15 02:18:13 +00002930 Result.set(E, Info.CurrentCall->Index);
2931 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2932 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002933 }
2934
2935 // Materialization of an lvalue temporary occurs when we need to force a copy
2936 // (for instance, if it's a bitfield).
2937 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2938 if (!Visit(E->GetTemporaryExpr()))
2939 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002940 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002941 Info.CurrentCall->Temporaries[E]))
2942 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002943 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002944 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002945}
2946
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002947bool
2948LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002949 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2950 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2951 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002952 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002953}
2954
Richard Smith47d21452011-12-27 12:18:28 +00002955bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2956 if (E->isTypeOperand())
2957 return Success(E);
2958 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2959 if (RD && RD->isPolymorphic()) {
2960 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2961 << E->getExprOperand()->getType()
2962 << E->getExprOperand()->getSourceRange();
2963 return false;
2964 }
2965 return Success(E);
2966}
2967
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002968bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002969 // Handle static data members.
2970 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2971 VisitIgnoredValue(E->getBase());
2972 return VisitVarDecl(E, VD);
2973 }
2974
Richard Smithd0dccea2011-10-28 22:34:42 +00002975 // Handle static member functions.
2976 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2977 if (MD->isStatic()) {
2978 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002979 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002980 }
2981 }
2982
Richard Smith180f4792011-11-10 06:34:14 +00002983 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002984 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002985}
2986
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002987bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002988 // FIXME: Deal with vectors as array subscript bases.
2989 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002990 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002991
Anders Carlsson3068d112008-11-16 19:01:22 +00002992 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002993 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002994
Anders Carlsson3068d112008-11-16 19:01:22 +00002995 APSInt Index;
2996 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002997 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002998 int64_t IndexValue
2999 = Index.isSigned() ? Index.getSExtValue()
3000 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003001
Richard Smithb4e85ed2012-01-06 16:39:00 +00003002 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003003}
Eli Friedman4efaa272008-11-12 09:44:48 +00003004
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003005bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003006 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003007}
3008
Richard Smith86024012012-02-18 22:04:06 +00003009bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3010 if (!Visit(E->getSubExpr()))
3011 return false;
3012 // __real is a no-op on scalar lvalues.
3013 if (E->getSubExpr()->getType()->isAnyComplexType())
3014 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3015 return true;
3016}
3017
3018bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3019 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3020 "lvalue __imag__ on scalar?");
3021 if (!Visit(E->getSubExpr()))
3022 return false;
3023 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3024 return true;
3025}
3026
Eli Friedman4efaa272008-11-12 09:44:48 +00003027//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003028// Pointer Evaluation
3029//===----------------------------------------------------------------------===//
3030
Anders Carlssonc754aa62008-07-08 05:13:58 +00003031namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003032class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003033 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003034 LValue &Result;
3035
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003036 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003037 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003038 return true;
3039 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003040public:
Mike Stump1eb44332009-09-09 15:08:12 +00003041
John McCallefdb83e2010-05-07 21:00:08 +00003042 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003043 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003044
Richard Smith1aa0be82012-03-03 22:46:17 +00003045 bool Success(const APValue &V, const Expr *E) {
3046 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003047 return true;
3048 }
Richard Smith51201882011-12-30 21:15:51 +00003049 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003050 return Success((Expr*)0);
3051 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003052
John McCallefdb83e2010-05-07 21:00:08 +00003053 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003054 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003055 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003056 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003057 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003058 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3059 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003060 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003061 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003062 bool VisitCallExpr(const CallExpr *E);
3063 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003064 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003065 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003066 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003067 }
Richard Smith180f4792011-11-10 06:34:14 +00003068 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3069 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003070 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003071 Result = *Info.CurrentCall->This;
3072 return true;
3073 }
John McCall56ca35d2011-02-17 10:25:35 +00003074
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003075 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003076};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003077} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003078
John McCallefdb83e2010-05-07 21:00:08 +00003079static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003080 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003081 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003082}
3083
John McCallefdb83e2010-05-07 21:00:08 +00003084bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003085 if (E->getOpcode() != BO_Add &&
3086 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003087 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003088
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003089 const Expr *PExp = E->getLHS();
3090 const Expr *IExp = E->getRHS();
3091 if (IExp->getType()->isPointerType())
3092 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Richard Smith745f5142012-01-27 01:14:48 +00003094 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3095 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003096 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003097
John McCallefdb83e2010-05-07 21:00:08 +00003098 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003099 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003100 return false;
3101 int64_t AdditionalOffset
3102 = Offset.isSigned() ? Offset.getSExtValue()
3103 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003104 if (E->getOpcode() == BO_Sub)
3105 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003106
Richard Smith180f4792011-11-10 06:34:14 +00003107 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003108 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3109 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003110}
Eli Friedman4efaa272008-11-12 09:44:48 +00003111
John McCallefdb83e2010-05-07 21:00:08 +00003112bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3113 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003114}
Mike Stump1eb44332009-09-09 15:08:12 +00003115
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003116bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3117 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003118
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003119 switch (E->getCastKind()) {
3120 default:
3121 break;
3122
John McCall2de56d12010-08-25 11:45:40 +00003123 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003124 case CK_CPointerToObjCPointerCast:
3125 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003126 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003127 if (!Visit(SubExpr))
3128 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003129 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3130 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3131 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003132 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003133 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003134 if (SubExpr->getType()->isVoidPointerType())
3135 CCEDiag(E, diag::note_constexpr_invalid_cast)
3136 << 3 << SubExpr->getType();
3137 else
3138 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3139 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003140 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003141
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003142 case CK_DerivedToBase:
3143 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003144 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003145 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003146 if (!Result.Base && Result.Offset.isZero())
3147 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003148
Richard Smith180f4792011-11-10 06:34:14 +00003149 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003150 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003151 QualType Type =
3152 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003153
Richard Smith180f4792011-11-10 06:34:14 +00003154 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003155 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003156 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3157 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003159 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003160 }
3161
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003162 return true;
3163 }
3164
Richard Smithe24f5fc2011-11-17 22:56:20 +00003165 case CK_BaseToDerived:
3166 if (!Visit(E->getSubExpr()))
3167 return false;
3168 if (!Result.Base && Result.Offset.isZero())
3169 return true;
3170 return HandleBaseToDerivedCast(Info, E, Result);
3171
Richard Smith47a1eed2011-10-29 20:57:55 +00003172 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003173 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003174
John McCall2de56d12010-08-25 11:45:40 +00003175 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003176 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3177
Richard Smith1aa0be82012-03-03 22:46:17 +00003178 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003179 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003180 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003181
John McCallefdb83e2010-05-07 21:00:08 +00003182 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003183 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3184 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003185 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003186 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003187 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003188 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003189 return true;
3190 } else {
3191 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003192 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003193 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003194 }
3195 }
John McCall2de56d12010-08-25 11:45:40 +00003196 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003197 if (SubExpr->isGLValue()) {
3198 if (!EvaluateLValue(SubExpr, Result, Info))
3199 return false;
3200 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003201 Result.set(SubExpr, Info.CurrentCall->Index);
3202 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3203 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003204 return false;
3205 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003206 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003207 if (const ConstantArrayType *CAT
3208 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3209 Result.addArray(Info, E, CAT);
3210 else
3211 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003212 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003213
John McCall2de56d12010-08-25 11:45:40 +00003214 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003215 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003216 }
3217
Richard Smithc49bd112011-10-28 17:51:58 +00003218 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003219}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003220
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003221bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003222 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003223 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003224
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003225 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003226}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003227
3228//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003229// Member Pointer Evaluation
3230//===----------------------------------------------------------------------===//
3231
3232namespace {
3233class MemberPointerExprEvaluator
3234 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3235 MemberPtr &Result;
3236
3237 bool Success(const ValueDecl *D) {
3238 Result = MemberPtr(D);
3239 return true;
3240 }
3241public:
3242
3243 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3244 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3245
Richard Smith1aa0be82012-03-03 22:46:17 +00003246 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003247 Result.setFrom(V);
3248 return true;
3249 }
Richard Smith51201882011-12-30 21:15:51 +00003250 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003251 return Success((const ValueDecl*)0);
3252 }
3253
3254 bool VisitCastExpr(const CastExpr *E);
3255 bool VisitUnaryAddrOf(const UnaryOperator *E);
3256};
3257} // end anonymous namespace
3258
3259static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3260 EvalInfo &Info) {
3261 assert(E->isRValue() && E->getType()->isMemberPointerType());
3262 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3263}
3264
3265bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3266 switch (E->getCastKind()) {
3267 default:
3268 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3269
3270 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003271 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003272
3273 case CK_BaseToDerivedMemberPointer: {
3274 if (!Visit(E->getSubExpr()))
3275 return false;
3276 if (E->path_empty())
3277 return true;
3278 // Base-to-derived member pointer casts store the path in derived-to-base
3279 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3280 // the wrong end of the derived->base arc, so stagger the path by one class.
3281 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3282 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3283 PathI != PathE; ++PathI) {
3284 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3285 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3286 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003287 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003288 }
3289 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3290 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003291 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003292 return true;
3293 }
3294
3295 case CK_DerivedToBaseMemberPointer:
3296 if (!Visit(E->getSubExpr()))
3297 return false;
3298 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3299 PathE = E->path_end(); PathI != PathE; ++PathI) {
3300 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3301 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3302 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003303 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003304 }
3305 return true;
3306 }
3307}
3308
3309bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3310 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3311 // member can be formed.
3312 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3313}
3314
3315//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003316// Record Evaluation
3317//===----------------------------------------------------------------------===//
3318
3319namespace {
3320 class RecordExprEvaluator
3321 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3322 const LValue &This;
3323 APValue &Result;
3324 public:
3325
3326 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3327 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3328
Richard Smith1aa0be82012-03-03 22:46:17 +00003329 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003330 Result = V;
3331 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003332 }
Richard Smith51201882011-12-30 21:15:51 +00003333 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003334
Richard Smith59efe262011-11-11 04:05:33 +00003335 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003336 bool VisitInitListExpr(const InitListExpr *E);
3337 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3338 };
3339}
3340
Richard Smith51201882011-12-30 21:15:51 +00003341/// Perform zero-initialization on an object of non-union class type.
3342/// C++11 [dcl.init]p5:
3343/// To zero-initialize an object or reference of type T means:
3344/// [...]
3345/// -- if T is a (possibly cv-qualified) non-union class type,
3346/// each non-static data member and each base-class subobject is
3347/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003348static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3349 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003350 const LValue &This, APValue &Result) {
3351 assert(!RD->isUnion() && "Expected non-union class type");
3352 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3353 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3354 std::distance(RD->field_begin(), RD->field_end()));
3355
3356 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3357
3358 if (CD) {
3359 unsigned Index = 0;
3360 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003361 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003362 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3363 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003364 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3365 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003366 Result.getStructBase(Index)))
3367 return false;
3368 }
3369 }
3370
Richard Smithb4e85ed2012-01-06 16:39:00 +00003371 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3372 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003373 // -- if T is a reference type, no initialization is performed.
3374 if ((*I)->getType()->isReferenceType())
3375 continue;
3376
3377 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003378 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003379
3380 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003381 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003382 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3383 return false;
3384 }
3385
3386 return true;
3387}
3388
3389bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3390 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3391 if (RD->isUnion()) {
3392 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3393 // object's first non-static named data member is zero-initialized
3394 RecordDecl::field_iterator I = RD->field_begin();
3395 if (I == RD->field_end()) {
3396 Result = APValue((const FieldDecl*)0);
3397 return true;
3398 }
3399
3400 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003401 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003402 Result = APValue(*I);
3403 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003404 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003405 }
3406
Richard Smithce582fe2012-02-17 00:44:16 +00003407 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3408 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3409 return false;
3410 }
3411
Richard Smithb4e85ed2012-01-06 16:39:00 +00003412 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003413}
3414
Richard Smith59efe262011-11-11 04:05:33 +00003415bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3416 switch (E->getCastKind()) {
3417 default:
3418 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3419
3420 case CK_ConstructorConversion:
3421 return Visit(E->getSubExpr());
3422
3423 case CK_DerivedToBase:
3424 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003425 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003426 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003427 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003428 if (!DerivedObject.isStruct())
3429 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003430
3431 // Derived-to-base rvalue conversion: just slice off the derived part.
3432 APValue *Value = &DerivedObject;
3433 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3434 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3435 PathE = E->path_end(); PathI != PathE; ++PathI) {
3436 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3437 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3438 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3439 RD = Base;
3440 }
3441 Result = *Value;
3442 return true;
3443 }
3444 }
3445}
3446
Richard Smith180f4792011-11-10 06:34:14 +00003447bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003448 // Cannot constant-evaluate std::initializer_list inits.
3449 if (E->initializesStdInitializerList())
3450 return false;
3451
Richard Smith180f4792011-11-10 06:34:14 +00003452 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3453 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3454
3455 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003456 const FieldDecl *Field = E->getInitializedFieldInUnion();
3457 Result = APValue(Field);
3458 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003459 return true;
Richard Smithec789162012-01-12 18:54:33 +00003460
3461 // If the initializer list for a union does not contain any elements, the
3462 // first element of the union is value-initialized.
3463 ImplicitValueInitExpr VIE(Field->getType());
3464 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3465
Richard Smith180f4792011-11-10 06:34:14 +00003466 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003467 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003468 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003469 }
3470
3471 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3472 "initializer list for class with base classes");
3473 Result = APValue(APValue::UninitStruct(), 0,
3474 std::distance(RD->field_begin(), RD->field_end()));
3475 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003476 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003477 for (RecordDecl::field_iterator Field = RD->field_begin(),
3478 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3479 // Anonymous bit-fields are not considered members of the class for
3480 // purposes of aggregate initialization.
3481 if (Field->isUnnamedBitfield())
3482 continue;
3483
3484 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003485
Richard Smith745f5142012-01-27 01:14:48 +00003486 bool HaveInit = ElementNo < E->getNumInits();
3487
3488 // FIXME: Diagnostics here should point to the end of the initializer
3489 // list, not the start.
3490 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3491 *Field, &Layout);
3492
3493 // Perform an implicit value-initialization for members beyond the end of
3494 // the initializer list.
3495 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3496
Richard Smith83587db2012-02-15 02:18:13 +00003497 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003498 Result.getStructField((*Field)->getFieldIndex()),
3499 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3500 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003501 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003502 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003503 }
3504 }
3505
Richard Smith745f5142012-01-27 01:14:48 +00003506 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003507}
3508
3509bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3510 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003511 bool ZeroInit = E->requiresZeroInitialization();
3512 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003513 // If we've already performed zero-initialization, we're already done.
3514 if (!Result.isUninit())
3515 return true;
3516
Richard Smith51201882011-12-30 21:15:51 +00003517 if (ZeroInit)
3518 return ZeroInitialization(E);
3519
Richard Smith61802452011-12-22 02:22:31 +00003520 const CXXRecordDecl *RD = FD->getParent();
3521 if (RD->isUnion())
3522 Result = APValue((FieldDecl*)0);
3523 else
3524 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3525 std::distance(RD->field_begin(), RD->field_end()));
3526 return true;
3527 }
3528
Richard Smith180f4792011-11-10 06:34:14 +00003529 const FunctionDecl *Definition = 0;
3530 FD->getBody(Definition);
3531
Richard Smithc1c5f272011-12-13 06:39:58 +00003532 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3533 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003534
Richard Smith610a60c2012-01-10 04:32:03 +00003535 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003536 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003537 if (const MaterializeTemporaryExpr *ME
3538 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3539 return Visit(ME->GetTemporaryExpr());
3540
Richard Smith51201882011-12-30 21:15:51 +00003541 if (ZeroInit && !ZeroInitialization(E))
3542 return false;
3543
Richard Smith180f4792011-11-10 06:34:14 +00003544 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003545 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003546 cast<CXXConstructorDecl>(Definition), Info,
3547 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003548}
3549
3550static bool EvaluateRecord(const Expr *E, const LValue &This,
3551 APValue &Result, EvalInfo &Info) {
3552 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003553 "can't evaluate expression as a record rvalue");
3554 return RecordExprEvaluator(Info, This, Result).Visit(E);
3555}
3556
3557//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003558// Temporary Evaluation
3559//
3560// Temporaries are represented in the AST as rvalues, but generally behave like
3561// lvalues. The full-object of which the temporary is a subobject is implicitly
3562// materialized so that a reference can bind to it.
3563//===----------------------------------------------------------------------===//
3564namespace {
3565class TemporaryExprEvaluator
3566 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3567public:
3568 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3569 LValueExprEvaluatorBaseTy(Info, Result) {}
3570
3571 /// Visit an expression which constructs the value of this temporary.
3572 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003573 Result.set(E, Info.CurrentCall->Index);
3574 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003575 }
3576
3577 bool VisitCastExpr(const CastExpr *E) {
3578 switch (E->getCastKind()) {
3579 default:
3580 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3581
3582 case CK_ConstructorConversion:
3583 return VisitConstructExpr(E->getSubExpr());
3584 }
3585 }
3586 bool VisitInitListExpr(const InitListExpr *E) {
3587 return VisitConstructExpr(E);
3588 }
3589 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3590 return VisitConstructExpr(E);
3591 }
3592 bool VisitCallExpr(const CallExpr *E) {
3593 return VisitConstructExpr(E);
3594 }
3595};
3596} // end anonymous namespace
3597
3598/// Evaluate an expression of record type as a temporary.
3599static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003600 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003601 return TemporaryExprEvaluator(Info, Result).Visit(E);
3602}
3603
3604//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003605// Vector Evaluation
3606//===----------------------------------------------------------------------===//
3607
3608namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003609 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003610 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3611 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003612 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003613
Richard Smith07fc6572011-10-22 21:10:00 +00003614 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3615 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Richard Smith07fc6572011-10-22 21:10:00 +00003617 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3618 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3619 // FIXME: remove this APValue copy.
3620 Result = APValue(V.data(), V.size());
3621 return true;
3622 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003623 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003624 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003625 Result = V;
3626 return true;
3627 }
Richard Smith51201882011-12-30 21:15:51 +00003628 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003629
Richard Smith07fc6572011-10-22 21:10:00 +00003630 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003631 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003632 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003633 bool VisitInitListExpr(const InitListExpr *E);
3634 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003635 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003636 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003637 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003638 };
3639} // end anonymous namespace
3640
3641static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003642 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003643 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003644}
3645
Richard Smith07fc6572011-10-22 21:10:00 +00003646bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3647 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003648 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Richard Smithd62ca372011-12-06 22:44:34 +00003650 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003651 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003652
Eli Friedman46a52322011-03-25 00:43:55 +00003653 switch (E->getCastKind()) {
3654 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003655 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003656 if (SETy->isIntegerType()) {
3657 APSInt IntResult;
3658 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003659 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003660 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003661 } else if (SETy->isRealFloatingType()) {
3662 APFloat F(0.0);
3663 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003664 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003665 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003666 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003667 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003668 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003669
3670 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003671 SmallVector<APValue, 4> Elts(NElts, Val);
3672 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003673 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003674 case CK_BitCast: {
3675 // Evaluate the operand into an APInt we can extract from.
3676 llvm::APInt SValInt;
3677 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3678 return false;
3679 // Extract the elements
3680 QualType EltTy = VTy->getElementType();
3681 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3682 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3683 SmallVector<APValue, 4> Elts;
3684 if (EltTy->isRealFloatingType()) {
3685 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3686 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3687 unsigned FloatEltSize = EltSize;
3688 if (&Sem == &APFloat::x87DoubleExtended)
3689 FloatEltSize = 80;
3690 for (unsigned i = 0; i < NElts; i++) {
3691 llvm::APInt Elt;
3692 if (BigEndian)
3693 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3694 else
3695 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3696 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3697 }
3698 } else if (EltTy->isIntegerType()) {
3699 for (unsigned i = 0; i < NElts; i++) {
3700 llvm::APInt Elt;
3701 if (BigEndian)
3702 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3703 else
3704 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3705 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3706 }
3707 } else {
3708 return Error(E);
3709 }
3710 return Success(Elts, E);
3711 }
Eli Friedman46a52322011-03-25 00:43:55 +00003712 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003713 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003714 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003715}
3716
Richard Smith07fc6572011-10-22 21:10:00 +00003717bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003718VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003719 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003720 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003721 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003722
Nate Begeman59b5da62009-01-18 03:20:47 +00003723 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003724 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003725
Eli Friedman3edd5a92012-01-03 23:24:20 +00003726 // The number of initializers can be less than the number of
3727 // vector elements. For OpenCL, this can be due to nested vector
3728 // initialization. For GCC compatibility, missing trailing elements
3729 // should be initialized with zeroes.
3730 unsigned CountInits = 0, CountElts = 0;
3731 while (CountElts < NumElements) {
3732 // Handle nested vector initialization.
3733 if (CountInits < NumInits
3734 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3735 APValue v;
3736 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3737 return Error(E);
3738 unsigned vlen = v.getVectorLength();
3739 for (unsigned j = 0; j < vlen; j++)
3740 Elements.push_back(v.getVectorElt(j));
3741 CountElts += vlen;
3742 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003743 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003744 if (CountInits < NumInits) {
3745 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3746 return Error(E);
3747 } else // trailing integer zero.
3748 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3749 Elements.push_back(APValue(sInt));
3750 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003751 } else {
3752 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003753 if (CountInits < NumInits) {
3754 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3755 return Error(E);
3756 } else // trailing float zero.
3757 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3758 Elements.push_back(APValue(f));
3759 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003760 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003761 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003762 }
Richard Smith07fc6572011-10-22 21:10:00 +00003763 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003764}
3765
Richard Smith07fc6572011-10-22 21:10:00 +00003766bool
Richard Smith51201882011-12-30 21:15:51 +00003767VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003768 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003769 QualType EltTy = VT->getElementType();
3770 APValue ZeroElement;
3771 if (EltTy->isIntegerType())
3772 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3773 else
3774 ZeroElement =
3775 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3776
Chris Lattner5f9e2722011-07-23 10:55:15 +00003777 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003778 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003779}
3780
Richard Smith07fc6572011-10-22 21:10:00 +00003781bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003782 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003783 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003784}
3785
Nate Begeman59b5da62009-01-18 03:20:47 +00003786//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003787// Array Evaluation
3788//===----------------------------------------------------------------------===//
3789
3790namespace {
3791 class ArrayExprEvaluator
3792 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003793 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003794 APValue &Result;
3795 public:
3796
Richard Smith180f4792011-11-10 06:34:14 +00003797 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3798 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003799
3800 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003801 assert((V.isArray() || V.isLValue()) &&
3802 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003803 Result = V;
3804 return true;
3805 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003806
Richard Smith51201882011-12-30 21:15:51 +00003807 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003808 const ConstantArrayType *CAT =
3809 Info.Ctx.getAsConstantArrayType(E->getType());
3810 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003811 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003812
3813 Result = APValue(APValue::UninitArray(), 0,
3814 CAT->getSize().getZExtValue());
3815 if (!Result.hasArrayFiller()) return true;
3816
Richard Smith51201882011-12-30 21:15:51 +00003817 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003818 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003819 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003820 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003821 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003822 }
3823
Richard Smithcc5d4f62011-11-07 09:22:26 +00003824 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003825 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003826 };
3827} // end anonymous namespace
3828
Richard Smith180f4792011-11-10 06:34:14 +00003829static bool EvaluateArray(const Expr *E, const LValue &This,
3830 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003831 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003832 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003833}
3834
3835bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3836 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3837 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003838 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839
Richard Smith974c5f92011-12-22 01:07:19 +00003840 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3841 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003842 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003843 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3844 LValue LV;
3845 if (!EvaluateLValue(E->getInit(0), LV, Info))
3846 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003847 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003848 LV.moveInto(Val);
3849 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003850 }
3851
Richard Smith745f5142012-01-27 01:14:48 +00003852 bool Success = true;
3853
Richard Smithcc5d4f62011-11-07 09:22:26 +00003854 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3855 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003856 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003857 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003858 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003859 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003860 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003861 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3862 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003863 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3864 CAT->getElementType(), 1)) {
3865 if (!Info.keepEvaluatingAfterFailure())
3866 return false;
3867 Success = false;
3868 }
Richard Smith180f4792011-11-10 06:34:14 +00003869 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003870
Richard Smith745f5142012-01-27 01:14:48 +00003871 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003872 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003873 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3874 // but sometimes does:
3875 // struct S { constexpr S() : p(&p) {} void *p; };
3876 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003877 return EvaluateInPlace(Result.getArrayFiller(), Info,
3878 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003879}
3880
Richard Smithe24f5fc2011-11-17 22:56:20 +00003881bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3882 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3883 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003884 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003885
Richard Smithec789162012-01-12 18:54:33 +00003886 bool HadZeroInit = !Result.isUninit();
3887 if (!HadZeroInit)
3888 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889 if (!Result.hasArrayFiller())
3890 return true;
3891
3892 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003893
Richard Smith51201882011-12-30 21:15:51 +00003894 bool ZeroInit = E->requiresZeroInitialization();
3895 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003896 if (HadZeroInit)
3897 return true;
3898
Richard Smith51201882011-12-30 21:15:51 +00003899 if (ZeroInit) {
3900 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003901 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003902 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003903 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003904 }
3905
Richard Smith61802452011-12-22 02:22:31 +00003906 const CXXRecordDecl *RD = FD->getParent();
3907 if (RD->isUnion())
3908 Result.getArrayFiller() = APValue((FieldDecl*)0);
3909 else
3910 Result.getArrayFiller() =
3911 APValue(APValue::UninitStruct(), RD->getNumBases(),
3912 std::distance(RD->field_begin(), RD->field_end()));
3913 return true;
3914 }
3915
Richard Smithe24f5fc2011-11-17 22:56:20 +00003916 const FunctionDecl *Definition = 0;
3917 FD->getBody(Definition);
3918
Richard Smithc1c5f272011-12-13 06:39:58 +00003919 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3920 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003921
3922 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3923 // but sometimes does:
3924 // struct S { constexpr S() : p(&p) {} void *p; };
3925 // S s[10];
3926 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003927 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003928
Richard Smithec789162012-01-12 18:54:33 +00003929 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003930 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003931 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003932 return false;
3933 }
3934
Richard Smithe24f5fc2011-11-17 22:56:20 +00003935 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003936 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003937 cast<CXXConstructorDecl>(Definition),
3938 Info, Result.getArrayFiller());
3939}
3940
Richard Smithcc5d4f62011-11-07 09:22:26 +00003941//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003942// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003943//
3944// As a GNU extension, we support casting pointers to sufficiently-wide integer
3945// types and back in constant folding. Integer values are thus represented
3946// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003947//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003948
3949namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003950class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003951 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003952 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003953public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003954 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003955 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003956
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003957 bool Success(const llvm::APSInt &SI, const Expr *E) {
3958 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003959 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003960 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003961 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003962 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003963 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003964 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003965 return true;
3966 }
3967
Daniel Dunbar131eb432009-02-19 09:06:44 +00003968 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003969 assert(E->getType()->isIntegralOrEnumerationType() &&
3970 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003971 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003972 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003973 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003974 Result.getInt().setIsUnsigned(
3975 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003976 return true;
3977 }
3978
3979 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003980 assert(E->getType()->isIntegralOrEnumerationType() &&
3981 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003982 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003983 return true;
3984 }
3985
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003986 bool Success(CharUnits Size, const Expr *E) {
3987 return Success(Size.getQuantity(), E);
3988 }
3989
Richard Smith1aa0be82012-03-03 22:46:17 +00003990 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003991 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003992 Result = V;
3993 return true;
3994 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003995 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003996 }
Mike Stump1eb44332009-09-09 15:08:12 +00003997
Richard Smith51201882011-12-30 21:15:51 +00003998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003999
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +00004000 // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4001 bool Visit(const Expr *E) {
4002 SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4003 Info.IntExprEvaluatorDepth+1);
4004 const unsigned MaxDepth = 512;
4005 if (Depth.get() > MaxDepth) {
4006 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4007 diag::err_intexpr_depth_limit_exceeded);
4008 return false;
4009 }
4010
4011 return ExprEvaluatorBaseTy::Visit(E);
4012 }
4013
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004014 //===--------------------------------------------------------------------===//
4015 // Visitor Methods
4016 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004017
Chris Lattner4c4867e2008-07-12 00:38:25 +00004018 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004019 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004020 }
4021 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004022 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004023 }
Eli Friedman04309752009-11-24 05:28:59 +00004024
4025 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4026 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004027 if (CheckReferencedDecl(E, E->getDecl()))
4028 return true;
4029
4030 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004031 }
4032 bool VisitMemberExpr(const MemberExpr *E) {
4033 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004034 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004035 return true;
4036 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004037
4038 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004039 }
4040
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004041 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004042 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004043 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004044 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004046 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004047 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004048
Anders Carlsson3068d112008-11-16 19:01:22 +00004049 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004050 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004051 }
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004053 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4054 return Success(E->getValue(), E);
4055 }
4056
Richard Smithf10d9172011-10-11 21:43:33 +00004057 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004058 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004059 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004060 }
4061
Sebastian Redl64b45f72009-01-05 20:52:13 +00004062 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004063 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004064 }
4065
Francois Pichet6ad6f282010-12-07 00:08:36 +00004066 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4067 return Success(E->getValue(), E);
4068 }
4069
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004070 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4071 return Success(E->getValue(), E);
4072 }
4073
John Wiegley21ff2e52011-04-28 00:16:57 +00004074 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4075 return Success(E->getValue(), E);
4076 }
4077
John Wiegley55262202011-04-25 06:54:41 +00004078 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4079 return Success(E->getValue(), E);
4080 }
4081
Eli Friedman722c7172009-02-28 03:59:05 +00004082 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004083 bool VisitUnaryImag(const UnaryOperator *E);
4084
Sebastian Redl295995c2010-09-10 20:55:47 +00004085 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004086 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004087
Chris Lattnerfcee0012008-07-11 21:24:13 +00004088private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004089 CharUnits GetAlignOfExpr(const Expr *E);
4090 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004091 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004092 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004093 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004094};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004095} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004096
Richard Smithc49bd112011-10-28 17:51:58 +00004097/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4098/// produce either the integer value or a pointer.
4099///
4100/// GCC has a heinous extension which folds casts between pointer types and
4101/// pointer-sized integral types. We support this by allowing the evaluation of
4102/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4103/// Some simple arithmetic on such values is supported (they are treated much
4104/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004105static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004106 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004107 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004108 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004109}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004110
Richard Smithf48fdb02011-12-09 22:58:01 +00004111static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004112 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004113 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004114 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004115 if (!Val.isInt()) {
4116 // FIXME: It would be better to produce the diagnostic for casting
4117 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004118 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004119 return false;
4120 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004121 Result = Val.getInt();
4122 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004123}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004124
Richard Smithf48fdb02011-12-09 22:58:01 +00004125/// Check whether the given declaration can be directly converted to an integral
4126/// rvalue. If not, no diagnostic is produced; there are other things we can
4127/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004128bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004129 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004130 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004131 // Check for signedness/width mismatches between E type and ECD value.
4132 bool SameSign = (ECD->getInitVal().isSigned()
4133 == E->getType()->isSignedIntegerOrEnumerationType());
4134 bool SameWidth = (ECD->getInitVal().getBitWidth()
4135 == Info.Ctx.getIntWidth(E->getType()));
4136 if (SameSign && SameWidth)
4137 return Success(ECD->getInitVal(), E);
4138 else {
4139 // Get rid of mismatch (otherwise Success assertions will fail)
4140 // by computing a new value matching the type of E.
4141 llvm::APSInt Val = ECD->getInitVal();
4142 if (!SameSign)
4143 Val.setIsSigned(!ECD->getInitVal().isSigned());
4144 if (!SameWidth)
4145 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4146 return Success(Val, E);
4147 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004148 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004149 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004150}
4151
Chris Lattnera4d55d82008-10-06 06:40:35 +00004152/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4153/// as GCC.
4154static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4155 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004156 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004157 enum gcc_type_class {
4158 no_type_class = -1,
4159 void_type_class, integer_type_class, char_type_class,
4160 enumeral_type_class, boolean_type_class,
4161 pointer_type_class, reference_type_class, offset_type_class,
4162 real_type_class, complex_type_class,
4163 function_type_class, method_type_class,
4164 record_type_class, union_type_class,
4165 array_type_class, string_type_class,
4166 lang_type_class
4167 };
Mike Stump1eb44332009-09-09 15:08:12 +00004168
4169 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004170 // ideal, however it is what gcc does.
4171 if (E->getNumArgs() == 0)
4172 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004173
Chris Lattnera4d55d82008-10-06 06:40:35 +00004174 QualType ArgTy = E->getArg(0)->getType();
4175 if (ArgTy->isVoidType())
4176 return void_type_class;
4177 else if (ArgTy->isEnumeralType())
4178 return enumeral_type_class;
4179 else if (ArgTy->isBooleanType())
4180 return boolean_type_class;
4181 else if (ArgTy->isCharType())
4182 return string_type_class; // gcc doesn't appear to use char_type_class
4183 else if (ArgTy->isIntegerType())
4184 return integer_type_class;
4185 else if (ArgTy->isPointerType())
4186 return pointer_type_class;
4187 else if (ArgTy->isReferenceType())
4188 return reference_type_class;
4189 else if (ArgTy->isRealType())
4190 return real_type_class;
4191 else if (ArgTy->isComplexType())
4192 return complex_type_class;
4193 else if (ArgTy->isFunctionType())
4194 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004195 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004196 return record_type_class;
4197 else if (ArgTy->isUnionType())
4198 return union_type_class;
4199 else if (ArgTy->isArrayType())
4200 return array_type_class;
4201 else if (ArgTy->isUnionType())
4202 return union_type_class;
4203 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004204 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004205}
4206
Richard Smith80d4b552011-12-28 19:48:30 +00004207/// EvaluateBuiltinConstantPForLValue - Determine the result of
4208/// __builtin_constant_p when applied to the given lvalue.
4209///
4210/// An lvalue is only "constant" if it is a pointer or reference to the first
4211/// character of a string literal.
4212template<typename LValue>
4213static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4214 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4215 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4216}
4217
4218/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4219/// GCC as we can manage.
4220static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4221 QualType ArgType = Arg->getType();
4222
4223 // __builtin_constant_p always has one operand. The rules which gcc follows
4224 // are not precisely documented, but are as follows:
4225 //
4226 // - If the operand is of integral, floating, complex or enumeration type,
4227 // and can be folded to a known value of that type, it returns 1.
4228 // - If the operand and can be folded to a pointer to the first character
4229 // of a string literal (or such a pointer cast to an integral type), it
4230 // returns 1.
4231 //
4232 // Otherwise, it returns 0.
4233 //
4234 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4235 // its support for this does not currently work.
4236 if (ArgType->isIntegralOrEnumerationType()) {
4237 Expr::EvalResult Result;
4238 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4239 return false;
4240
4241 APValue &V = Result.Val;
4242 if (V.getKind() == APValue::Int)
4243 return true;
4244
4245 return EvaluateBuiltinConstantPForLValue(V);
4246 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4247 return Arg->isEvaluatable(Ctx);
4248 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4249 LValue LV;
4250 Expr::EvalStatus Status;
4251 EvalInfo Info(Ctx, Status);
4252 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4253 : EvaluatePointer(Arg, LV, Info)) &&
4254 !Status.HasSideEffects)
4255 return EvaluateBuiltinConstantPForLValue(LV);
4256 }
4257
4258 // Anything else isn't considered to be sufficiently constant.
4259 return false;
4260}
4261
John McCall42c8f872010-05-10 23:27:23 +00004262/// Retrieves the "underlying object type" of the given expression,
4263/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004264QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4265 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4266 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004267 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004268 } else if (const Expr *E = B.get<const Expr*>()) {
4269 if (isa<CompoundLiteralExpr>(E))
4270 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004271 }
4272
4273 return QualType();
4274}
4275
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004276bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004277 // TODO: Perhaps we should let LLVM lower this?
4278 LValue Base;
4279 if (!EvaluatePointer(E->getArg(0), Base, Info))
4280 return false;
4281
4282 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004283 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004284
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004285 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004286 if (T.isNull() ||
4287 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004288 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004289 T->isVariablyModifiedType() ||
4290 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004291 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004292
4293 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4294 CharUnits Offset = Base.getLValueOffset();
4295
4296 if (!Offset.isNegative() && Offset <= Size)
4297 Size -= Offset;
4298 else
4299 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004300 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004301}
4302
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004303bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004304 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004305 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004306 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004307
4308 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004309 if (TryEvaluateBuiltinObjectSize(E))
4310 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004311
Eric Christopherb2aaf512010-01-19 22:58:35 +00004312 // If evaluating the argument has side-effects we can't determine
4313 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004314 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004315 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004316 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004317 return Success(0, E);
4318 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004319
Richard Smithf48fdb02011-12-09 22:58:01 +00004320 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004321 }
4322
Chris Lattner019f4e82008-10-06 05:28:25 +00004323 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004324 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004325
Richard Smith80d4b552011-12-28 19:48:30 +00004326 case Builtin::BI__builtin_constant_p:
4327 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004328
Chris Lattner21fb98e2009-09-23 06:06:36 +00004329 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004330 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004331 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004332 return Success(Operand, E);
4333 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004334
4335 case Builtin::BI__builtin_expect:
4336 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004337
Douglas Gregor5726d402010-09-10 06:27:15 +00004338 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004339 // A call to strlen is not a constant expression.
4340 if (Info.getLangOpts().CPlusPlus0x)
4341 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4342 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4343 else
4344 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4345 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004346 case Builtin::BI__builtin_strlen:
4347 // As an extension, we support strlen() and __builtin_strlen() as constant
4348 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004349 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004350 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4351 // The string literal may have embedded null characters. Find the first
4352 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004353 StringRef Str = S->getString();
4354 StringRef::size_type Pos = Str.find(0);
4355 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004356 Str = Str.substr(0, Pos);
4357
4358 return Success(Str.size(), E);
4359 }
4360
Richard Smithf48fdb02011-12-09 22:58:01 +00004361 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004362
4363 case Builtin::BI__atomic_is_lock_free: {
4364 APSInt SizeVal;
4365 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4366 return false;
4367
4368 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4369 // of two less than the maximum inline atomic width, we know it is
4370 // lock-free. If the size isn't a power of two, or greater than the
4371 // maximum alignment where we promote atomics, we know it is not lock-free
4372 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4373 // the answer can only be determined at runtime; for example, 16-byte
4374 // atomics have lock-free implementations on some, but not all,
4375 // x86-64 processors.
4376
4377 // Check power-of-two.
4378 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4379 if (!Size.isPowerOfTwo())
4380#if 0
4381 // FIXME: Suppress this folding until the ABI for the promotion width
4382 // settles.
4383 return Success(0, E);
4384#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004385 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004386#endif
4387
4388#if 0
4389 // Check against promotion width.
4390 // FIXME: Suppress this folding until the ABI for the promotion width
4391 // settles.
4392 unsigned PromoteWidthBits =
4393 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4394 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4395 return Success(0, E);
4396#endif
4397
4398 // Check against inlining width.
4399 unsigned InlineWidthBits =
4400 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4401 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4402 return Success(1, E);
4403
Richard Smithf48fdb02011-12-09 22:58:01 +00004404 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004405 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004406 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004407}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004408
Richard Smith625b8072011-10-31 01:37:14 +00004409static bool HasSameBase(const LValue &A, const LValue &B) {
4410 if (!A.getLValueBase())
4411 return !B.getLValueBase();
4412 if (!B.getLValueBase())
4413 return false;
4414
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004415 if (A.getLValueBase().getOpaqueValue() !=
4416 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004417 const Decl *ADecl = GetLValueBaseDecl(A);
4418 if (!ADecl)
4419 return false;
4420 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004421 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004422 return false;
4423 }
4424
4425 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004426 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004427}
4428
Richard Smith7b48a292012-02-01 05:53:12 +00004429/// Perform the given integer operation, which is known to need at most BitWidth
4430/// bits, and check for overflow in the original type (if that type was not an
4431/// unsigned type).
4432template<typename Operation>
4433static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4434 const APSInt &LHS, const APSInt &RHS,
4435 unsigned BitWidth, Operation Op) {
4436 if (LHS.isUnsigned())
4437 return Op(LHS, RHS);
4438
4439 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4440 APSInt Result = Value.trunc(LHS.getBitWidth());
4441 if (Result.extend(BitWidth) != Value)
4442 HandleOverflow(Info, E, Value, E->getType());
4443 return Result;
4444}
4445
Chris Lattnerb542afe2008-07-11 19:10:17 +00004446bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004447 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004448 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004449
John McCall2de56d12010-08-25 11:45:40 +00004450 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004451 VisitIgnoredValue(E->getLHS());
4452 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004453 }
4454
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004455 if (E->isLogicalOp()) {
4456 // These need to be handled specially because the operands aren't
4457 // necessarily integral nor evaluated.
4458 bool lhsResult, rhsResult;
4459
4460 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4461 // We were able to evaluate the LHS, see if we can get away with not
4462 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4463 if (lhsResult == (E->getOpcode() == BO_LOr))
4464 return Success(lhsResult, E);
4465
4466 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4467 if (E->getOpcode() == BO_LOr)
4468 return Success(lhsResult || rhsResult, E);
4469 else
4470 return Success(lhsResult && rhsResult, E);
4471 }
4472 } else {
4473 // Since we weren't able to evaluate the left hand side, it
4474 // must have had side effects.
4475 Info.EvalStatus.HasSideEffects = true;
4476
4477 // Suppress diagnostics from this arm.
4478 SpeculativeEvaluationRAII Speculative(Info);
4479 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4480 // We can't evaluate the LHS; however, sometimes the result
4481 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4482 if (rhsResult == (E->getOpcode() == BO_LOr))
4483 return Success(rhsResult, E);
4484 }
4485 }
4486
4487 return false;
4488 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004489
Anders Carlsson286f85e2008-11-16 07:17:21 +00004490 QualType LHSTy = E->getLHS()->getType();
4491 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004492
4493 if (LHSTy->isAnyComplexType()) {
4494 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004495 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004496
Richard Smith745f5142012-01-27 01:14:48 +00004497 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4498 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004499 return false;
4500
Richard Smith745f5142012-01-27 01:14:48 +00004501 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004502 return false;
4503
4504 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004505 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004506 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004507 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004508 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4509
John McCall2de56d12010-08-25 11:45:40 +00004510 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004511 return Success((CR_r == APFloat::cmpEqual &&
4512 CR_i == APFloat::cmpEqual), E);
4513 else {
John McCall2de56d12010-08-25 11:45:40 +00004514 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004515 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004516 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004517 CR_r == APFloat::cmpLessThan ||
4518 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004519 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004520 CR_i == APFloat::cmpLessThan ||
4521 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004522 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004523 } else {
John McCall2de56d12010-08-25 11:45:40 +00004524 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004525 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4526 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4527 else {
John McCall2de56d12010-08-25 11:45:40 +00004528 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004529 "Invalid compex comparison.");
4530 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4531 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4532 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004533 }
4534 }
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Anders Carlsson286f85e2008-11-16 07:17:21 +00004536 if (LHSTy->isRealFloatingType() &&
4537 RHSTy->isRealFloatingType()) {
4538 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004539
Richard Smith745f5142012-01-27 01:14:48 +00004540 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4541 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004542 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004543
Richard Smith745f5142012-01-27 01:14:48 +00004544 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004545 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004546
Anders Carlsson286f85e2008-11-16 07:17:21 +00004547 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004548
Anders Carlsson286f85e2008-11-16 07:17:21 +00004549 switch (E->getOpcode()) {
4550 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004551 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004552 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004553 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004554 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004555 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004556 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004557 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004558 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004559 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004560 E);
John McCall2de56d12010-08-25 11:45:40 +00004561 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004562 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004563 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004564 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004565 || CR == APFloat::cmpLessThan
4566 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004567 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004568 }
Mike Stump1eb44332009-09-09 15:08:12 +00004569
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004570 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004571 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004572 LValue LHSValue, RHSValue;
4573
4574 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4575 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004576 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004577
Richard Smith745f5142012-01-27 01:14:48 +00004578 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004579 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004580
Richard Smith625b8072011-10-31 01:37:14 +00004581 // Reject differing bases from the normal codepath; we special-case
4582 // comparisons to null.
4583 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004584 if (E->getOpcode() == BO_Sub) {
4585 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004586 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4587 return false;
4588 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4589 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4590 if (!LHSExpr || !RHSExpr)
4591 return false;
4592 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4593 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4594 if (!LHSAddrExpr || !RHSAddrExpr)
4595 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004596 // Make sure both labels come from the same function.
4597 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4598 RHSAddrExpr->getLabel()->getDeclContext())
4599 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004600 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004601 return true;
4602 }
Richard Smith9e36b532011-10-31 05:11:32 +00004603 // Inequalities and subtractions between unrelated pointers have
4604 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004605 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004606 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004607 // A constant address may compare equal to the address of a symbol.
4608 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004609 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004610 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4611 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004612 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004613 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004614 // distinct addresses. In clang, the result of such a comparison is
4615 // unspecified, so it is not a constant expression. However, we do know
4616 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004617 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4618 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004619 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004620 // We can't tell whether weak symbols will end up pointing to the same
4621 // object.
4622 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004623 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004624 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004625 // (Note that clang defaults to -fmerge-all-constants, which can
4626 // lead to inconsistent results for comparisons involving the address
4627 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004628 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004629 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004630
Richard Smith15efc4d2012-02-01 08:10:20 +00004631 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4632 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4633
Richard Smithf15fda02012-02-02 01:16:57 +00004634 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4635 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4636
John McCall2de56d12010-08-25 11:45:40 +00004637 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004638 // C++11 [expr.add]p6:
4639 // Unless both pointers point to elements of the same array object, or
4640 // one past the last element of the array object, the behavior is
4641 // undefined.
4642 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4643 !AreElementsOfSameArray(getType(LHSValue.Base),
4644 LHSDesignator, RHSDesignator))
4645 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4646
Chris Lattner4992bdd2010-04-20 17:13:14 +00004647 QualType Type = E->getLHS()->getType();
4648 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004649
Richard Smith180f4792011-11-10 06:34:14 +00004650 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004651 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004652 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004653
Richard Smith15efc4d2012-02-01 08:10:20 +00004654 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4655 // and produce incorrect results when it overflows. Such behavior
4656 // appears to be non-conforming, but is common, so perhaps we should
4657 // assume the standard intended for such cases to be undefined behavior
4658 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004659
Richard Smith15efc4d2012-02-01 08:10:20 +00004660 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4661 // overflow in the final conversion to ptrdiff_t.
4662 APSInt LHS(
4663 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4664 APSInt RHS(
4665 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4666 APSInt ElemSize(
4667 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4668 APSInt TrueResult = (LHS - RHS) / ElemSize;
4669 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4670
4671 if (Result.extend(65) != TrueResult)
4672 HandleOverflow(Info, E, TrueResult, E->getType());
4673 return Success(Result, E);
4674 }
Richard Smith82f28582012-01-31 06:41:30 +00004675
4676 // C++11 [expr.rel]p3:
4677 // Pointers to void (after pointer conversions) can be compared, with a
4678 // result defined as follows: If both pointers represent the same
4679 // address or are both the null pointer value, the result is true if the
4680 // operator is <= or >= and false otherwise; otherwise the result is
4681 // unspecified.
4682 // We interpret this as applying to pointers to *cv* void.
4683 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004684 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004685 CCEDiag(E, diag::note_constexpr_void_comparison);
4686
Richard Smithf15fda02012-02-02 01:16:57 +00004687 // C++11 [expr.rel]p2:
4688 // - If two pointers point to non-static data members of the same object,
4689 // or to subobjects or array elements fo such members, recursively, the
4690 // pointer to the later declared member compares greater provided the
4691 // two members have the same access control and provided their class is
4692 // not a union.
4693 // [...]
4694 // - Otherwise pointer comparisons are unspecified.
4695 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4696 E->isRelationalOp()) {
4697 bool WasArrayIndex;
4698 unsigned Mismatch =
4699 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4700 RHSDesignator, WasArrayIndex);
4701 // At the point where the designators diverge, the comparison has a
4702 // specified value if:
4703 // - we are comparing array indices
4704 // - we are comparing fields of a union, or fields with the same access
4705 // Otherwise, the result is unspecified and thus the comparison is not a
4706 // constant expression.
4707 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4708 Mismatch < RHSDesignator.Entries.size()) {
4709 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4710 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4711 if (!LF && !RF)
4712 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4713 else if (!LF)
4714 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4715 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4716 << RF->getParent() << RF;
4717 else if (!RF)
4718 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4719 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4720 << LF->getParent() << LF;
4721 else if (!LF->getParent()->isUnion() &&
4722 LF->getAccess() != RF->getAccess())
4723 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4724 << LF << LF->getAccess() << RF << RF->getAccess()
4725 << LF->getParent();
4726 }
4727 }
4728
Richard Smith625b8072011-10-31 01:37:14 +00004729 switch (E->getOpcode()) {
4730 default: llvm_unreachable("missing comparison operator");
4731 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4732 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4733 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4734 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4735 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4736 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004737 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004738 }
4739 }
Richard Smithb02e4622012-02-01 01:42:44 +00004740
4741 if (LHSTy->isMemberPointerType()) {
4742 assert(E->isEqualityOp() && "unexpected member pointer operation");
4743 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4744
4745 MemberPtr LHSValue, RHSValue;
4746
4747 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4748 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4749 return false;
4750
4751 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4752 return false;
4753
4754 // C++11 [expr.eq]p2:
4755 // If both operands are null, they compare equal. Otherwise if only one is
4756 // null, they compare unequal.
4757 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4758 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4759 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4760 }
4761
4762 // Otherwise if either is a pointer to a virtual member function, the
4763 // result is unspecified.
4764 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4765 if (MD->isVirtual())
4766 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4768 if (MD->isVirtual())
4769 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4770
4771 // Otherwise they compare equal if and only if they would refer to the
4772 // same member of the same most derived object or the same subobject if
4773 // they were dereferenced with a hypothetical object of the associated
4774 // class type.
4775 bool Equal = LHSValue == RHSValue;
4776 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4777 }
4778
Richard Smith26f2cac2012-02-14 22:35:28 +00004779 if (LHSTy->isNullPtrType()) {
4780 assert(E->isComparisonOp() && "unexpected nullptr operation");
4781 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4782 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4783 // are compared, the result is true of the operator is <=, >= or ==, and
4784 // false otherwise.
4785 BinaryOperator::Opcode Opcode = E->getOpcode();
4786 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4787 }
4788
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004789 if (!LHSTy->isIntegralOrEnumerationType() ||
4790 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004791 // We can't continue from here for non-integral types.
4792 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004793 }
4794
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004795 // The LHS of a constant expr is always evaluated and needed.
Richard Smith1aa0be82012-03-03 22:46:17 +00004796 APValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004797
4798 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4799 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004800 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004801
Richard Smith745f5142012-01-27 01:14:48 +00004802 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004803 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004804
Richard Smith1aa0be82012-03-03 22:46:17 +00004805 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004806
4807 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004808 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004809 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4810 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004811 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004812 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004813 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004814 LHSVal.getLValueOffset() -= AdditionalOffset;
4815 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004816 return true;
4817 }
4818
4819 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004820 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004821 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004822 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4823 LHSVal.getInt().getZExtValue());
4824 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004825 return true;
4826 }
4827
Eli Friedman65639282012-01-04 23:13:47 +00004828 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4829 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004830 if (!LHSVal.getLValueOffset().isZero() ||
4831 !RHSVal.getLValueOffset().isZero())
4832 return false;
4833 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4834 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4835 if (!LHSExpr || !RHSExpr)
4836 return false;
4837 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4838 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4839 if (!LHSAddrExpr || !RHSAddrExpr)
4840 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004841 // Make sure both labels come from the same function.
4842 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4843 RHSAddrExpr->getLabel()->getDeclContext())
4844 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004845 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004846 return true;
4847 }
4848
Eli Friedman42edd0d2009-03-24 01:14:50 +00004849 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004850 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004851 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004852
Richard Smithc49bd112011-10-28 17:51:58 +00004853 APSInt &LHS = LHSVal.getInt();
4854 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004855
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004856 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004857 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004858 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004859 case BO_Mul:
4860 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4861 LHS.getBitWidth() * 2,
4862 std::multiplies<APSInt>()), E);
4863 case BO_Add:
4864 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4865 LHS.getBitWidth() + 1,
4866 std::plus<APSInt>()), E);
4867 case BO_Sub:
4868 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4869 LHS.getBitWidth() + 1,
4870 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004871 case BO_And: return Success(LHS & RHS, E);
4872 case BO_Xor: return Success(LHS ^ RHS, E);
4873 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004875 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004876 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004877 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004878 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4879 // actually undefined behavior in C++11 due to a language defect.
4880 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4881 LHS.isSigned() && LHS.isMinSignedValue())
4882 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4883 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004884 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004885 // During constant-folding, a negative shift is an opposite shift. Such a
4886 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004887 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004888 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004889 RHS = -RHS;
4890 goto shift_right;
4891 }
4892
4893 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004894 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4895 // shifted type.
4896 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4897 if (SA != RHS) {
4898 CCEDiag(E, diag::note_constexpr_large_shift)
4899 << RHS << E->getType() << LHS.getBitWidth();
4900 } else if (LHS.isSigned()) {
4901 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004902 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004903 if (LHS.isNegative())
4904 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004905 else if (LHS.countLeadingZeros() < SA)
4906 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004907 }
4908
Richard Smithc49bd112011-10-28 17:51:58 +00004909 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004910 }
John McCall2de56d12010-08-25 11:45:40 +00004911 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004912 // During constant-folding, a negative shift is an opposite shift. Such a
4913 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004914 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004915 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004916 RHS = -RHS;
4917 goto shift_left;
4918 }
4919
4920 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004921 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4922 // shifted type.
4923 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4924 if (SA != RHS)
4925 CCEDiag(E, diag::note_constexpr_large_shift)
4926 << RHS << E->getType() << LHS.getBitWidth();
4927
Richard Smithc49bd112011-10-28 17:51:58 +00004928 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004929 }
Mike Stump1eb44332009-09-09 15:08:12 +00004930
Richard Smithc49bd112011-10-28 17:51:58 +00004931 case BO_LT: return Success(LHS < RHS, E);
4932 case BO_GT: return Success(LHS > RHS, E);
4933 case BO_LE: return Success(LHS <= RHS, E);
4934 case BO_GE: return Success(LHS >= RHS, E);
4935 case BO_EQ: return Success(LHS == RHS, E);
4936 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004937 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004938}
4939
Ken Dyck8b752f12010-01-27 17:10:57 +00004940CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004941 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4942 // result shall be the alignment of the referenced type."
4943 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4944 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004945
4946 // __alignof is defined to return the preferred alignment.
4947 return Info.Ctx.toCharUnitsFromBits(
4948 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004949}
4950
Ken Dyck8b752f12010-01-27 17:10:57 +00004951CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004952 E = E->IgnoreParens();
4953
4954 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004955 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004956 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004957 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4958 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004959
Chris Lattneraf707ab2009-01-24 21:53:27 +00004960 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004961 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4962 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004963
Chris Lattnere9feb472009-01-24 21:09:06 +00004964 return GetAlignOfType(E->getType());
4965}
4966
4967
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004968/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4969/// a result as the expression's type.
4970bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4971 const UnaryExprOrTypeTraitExpr *E) {
4972 switch(E->getKind()) {
4973 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004974 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004975 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004976 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004977 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004978 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004979
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004980 case UETT_VecStep: {
4981 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004982
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004983 if (Ty->isVectorType()) {
4984 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004985
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004986 // The vec_step built-in functions that take a 3-component
4987 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4988 if (n == 3)
4989 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004990
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004991 return Success(n, E);
4992 } else
4993 return Success(1, E);
4994 }
4995
4996 case UETT_SizeOf: {
4997 QualType SrcTy = E->getTypeOfArgument();
4998 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4999 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005000 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5001 SrcTy = Ref->getPointeeType();
5002
Richard Smith180f4792011-11-10 06:34:14 +00005003 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005004 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005005 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005006 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005007 }
5008 }
5009
5010 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005011}
5012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005013bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005014 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005015 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005016 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005017 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005018 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005019 for (unsigned i = 0; i != n; ++i) {
5020 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5021 switch (ON.getKind()) {
5022 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005023 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005024 APSInt IdxResult;
5025 if (!EvaluateInteger(Idx, IdxResult, Info))
5026 return false;
5027 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5028 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005029 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005030 CurrentType = AT->getElementType();
5031 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5032 Result += IdxResult.getSExtValue() * ElementSize;
5033 break;
5034 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005035
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005036 case OffsetOfExpr::OffsetOfNode::Field: {
5037 FieldDecl *MemberDecl = ON.getField();
5038 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005039 if (!RT)
5040 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005041 RecordDecl *RD = RT->getDecl();
5042 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005043 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005044 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005045 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005046 CurrentType = MemberDecl->getType().getNonReferenceType();
5047 break;
5048 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005049
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005050 case OffsetOfExpr::OffsetOfNode::Identifier:
5051 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005052
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005053 case OffsetOfExpr::OffsetOfNode::Base: {
5054 CXXBaseSpecifier *BaseSpec = ON.getBase();
5055 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005056 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005057
5058 // Find the layout of the class whose base we are looking into.
5059 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005060 if (!RT)
5061 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005062 RecordDecl *RD = RT->getDecl();
5063 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5064
5065 // Find the base class itself.
5066 CurrentType = BaseSpec->getType();
5067 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5068 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005069 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005070
5071 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005072 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005073 break;
5074 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005075 }
5076 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005077 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005078}
5079
Chris Lattnerb542afe2008-07-11 19:10:17 +00005080bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005081 switch (E->getOpcode()) {
5082 default:
5083 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5084 // See C99 6.6p3.
5085 return Error(E);
5086 case UO_Extension:
5087 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5088 // If so, we could clear the diagnostic ID.
5089 return Visit(E->getSubExpr());
5090 case UO_Plus:
5091 // The result is just the value.
5092 return Visit(E->getSubExpr());
5093 case UO_Minus: {
5094 if (!Visit(E->getSubExpr()))
5095 return false;
5096 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005097 const APSInt &Value = Result.getInt();
5098 if (Value.isSigned() && Value.isMinSignedValue())
5099 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5100 E->getType());
5101 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005102 }
5103 case UO_Not: {
5104 if (!Visit(E->getSubExpr()))
5105 return false;
5106 if (!Result.isInt()) return Error(E);
5107 return Success(~Result.getInt(), E);
5108 }
5109 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005110 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005111 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005112 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005113 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005114 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005115 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005116}
Mike Stump1eb44332009-09-09 15:08:12 +00005117
Chris Lattner732b2232008-07-12 01:15:53 +00005118/// HandleCast - This is used to evaluate implicit or explicit casts where the
5119/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005120bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5121 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005122 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005123 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005124
Eli Friedman46a52322011-03-25 00:43:55 +00005125 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005126 case CK_BaseToDerived:
5127 case CK_DerivedToBase:
5128 case CK_UncheckedDerivedToBase:
5129 case CK_Dynamic:
5130 case CK_ToUnion:
5131 case CK_ArrayToPointerDecay:
5132 case CK_FunctionToPointerDecay:
5133 case CK_NullToPointer:
5134 case CK_NullToMemberPointer:
5135 case CK_BaseToDerivedMemberPointer:
5136 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005137 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005138 case CK_ConstructorConversion:
5139 case CK_IntegralToPointer:
5140 case CK_ToVoid:
5141 case CK_VectorSplat:
5142 case CK_IntegralToFloating:
5143 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005144 case CK_CPointerToObjCPointerCast:
5145 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005146 case CK_AnyPointerToBlockPointerCast:
5147 case CK_ObjCObjectLValueCast:
5148 case CK_FloatingRealToComplex:
5149 case CK_FloatingComplexToReal:
5150 case CK_FloatingComplexCast:
5151 case CK_FloatingComplexToIntegralComplex:
5152 case CK_IntegralRealToComplex:
5153 case CK_IntegralComplexCast:
5154 case CK_IntegralComplexToFloatingComplex:
5155 llvm_unreachable("invalid cast kind for integral value");
5156
Eli Friedmane50c2972011-03-25 19:07:11 +00005157 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005158 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005159 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005160 case CK_ARCProduceObject:
5161 case CK_ARCConsumeObject:
5162 case CK_ARCReclaimReturnedObject:
5163 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005164 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005165 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005166
Richard Smith7d580a42012-01-17 21:17:26 +00005167 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005168 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005169 case CK_AtomicToNonAtomic:
5170 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005171 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005172 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005173
5174 case CK_MemberPointerToBoolean:
5175 case CK_PointerToBoolean:
5176 case CK_IntegralToBoolean:
5177 case CK_FloatingToBoolean:
5178 case CK_FloatingComplexToBoolean:
5179 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005180 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005181 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005182 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005183 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005184 }
5185
Eli Friedman46a52322011-03-25 00:43:55 +00005186 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005187 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005188 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005189
Eli Friedmanbe265702009-02-20 01:15:07 +00005190 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005191 // Allow casts of address-of-label differences if they are no-ops
5192 // or narrowing. (The narrowing case isn't actually guaranteed to
5193 // be constant-evaluatable except in some narrow cases which are hard
5194 // to detect here. We let it through on the assumption the user knows
5195 // what they are doing.)
5196 if (Result.isAddrLabelDiff())
5197 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005198 // Only allow casts of lvalues if they are lossless.
5199 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5200 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005201
Richard Smithf72fccf2012-01-30 22:27:01 +00005202 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5203 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005204 }
Mike Stump1eb44332009-09-09 15:08:12 +00005205
Eli Friedman46a52322011-03-25 00:43:55 +00005206 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005207 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5208
John McCallefdb83e2010-05-07 21:00:08 +00005209 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005210 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005211 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005212
Daniel Dunbardd211642009-02-19 22:24:01 +00005213 if (LV.getLValueBase()) {
5214 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005215 // FIXME: Allow a larger integer size than the pointer size, and allow
5216 // narrowing back down to pointer width in subsequent integral casts.
5217 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005218 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005219 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005220
Richard Smithb755a9d2011-11-16 07:18:12 +00005221 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005222 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005223 return true;
5224 }
5225
Ken Dycka7305832010-01-15 12:37:54 +00005226 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5227 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005228 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005229 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005230
Eli Friedman46a52322011-03-25 00:43:55 +00005231 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005232 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005233 if (!EvaluateComplex(SubExpr, C, Info))
5234 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005235 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005236 }
Eli Friedman2217c872009-02-22 11:46:18 +00005237
Eli Friedman46a52322011-03-25 00:43:55 +00005238 case CK_FloatingToIntegral: {
5239 APFloat F(0.0);
5240 if (!EvaluateFloat(SubExpr, F, Info))
5241 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005242
Richard Smithc1c5f272011-12-13 06:39:58 +00005243 APSInt Value;
5244 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5245 return false;
5246 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005247 }
5248 }
Mike Stump1eb44332009-09-09 15:08:12 +00005249
Eli Friedman46a52322011-03-25 00:43:55 +00005250 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005251}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005252
Eli Friedman722c7172009-02-28 03:59:05 +00005253bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5254 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005255 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005256 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5257 return false;
5258 if (!LV.isComplexInt())
5259 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005260 return Success(LV.getComplexIntReal(), E);
5261 }
5262
5263 return Visit(E->getSubExpr());
5264}
5265
Eli Friedman664a1042009-02-27 04:45:43 +00005266bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005267 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005268 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005269 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5270 return false;
5271 if (!LV.isComplexInt())
5272 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005273 return Success(LV.getComplexIntImag(), E);
5274 }
5275
Richard Smith8327fad2011-10-24 18:44:57 +00005276 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005277 return Success(0, E);
5278}
5279
Douglas Gregoree8aff02011-01-04 17:33:58 +00005280bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5281 return Success(E->getPackLength(), E);
5282}
5283
Sebastian Redl295995c2010-09-10 20:55:47 +00005284bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5285 return Success(E->getValue(), E);
5286}
5287
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005288//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005289// Float Evaluation
5290//===----------------------------------------------------------------------===//
5291
5292namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005293class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005294 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005295 APFloat &Result;
5296public:
5297 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005298 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005299
Richard Smith1aa0be82012-03-03 22:46:17 +00005300 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005301 Result = V.getFloat();
5302 return true;
5303 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005304
Richard Smith51201882011-12-30 21:15:51 +00005305 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005306 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5307 return true;
5308 }
5309
Chris Lattner019f4e82008-10-06 05:28:25 +00005310 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005311
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005312 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005313 bool VisitBinaryOperator(const BinaryOperator *E);
5314 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005315 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005316
John McCallabd3a852010-05-07 22:08:54 +00005317 bool VisitUnaryReal(const UnaryOperator *E);
5318 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005319
Richard Smith51201882011-12-30 21:15:51 +00005320 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005321};
5322} // end anonymous namespace
5323
5324static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005325 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005326 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005327}
5328
Jay Foad4ba2a172011-01-12 09:06:06 +00005329static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005330 QualType ResultTy,
5331 const Expr *Arg,
5332 bool SNaN,
5333 llvm::APFloat &Result) {
5334 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5335 if (!S) return false;
5336
5337 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5338
5339 llvm::APInt fill;
5340
5341 // Treat empty strings as if they were zero.
5342 if (S->getString().empty())
5343 fill = llvm::APInt(32, 0);
5344 else if (S->getString().getAsInteger(0, fill))
5345 return false;
5346
5347 if (SNaN)
5348 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5349 else
5350 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5351 return true;
5352}
5353
Chris Lattner019f4e82008-10-06 05:28:25 +00005354bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005355 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005356 default:
5357 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5358
Chris Lattner019f4e82008-10-06 05:28:25 +00005359 case Builtin::BI__builtin_huge_val:
5360 case Builtin::BI__builtin_huge_valf:
5361 case Builtin::BI__builtin_huge_vall:
5362 case Builtin::BI__builtin_inf:
5363 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005364 case Builtin::BI__builtin_infl: {
5365 const llvm::fltSemantics &Sem =
5366 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005367 Result = llvm::APFloat::getInf(Sem);
5368 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005369 }
Mike Stump1eb44332009-09-09 15:08:12 +00005370
John McCalldb7b72a2010-02-28 13:00:19 +00005371 case Builtin::BI__builtin_nans:
5372 case Builtin::BI__builtin_nansf:
5373 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005374 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5375 true, Result))
5376 return Error(E);
5377 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005378
Chris Lattner9e621712008-10-06 06:31:58 +00005379 case Builtin::BI__builtin_nan:
5380 case Builtin::BI__builtin_nanf:
5381 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005382 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005383 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005384 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5385 false, Result))
5386 return Error(E);
5387 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005388
5389 case Builtin::BI__builtin_fabs:
5390 case Builtin::BI__builtin_fabsf:
5391 case Builtin::BI__builtin_fabsl:
5392 if (!EvaluateFloat(E->getArg(0), Result, Info))
5393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005395 if (Result.isNegative())
5396 Result.changeSign();
5397 return true;
5398
Mike Stump1eb44332009-09-09 15:08:12 +00005399 case Builtin::BI__builtin_copysign:
5400 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005401 case Builtin::BI__builtin_copysignl: {
5402 APFloat RHS(0.);
5403 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5404 !EvaluateFloat(E->getArg(1), RHS, Info))
5405 return false;
5406 Result.copySign(RHS);
5407 return true;
5408 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005409 }
5410}
5411
John McCallabd3a852010-05-07 22:08:54 +00005412bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005413 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5414 ComplexValue CV;
5415 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5416 return false;
5417 Result = CV.FloatReal;
5418 return true;
5419 }
5420
5421 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005422}
5423
5424bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005425 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5426 ComplexValue CV;
5427 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5428 return false;
5429 Result = CV.FloatImag;
5430 return true;
5431 }
5432
Richard Smith8327fad2011-10-24 18:44:57 +00005433 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005434 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5435 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005436 return true;
5437}
5438
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005439bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005440 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005441 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005442 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005443 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005444 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005445 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5446 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005447 Result.changeSign();
5448 return true;
5449 }
5450}
Chris Lattner019f4e82008-10-06 05:28:25 +00005451
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005452bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005453 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5454 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005455
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005456 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005457 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5458 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005459 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005460 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005461 return false;
5462
5463 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005464 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005465 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005466 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005467 break;
John McCall2de56d12010-08-25 11:45:40 +00005468 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005469 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005470 break;
John McCall2de56d12010-08-25 11:45:40 +00005471 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005472 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005473 break;
John McCall2de56d12010-08-25 11:45:40 +00005474 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005475 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005476 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005477 }
Richard Smith7b48a292012-02-01 05:53:12 +00005478
5479 if (Result.isInfinity() || Result.isNaN())
5480 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5481 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005482}
5483
5484bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5485 Result = E->getValue();
5486 return true;
5487}
5488
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005489bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5490 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005491
Eli Friedman2a523ee2011-03-25 00:54:52 +00005492 switch (E->getCastKind()) {
5493 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005494 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005495
5496 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005497 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005498 return EvaluateInteger(SubExpr, IntResult, Info) &&
5499 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5500 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005501 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005502
5503 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005504 if (!Visit(SubExpr))
5505 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005506 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5507 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005508 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005509
Eli Friedman2a523ee2011-03-25 00:54:52 +00005510 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005511 ComplexValue V;
5512 if (!EvaluateComplex(SubExpr, V, Info))
5513 return false;
5514 Result = V.getComplexFloatReal();
5515 return true;
5516 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005517 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005518}
5519
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005520//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005521// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005522//===----------------------------------------------------------------------===//
5523
5524namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005525class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005526 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005527 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005528
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005529public:
John McCallf4cf1a12010-05-07 17:22:02 +00005530 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005531 : ExprEvaluatorBaseTy(info), Result(Result) {}
5532
Richard Smith1aa0be82012-03-03 22:46:17 +00005533 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005534 Result.setFrom(V);
5535 return true;
5536 }
Mike Stump1eb44332009-09-09 15:08:12 +00005537
Eli Friedman7ead5c72012-01-10 04:58:17 +00005538 bool ZeroInitialization(const Expr *E);
5539
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005540 //===--------------------------------------------------------------------===//
5541 // Visitor Methods
5542 //===--------------------------------------------------------------------===//
5543
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005544 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005545 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005546 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005547 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005548 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005549};
5550} // end anonymous namespace
5551
John McCallf4cf1a12010-05-07 17:22:02 +00005552static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5553 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005554 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005555 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005556}
5557
Eli Friedman7ead5c72012-01-10 04:58:17 +00005558bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005559 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005560 if (ElemTy->isRealFloatingType()) {
5561 Result.makeComplexFloat();
5562 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5563 Result.FloatReal = Zero;
5564 Result.FloatImag = Zero;
5565 } else {
5566 Result.makeComplexInt();
5567 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5568 Result.IntReal = Zero;
5569 Result.IntImag = Zero;
5570 }
5571 return true;
5572}
5573
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005574bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5575 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005576
5577 if (SubExpr->getType()->isRealFloatingType()) {
5578 Result.makeComplexFloat();
5579 APFloat &Imag = Result.FloatImag;
5580 if (!EvaluateFloat(SubExpr, Imag, Info))
5581 return false;
5582
5583 Result.FloatReal = APFloat(Imag.getSemantics());
5584 return true;
5585 } else {
5586 assert(SubExpr->getType()->isIntegerType() &&
5587 "Unexpected imaginary literal.");
5588
5589 Result.makeComplexInt();
5590 APSInt &Imag = Result.IntImag;
5591 if (!EvaluateInteger(SubExpr, Imag, Info))
5592 return false;
5593
5594 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5595 return true;
5596 }
5597}
5598
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005599bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005600
John McCall8786da72010-12-14 17:51:41 +00005601 switch (E->getCastKind()) {
5602 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005603 case CK_BaseToDerived:
5604 case CK_DerivedToBase:
5605 case CK_UncheckedDerivedToBase:
5606 case CK_Dynamic:
5607 case CK_ToUnion:
5608 case CK_ArrayToPointerDecay:
5609 case CK_FunctionToPointerDecay:
5610 case CK_NullToPointer:
5611 case CK_NullToMemberPointer:
5612 case CK_BaseToDerivedMemberPointer:
5613 case CK_DerivedToBaseMemberPointer:
5614 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005615 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005616 case CK_ConstructorConversion:
5617 case CK_IntegralToPointer:
5618 case CK_PointerToIntegral:
5619 case CK_PointerToBoolean:
5620 case CK_ToVoid:
5621 case CK_VectorSplat:
5622 case CK_IntegralCast:
5623 case CK_IntegralToBoolean:
5624 case CK_IntegralToFloating:
5625 case CK_FloatingToIntegral:
5626 case CK_FloatingToBoolean:
5627 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005628 case CK_CPointerToObjCPointerCast:
5629 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005630 case CK_AnyPointerToBlockPointerCast:
5631 case CK_ObjCObjectLValueCast:
5632 case CK_FloatingComplexToReal:
5633 case CK_FloatingComplexToBoolean:
5634 case CK_IntegralComplexToReal:
5635 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005636 case CK_ARCProduceObject:
5637 case CK_ARCConsumeObject:
5638 case CK_ARCReclaimReturnedObject:
5639 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005640 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005641 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005642
John McCall8786da72010-12-14 17:51:41 +00005643 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005644 case CK_AtomicToNonAtomic:
5645 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005646 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005647 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005648
5649 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005650 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005651 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005652 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005653
5654 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005655 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005656 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005657 return false;
5658
John McCall8786da72010-12-14 17:51:41 +00005659 Result.makeComplexFloat();
5660 Result.FloatImag = APFloat(Real.getSemantics());
5661 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005662 }
5663
John McCall8786da72010-12-14 17:51:41 +00005664 case CK_FloatingComplexCast: {
5665 if (!Visit(E->getSubExpr()))
5666 return false;
5667
5668 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5669 QualType From
5670 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5671
Richard Smithc1c5f272011-12-13 06:39:58 +00005672 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5673 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005674 }
5675
5676 case CK_FloatingComplexToIntegralComplex: {
5677 if (!Visit(E->getSubExpr()))
5678 return false;
5679
5680 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5681 QualType From
5682 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5683 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005684 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5685 To, Result.IntReal) &&
5686 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5687 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005688 }
5689
5690 case CK_IntegralRealToComplex: {
5691 APSInt &Real = Result.IntReal;
5692 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5693 return false;
5694
5695 Result.makeComplexInt();
5696 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5697 return true;
5698 }
5699
5700 case CK_IntegralComplexCast: {
5701 if (!Visit(E->getSubExpr()))
5702 return false;
5703
5704 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5705 QualType From
5706 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5707
Richard Smithf72fccf2012-01-30 22:27:01 +00005708 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5709 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005710 return true;
5711 }
5712
5713 case CK_IntegralComplexToFloatingComplex: {
5714 if (!Visit(E->getSubExpr()))
5715 return false;
5716
5717 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5718 QualType From
5719 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5720 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005721 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5722 To, Result.FloatReal) &&
5723 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5724 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005725 }
5726 }
5727
5728 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005729}
5730
John McCallf4cf1a12010-05-07 17:22:02 +00005731bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005732 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005733 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5734
Richard Smith745f5142012-01-27 01:14:48 +00005735 bool LHSOK = Visit(E->getLHS());
5736 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005737 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005738
John McCallf4cf1a12010-05-07 17:22:02 +00005739 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005740 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005741 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005742
Daniel Dunbar3f279872009-01-29 01:32:56 +00005743 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5744 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005745 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005746 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005747 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005748 if (Result.isComplexFloat()) {
5749 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5750 APFloat::rmNearestTiesToEven);
5751 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5752 APFloat::rmNearestTiesToEven);
5753 } else {
5754 Result.getComplexIntReal() += RHS.getComplexIntReal();
5755 Result.getComplexIntImag() += RHS.getComplexIntImag();
5756 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005757 break;
John McCall2de56d12010-08-25 11:45:40 +00005758 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005759 if (Result.isComplexFloat()) {
5760 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5761 APFloat::rmNearestTiesToEven);
5762 Result.getComplexFloatImag().subtract(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_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005770 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005771 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005772 APFloat &LHS_r = LHS.getComplexFloatReal();
5773 APFloat &LHS_i = LHS.getComplexFloatImag();
5774 APFloat &RHS_r = RHS.getComplexFloatReal();
5775 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005776
Daniel Dunbar3f279872009-01-29 01:32:56 +00005777 APFloat Tmp = LHS_r;
5778 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5779 Result.getComplexFloatReal() = Tmp;
5780 Tmp = LHS_i;
5781 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5782 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5783
5784 Tmp = LHS_r;
5785 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5786 Result.getComplexFloatImag() = Tmp;
5787 Tmp = LHS_i;
5788 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5789 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5790 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005791 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005792 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005793 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5794 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005795 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005796 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5797 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5798 }
5799 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005800 case BO_Div:
5801 if (Result.isComplexFloat()) {
5802 ComplexValue LHS = Result;
5803 APFloat &LHS_r = LHS.getComplexFloatReal();
5804 APFloat &LHS_i = LHS.getComplexFloatImag();
5805 APFloat &RHS_r = RHS.getComplexFloatReal();
5806 APFloat &RHS_i = RHS.getComplexFloatImag();
5807 APFloat &Res_r = Result.getComplexFloatReal();
5808 APFloat &Res_i = Result.getComplexFloatImag();
5809
5810 APFloat Den = RHS_r;
5811 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5812 APFloat Tmp = RHS_i;
5813 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5814 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5815
5816 Res_r = LHS_r;
5817 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5818 Tmp = LHS_i;
5819 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5820 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5821 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5822
5823 Res_i = LHS_i;
5824 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5825 Tmp = LHS_r;
5826 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5827 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5828 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5829 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005830 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5831 return Error(E, diag::note_expr_divide_by_zero);
5832
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005833 ComplexValue LHS = Result;
5834 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5835 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5836 Result.getComplexIntReal() =
5837 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5838 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5839 Result.getComplexIntImag() =
5840 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5841 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5842 }
5843 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005844 }
5845
John McCallf4cf1a12010-05-07 17:22:02 +00005846 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005847}
5848
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005849bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5850 // Get the operand value into 'Result'.
5851 if (!Visit(E->getSubExpr()))
5852 return false;
5853
5854 switch (E->getOpcode()) {
5855 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005856 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005857 case UO_Extension:
5858 return true;
5859 case UO_Plus:
5860 // The result is always just the subexpr.
5861 return true;
5862 case UO_Minus:
5863 if (Result.isComplexFloat()) {
5864 Result.getComplexFloatReal().changeSign();
5865 Result.getComplexFloatImag().changeSign();
5866 }
5867 else {
5868 Result.getComplexIntReal() = -Result.getComplexIntReal();
5869 Result.getComplexIntImag() = -Result.getComplexIntImag();
5870 }
5871 return true;
5872 case UO_Not:
5873 if (Result.isComplexFloat())
5874 Result.getComplexFloatImag().changeSign();
5875 else
5876 Result.getComplexIntImag() = -Result.getComplexIntImag();
5877 return true;
5878 }
5879}
5880
Eli Friedman7ead5c72012-01-10 04:58:17 +00005881bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5882 if (E->getNumInits() == 2) {
5883 if (E->getType()->isComplexType()) {
5884 Result.makeComplexFloat();
5885 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5886 return false;
5887 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5888 return false;
5889 } else {
5890 Result.makeComplexInt();
5891 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5892 return false;
5893 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5894 return false;
5895 }
5896 return true;
5897 }
5898 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5899}
5900
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005901//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005902// Void expression evaluation, primarily for a cast to void on the LHS of a
5903// comma operator
5904//===----------------------------------------------------------------------===//
5905
5906namespace {
5907class VoidExprEvaluator
5908 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5909public:
5910 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5911
Richard Smith1aa0be82012-03-03 22:46:17 +00005912 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005913
5914 bool VisitCastExpr(const CastExpr *E) {
5915 switch (E->getCastKind()) {
5916 default:
5917 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5918 case CK_ToVoid:
5919 VisitIgnoredValue(E->getSubExpr());
5920 return true;
5921 }
5922 }
5923};
5924} // end anonymous namespace
5925
5926static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5927 assert(E->isRValue() && E->getType()->isVoidType());
5928 return VoidExprEvaluator(Info).Visit(E);
5929}
5930
5931//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005932// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005933//===----------------------------------------------------------------------===//
5934
Richard Smith1aa0be82012-03-03 22:46:17 +00005935static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005936 // In C, function designators are not lvalues, but we evaluate them as if they
5937 // are.
5938 if (E->isGLValue() || E->getType()->isFunctionType()) {
5939 LValue LV;
5940 if (!EvaluateLValue(E, LV, Info))
5941 return false;
5942 LV.moveInto(Result);
5943 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005944 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005945 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005946 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005947 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005948 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005949 } else if (E->getType()->hasPointerRepresentation()) {
5950 LValue LV;
5951 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005952 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005953 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005954 } else if (E->getType()->isRealFloatingType()) {
5955 llvm::APFloat F(0.0);
5956 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005957 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005958 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005959 } else if (E->getType()->isAnyComplexType()) {
5960 ComplexValue C;
5961 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005962 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005963 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005964 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005965 MemberPtr P;
5966 if (!EvaluateMemberPointer(E, P, Info))
5967 return false;
5968 P.moveInto(Result);
5969 return true;
Richard Smith51201882011-12-30 21:15:51 +00005970 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005971 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005972 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005973 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005974 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005975 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005976 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005977 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005978 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005979 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5980 return false;
5981 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005982 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005983 if (Info.getLangOpts().CPlusPlus0x)
5984 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5985 << E->getType();
5986 else
5987 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005988 if (!EvaluateVoid(E, Info))
5989 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005990 } else if (Info.getLangOpts().CPlusPlus0x) {
5991 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5992 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005993 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005994 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005995 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005996 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005997
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005998 return true;
5999}
6000
Richard Smith83587db2012-02-15 02:18:13 +00006001/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6002/// cases, the in-place evaluation is essential, since later initializers for
6003/// an object can indirectly refer to subobjects which were initialized earlier.
6004static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6005 const Expr *E, CheckConstantExpressionKind CCEK,
6006 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006007 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006008 return false;
6009
6010 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006011 // Evaluate arrays and record types in-place, so that later initializers can
6012 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006013 if (E->getType()->isArrayType())
6014 return EvaluateArray(E, This, Result, Info);
6015 else if (E->getType()->isRecordType())
6016 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006017 }
6018
6019 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006020 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006021}
6022
Richard Smithf48fdb02011-12-09 22:58:01 +00006023/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6024/// lvalue-to-rvalue cast if it is an lvalue.
6025static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006026 if (!CheckLiteralType(Info, E))
6027 return false;
6028
Richard Smith1aa0be82012-03-03 22:46:17 +00006029 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006030 return false;
6031
6032 if (E->isGLValue()) {
6033 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006034 LV.setFrom(Info.Ctx, Result);
6035 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006036 return false;
6037 }
6038
Richard Smith1aa0be82012-03-03 22:46:17 +00006039 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006040 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006041}
Richard Smithc49bd112011-10-28 17:51:58 +00006042
Richard Smith51f47082011-10-29 00:50:52 +00006043/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006044/// any crazy technique (that has nothing to do with language standards) that
6045/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006046/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6047/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006048bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006049 // Fast-path evaluations of integer literals, since we sometimes see files
6050 // containing vast quantities of these.
6051 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6052 Result.Val = APValue(APSInt(L->getValue(),
6053 L->getType()->isUnsignedIntegerType()));
6054 return true;
6055 }
6056
Richard Smith2d6a5672012-01-14 04:30:29 +00006057 // FIXME: Evaluating values of large array and record types can cause
6058 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006059 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6060 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006061 return false;
6062
Richard Smithf48fdb02011-12-09 22:58:01 +00006063 EvalInfo Info(Ctx, Result);
6064 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006065}
6066
Jay Foad4ba2a172011-01-12 09:06:06 +00006067bool Expr::EvaluateAsBooleanCondition(bool &Result,
6068 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006069 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006070 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006071 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006072}
6073
Richard Smith80d4b552011-12-28 19:48:30 +00006074bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6075 SideEffectsKind AllowSideEffects) const {
6076 if (!getType()->isIntegralOrEnumerationType())
6077 return false;
6078
Richard Smithc49bd112011-10-28 17:51:58 +00006079 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006080 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6081 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006082 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006083
Richard Smithc49bd112011-10-28 17:51:58 +00006084 Result = ExprResult.Val.getInt();
6085 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006086}
6087
Jay Foad4ba2a172011-01-12 09:06:06 +00006088bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006089 EvalInfo Info(Ctx, Result);
6090
John McCallefdb83e2010-05-07 21:00:08 +00006091 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006092 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6093 !CheckLValueConstantExpression(Info, getExprLoc(),
6094 Ctx.getLValueReferenceType(getType()), LV))
6095 return false;
6096
Richard Smith1aa0be82012-03-03 22:46:17 +00006097 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006098 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006099}
6100
Richard Smith099e7f62011-12-19 06:19:21 +00006101bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6102 const VarDecl *VD,
6103 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006104 // FIXME: Evaluating initializers for large array and record types can cause
6105 // performance problems. Only do so in C++11 for now.
6106 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6107 !Ctx.getLangOptions().CPlusPlus0x)
6108 return false;
6109
Richard Smith099e7f62011-12-19 06:19:21 +00006110 Expr::EvalStatus EStatus;
6111 EStatus.Diag = &Notes;
6112
6113 EvalInfo InitInfo(Ctx, EStatus);
6114 InitInfo.setEvaluatingDecl(VD, Value);
6115
6116 LValue LVal;
6117 LVal.set(VD);
6118
Richard Smith51201882011-12-30 21:15:51 +00006119 // C++11 [basic.start.init]p2:
6120 // Variables with static storage duration or thread storage duration shall be
6121 // zero-initialized before any other initialization takes place.
6122 // This behavior is not present in C.
6123 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6124 !VD->getType()->isReferenceType()) {
6125 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006126 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6127 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006128 return false;
6129 }
6130
Richard Smith83587db2012-02-15 02:18:13 +00006131 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6132 /*AllowNonLiteralTypes=*/true) ||
6133 EStatus.HasSideEffects)
6134 return false;
6135
6136 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6137 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006138}
6139
Richard Smith51f47082011-10-29 00:50:52 +00006140/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6141/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006142bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006143 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006144 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006145}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006146
Jay Foad4ba2a172011-01-12 09:06:06 +00006147bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006148 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006149}
6150
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006151APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006152 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006153 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006154 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006155 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006156 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006157
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006158 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006159}
John McCalld905f5a2010-05-07 05:32:02 +00006160
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006161 bool Expr::EvalResult::isGlobalLValue() const {
6162 assert(Val.isLValue());
6163 return IsGlobalLValue(Val.getLValueBase());
6164 }
6165
6166
John McCalld905f5a2010-05-07 05:32:02 +00006167/// isIntegerConstantExpr - this recursive routine will test if an expression is
6168/// an integer constant expression.
6169
6170/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6171/// comma, etc
6172///
6173/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6174/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6175/// cast+dereference.
6176
6177// CheckICE - This function does the fundamental ICE checking: the returned
6178// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6179// Note that to reduce code duplication, this helper does no evaluation
6180// itself; the caller checks whether the expression is evaluatable, and
6181// in the rare cases where CheckICE actually cares about the evaluated
6182// value, it calls into Evalute.
6183//
6184// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006185// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006186// 1: This expression is not an ICE, but if it isn't evaluated, it's
6187// a legal subexpression for an ICE. This return value is used to handle
6188// the comma operator in C99 mode.
6189// 2: This expression is not an ICE, and is not a legal subexpression for one.
6190
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006191namespace {
6192
John McCalld905f5a2010-05-07 05:32:02 +00006193struct ICEDiag {
6194 unsigned Val;
6195 SourceLocation Loc;
6196
6197 public:
6198 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6199 ICEDiag() : Val(0) {}
6200};
6201
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006202}
6203
6204static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006205
6206static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6207 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006208 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006209 !EVResult.Val.isInt()) {
6210 return ICEDiag(2, E->getLocStart());
6211 }
6212 return NoDiag();
6213}
6214
6215static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6216 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006217 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006218 return ICEDiag(2, E->getLocStart());
6219 }
6220
6221 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006222#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006223#define STMT(Node, Base) case Expr::Node##Class:
6224#define EXPR(Node, Base)
6225#include "clang/AST/StmtNodes.inc"
6226 case Expr::PredefinedExprClass:
6227 case Expr::FloatingLiteralClass:
6228 case Expr::ImaginaryLiteralClass:
6229 case Expr::StringLiteralClass:
6230 case Expr::ArraySubscriptExprClass:
6231 case Expr::MemberExprClass:
6232 case Expr::CompoundAssignOperatorClass:
6233 case Expr::CompoundLiteralExprClass:
6234 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006235 case Expr::DesignatedInitExprClass:
6236 case Expr::ImplicitValueInitExprClass:
6237 case Expr::ParenListExprClass:
6238 case Expr::VAArgExprClass:
6239 case Expr::AddrLabelExprClass:
6240 case Expr::StmtExprClass:
6241 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006242 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006243 case Expr::CXXDynamicCastExprClass:
6244 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006245 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006246 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006247 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006248 case Expr::CXXThisExprClass:
6249 case Expr::CXXThrowExprClass:
6250 case Expr::CXXNewExprClass:
6251 case Expr::CXXDeleteExprClass:
6252 case Expr::CXXPseudoDestructorExprClass:
6253 case Expr::UnresolvedLookupExprClass:
6254 case Expr::DependentScopeDeclRefExprClass:
6255 case Expr::CXXConstructExprClass:
6256 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006257 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006258 case Expr::CXXTemporaryObjectExprClass:
6259 case Expr::CXXUnresolvedConstructExprClass:
6260 case Expr::CXXDependentScopeMemberExprClass:
6261 case Expr::UnresolvedMemberExprClass:
6262 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006263 case Expr::ObjCNumericLiteralClass:
6264 case Expr::ObjCArrayLiteralClass:
6265 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006266 case Expr::ObjCEncodeExprClass:
6267 case Expr::ObjCMessageExprClass:
6268 case Expr::ObjCSelectorExprClass:
6269 case Expr::ObjCProtocolExprClass:
6270 case Expr::ObjCIvarRefExprClass:
6271 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006272 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006273 case Expr::ObjCIsaExprClass:
6274 case Expr::ShuffleVectorExprClass:
6275 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006276 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006277 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006278 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006279 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006280 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006281 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006282 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006283 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006284 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006285 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006286 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006287 return ICEDiag(2, E->getLocStart());
6288
Douglas Gregoree8aff02011-01-04 17:33:58 +00006289 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006290 case Expr::GNUNullExprClass:
6291 // GCC considers the GNU __null value to be an integral constant expression.
6292 return NoDiag();
6293
John McCall91a57552011-07-15 05:09:51 +00006294 case Expr::SubstNonTypeTemplateParmExprClass:
6295 return
6296 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6297
John McCalld905f5a2010-05-07 05:32:02 +00006298 case Expr::ParenExprClass:
6299 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006300 case Expr::GenericSelectionExprClass:
6301 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006302 case Expr::IntegerLiteralClass:
6303 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006304 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006305 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006306 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006307 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006308 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006309 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006310 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006311 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006312 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006313 return NoDiag();
6314 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006315 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006316 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6317 // constant expressions, but they can never be ICEs because an ICE cannot
6318 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006319 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006320 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006321 return CheckEvalInICE(E, Ctx);
6322 return ICEDiag(2, E->getLocStart());
6323 }
Richard Smith359c89d2012-02-24 22:12:32 +00006324 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006325 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6326 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006327 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6328 if (Ctx.getLangOptions().CPlusPlus &&
6329 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006330 // Parameter variables are never constants. Without this check,
6331 // getAnyInitializer() can find a default argument, which leads
6332 // to chaos.
6333 if (isa<ParmVarDecl>(D))
6334 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6335
6336 // C++ 7.1.5.1p2
6337 // A variable of non-volatile const-qualified integral or enumeration
6338 // type initialized by an ICE can be used in ICEs.
6339 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006340 if (!Dcl->getType()->isIntegralOrEnumerationType())
6341 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6342
Richard Smith099e7f62011-12-19 06:19:21 +00006343 const VarDecl *VD;
6344 // Look for a declaration of this variable that has an initializer, and
6345 // check whether it is an ICE.
6346 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6347 return NoDiag();
6348 else
6349 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006350 }
6351 }
6352 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006353 }
John McCalld905f5a2010-05-07 05:32:02 +00006354 case Expr::UnaryOperatorClass: {
6355 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6356 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006357 case UO_PostInc:
6358 case UO_PostDec:
6359 case UO_PreInc:
6360 case UO_PreDec:
6361 case UO_AddrOf:
6362 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006363 // C99 6.6/3 allows increment and decrement within unevaluated
6364 // subexpressions of constant expressions, but they can never be ICEs
6365 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006366 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006367 case UO_Extension:
6368 case UO_LNot:
6369 case UO_Plus:
6370 case UO_Minus:
6371 case UO_Not:
6372 case UO_Real:
6373 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006374 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006375 }
6376
6377 // OffsetOf falls through here.
6378 }
6379 case Expr::OffsetOfExprClass: {
6380 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006381 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006382 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006383 // compliance: we should warn earlier for offsetof expressions with
6384 // array subscripts that aren't ICEs, and if the array subscripts
6385 // are ICEs, the value of the offsetof must be an integer constant.
6386 return CheckEvalInICE(E, Ctx);
6387 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006388 case Expr::UnaryExprOrTypeTraitExprClass: {
6389 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6390 if ((Exp->getKind() == UETT_SizeOf) &&
6391 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006392 return ICEDiag(2, E->getLocStart());
6393 return NoDiag();
6394 }
6395 case Expr::BinaryOperatorClass: {
6396 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6397 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006398 case BO_PtrMemD:
6399 case BO_PtrMemI:
6400 case BO_Assign:
6401 case BO_MulAssign:
6402 case BO_DivAssign:
6403 case BO_RemAssign:
6404 case BO_AddAssign:
6405 case BO_SubAssign:
6406 case BO_ShlAssign:
6407 case BO_ShrAssign:
6408 case BO_AndAssign:
6409 case BO_XorAssign:
6410 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006411 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6412 // constant expressions, but they can never be ICEs because an ICE cannot
6413 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006414 return ICEDiag(2, E->getLocStart());
6415
John McCall2de56d12010-08-25 11:45:40 +00006416 case BO_Mul:
6417 case BO_Div:
6418 case BO_Rem:
6419 case BO_Add:
6420 case BO_Sub:
6421 case BO_Shl:
6422 case BO_Shr:
6423 case BO_LT:
6424 case BO_GT:
6425 case BO_LE:
6426 case BO_GE:
6427 case BO_EQ:
6428 case BO_NE:
6429 case BO_And:
6430 case BO_Xor:
6431 case BO_Or:
6432 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006433 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6434 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006435 if (Exp->getOpcode() == BO_Div ||
6436 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006437 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006438 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006439 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006440 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006441 if (REval == 0)
6442 return ICEDiag(1, E->getLocStart());
6443 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006444 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006445 if (LEval.isMinSignedValue())
6446 return ICEDiag(1, E->getLocStart());
6447 }
6448 }
6449 }
John McCall2de56d12010-08-25 11:45:40 +00006450 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006451 if (Ctx.getLangOptions().C99) {
6452 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6453 // if it isn't evaluated.
6454 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6455 return ICEDiag(1, E->getLocStart());
6456 } else {
6457 // In both C89 and C++, commas in ICEs are illegal.
6458 return ICEDiag(2, E->getLocStart());
6459 }
6460 }
6461 if (LHSResult.Val >= RHSResult.Val)
6462 return LHSResult;
6463 return RHSResult;
6464 }
John McCall2de56d12010-08-25 11:45:40 +00006465 case BO_LAnd:
6466 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006467 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6468 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6469 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6470 // Rare case where the RHS has a comma "side-effect"; we need
6471 // to actually check the condition to see whether the side
6472 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006473 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006474 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006475 return RHSResult;
6476 return NoDiag();
6477 }
6478
6479 if (LHSResult.Val >= RHSResult.Val)
6480 return LHSResult;
6481 return RHSResult;
6482 }
6483 }
6484 }
6485 case Expr::ImplicitCastExprClass:
6486 case Expr::CStyleCastExprClass:
6487 case Expr::CXXFunctionalCastExprClass:
6488 case Expr::CXXStaticCastExprClass:
6489 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006490 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006491 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006492 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006493 if (isa<ExplicitCastExpr>(E)) {
6494 if (const FloatingLiteral *FL
6495 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6496 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6497 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6498 APSInt IgnoredVal(DestWidth, !DestSigned);
6499 bool Ignored;
6500 // If the value does not fit in the destination type, the behavior is
6501 // undefined, so we are not required to treat it as a constant
6502 // expression.
6503 if (FL->getValue().convertToInteger(IgnoredVal,
6504 llvm::APFloat::rmTowardZero,
6505 &Ignored) & APFloat::opInvalidOp)
6506 return ICEDiag(2, E->getLocStart());
6507 return NoDiag();
6508 }
6509 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006510 switch (cast<CastExpr>(E)->getCastKind()) {
6511 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006512 case CK_AtomicToNonAtomic:
6513 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006514 case CK_NoOp:
6515 case CK_IntegralToBoolean:
6516 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006517 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006518 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006519 return ICEDiag(2, E->getLocStart());
6520 }
John McCalld905f5a2010-05-07 05:32:02 +00006521 }
John McCall56ca35d2011-02-17 10:25:35 +00006522 case Expr::BinaryConditionalOperatorClass: {
6523 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6524 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6525 if (CommonResult.Val == 2) return CommonResult;
6526 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6527 if (FalseResult.Val == 2) return FalseResult;
6528 if (CommonResult.Val == 1) return CommonResult;
6529 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006530 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006531 return FalseResult;
6532 }
John McCalld905f5a2010-05-07 05:32:02 +00006533 case Expr::ConditionalOperatorClass: {
6534 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6535 // If the condition (ignoring parens) is a __builtin_constant_p call,
6536 // then only the true side is actually considered in an integer constant
6537 // expression, and it is fully evaluated. This is an important GNU
6538 // extension. See GCC PR38377 for discussion.
6539 if (const CallExpr *CallCE
6540 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006541 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6542 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006543 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006544 if (CondResult.Val == 2)
6545 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006546
Richard Smithf48fdb02011-12-09 22:58:01 +00006547 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6548 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006549
John McCalld905f5a2010-05-07 05:32:02 +00006550 if (TrueResult.Val == 2)
6551 return TrueResult;
6552 if (FalseResult.Val == 2)
6553 return FalseResult;
6554 if (CondResult.Val == 1)
6555 return CondResult;
6556 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6557 return NoDiag();
6558 // Rare case where the diagnostics depend on which side is evaluated
6559 // Note that if we get here, CondResult is 0, and at least one of
6560 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006561 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006562 return FalseResult;
6563 }
6564 return TrueResult;
6565 }
6566 case Expr::CXXDefaultArgExprClass:
6567 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6568 case Expr::ChooseExprClass: {
6569 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6570 }
6571 }
6572
David Blaikie30263482012-01-20 21:50:17 +00006573 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006574}
6575
Richard Smithf48fdb02011-12-09 22:58:01 +00006576/// Evaluate an expression as a C++11 integral constant expression.
6577static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6578 const Expr *E,
6579 llvm::APSInt *Value,
6580 SourceLocation *Loc) {
6581 if (!E->getType()->isIntegralOrEnumerationType()) {
6582 if (Loc) *Loc = E->getExprLoc();
6583 return false;
6584 }
6585
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006586 APValue Result;
6587 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006588 return false;
6589
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006590 assert(Result.isInt() && "pointer cast to int is not an ICE");
6591 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006592 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006593}
6594
Richard Smithdd1f29b2011-12-12 09:28:41 +00006595bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006596 if (Ctx.getLangOptions().CPlusPlus0x)
6597 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6598
John McCalld905f5a2010-05-07 05:32:02 +00006599 ICEDiag d = CheckICE(this, Ctx);
6600 if (d.Val != 0) {
6601 if (Loc) *Loc = d.Loc;
6602 return false;
6603 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006604 return true;
6605}
6606
6607bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6608 SourceLocation *Loc, bool isEvaluated) const {
6609 if (Ctx.getLangOptions().CPlusPlus0x)
6610 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6611
6612 if (!isIntegerConstantExpr(Ctx, Loc))
6613 return false;
6614 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006615 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006616 return true;
6617}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006618
Richard Smith70488e22012-02-14 21:38:30 +00006619bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6620 return CheckICE(this, Ctx).Val == 0;
6621}
6622
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006623bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6624 SourceLocation *Loc) const {
6625 // We support this checking in C++98 mode in order to diagnose compatibility
6626 // issues.
6627 assert(Ctx.getLangOptions().CPlusPlus);
6628
Richard Smith70488e22012-02-14 21:38:30 +00006629 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006630 Expr::EvalStatus Status;
6631 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6632 Status.Diag = &Diags;
6633 EvalInfo Info(Ctx, Status);
6634
6635 APValue Scratch;
6636 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6637
6638 if (!Diags.empty()) {
6639 IsConstExpr = false;
6640 if (Loc) *Loc = Diags[0].first;
6641 } else if (!IsConstExpr) {
6642 // FIXME: This shouldn't happen.
6643 if (Loc) *Loc = getExprLoc();
6644 }
6645
6646 return IsConstExpr;
6647}
Richard Smith745f5142012-01-27 01:14:48 +00006648
6649bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6650 llvm::SmallVectorImpl<
6651 PartialDiagnosticAt> &Diags) {
6652 // FIXME: It would be useful to check constexpr function templates, but at the
6653 // moment the constant expression evaluator cannot cope with the non-rigorous
6654 // ASTs which we build for dependent expressions.
6655 if (FD->isDependentContext())
6656 return true;
6657
6658 Expr::EvalStatus Status;
6659 Status.Diag = &Diags;
6660
6661 EvalInfo Info(FD->getASTContext(), Status);
6662 Info.CheckingPotentialConstantExpression = true;
6663
6664 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6665 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6666
6667 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6668 // is a temporary being used as the 'this' pointer.
6669 LValue This;
6670 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006671 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006672
Richard Smith745f5142012-01-27 01:14:48 +00006673 ArrayRef<const Expr*> Args;
6674
6675 SourceLocation Loc = FD->getLocation();
6676
Richard Smith1aa0be82012-03-03 22:46:17 +00006677 APValue Scratch;
6678 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006679 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006680 else
Richard Smith745f5142012-01-27 01:14:48 +00006681 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6682 Args, FD->getBody(), Info, Scratch);
6683
6684 return Diags.empty();
6685}