blob: 08794f355f73341767efc0f0807bb1e6aca40d47 [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 Smithcc5d4f62011-11-07 09:22:26 +00001521 const 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 Smith1aa0be82012-03-03 22:46:17 +00001619 Obj = APValue(*O);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001620 return true;
1621}
1622
Richard Smithf15fda02012-02-02 01:16:57 +00001623/// Find the position where two subobject designators diverge, or equivalently
1624/// the length of the common initial subsequence.
1625static unsigned FindDesignatorMismatch(QualType ObjType,
1626 const SubobjectDesignator &A,
1627 const SubobjectDesignator &B,
1628 bool &WasArrayIndex) {
1629 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1630 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001631 if (!ObjType.isNull() &&
1632 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001633 // Next subobject is an array element.
1634 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1635 WasArrayIndex = true;
1636 return I;
1637 }
Richard Smith86024012012-02-18 22:04:06 +00001638 if (ObjType->isAnyComplexType())
1639 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1640 else
1641 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001642 } else {
1643 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1644 WasArrayIndex = false;
1645 return I;
1646 }
1647 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1648 // Next subobject is a field.
1649 ObjType = FD->getType();
1650 else
1651 // Next subobject is a base class.
1652 ObjType = QualType();
1653 }
1654 }
1655 WasArrayIndex = false;
1656 return I;
1657}
1658
1659/// Determine whether the given subobject designators refer to elements of the
1660/// same array object.
1661static bool AreElementsOfSameArray(QualType ObjType,
1662 const SubobjectDesignator &A,
1663 const SubobjectDesignator &B) {
1664 if (A.Entries.size() != B.Entries.size())
1665 return false;
1666
1667 bool IsArray = A.MostDerivedArraySize != 0;
1668 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1669 // A is a subobject of the array element.
1670 return false;
1671
1672 // If A (and B) designates an array element, the last entry will be the array
1673 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1674 // of length 1' case, and the entire path must match.
1675 bool WasArrayIndex;
1676 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1677 return CommonLength >= A.Entries.size() - IsArray;
1678}
1679
Richard Smith180f4792011-11-10 06:34:14 +00001680/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1681/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1682/// for looking up the glvalue referred to by an entity of reference type.
1683///
1684/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001685/// \param Conv - The expression for which we are performing the conversion.
1686/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001687/// \param Type - The type we expect this conversion to produce, before
1688/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001689/// \param LVal - The glvalue on which we are attempting to perform this action.
1690/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001691static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1692 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001693 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001694 if (LVal.Designator.Invalid)
1695 // A diagnostic will have already been produced.
1696 return false;
1697
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001698 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001699 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001700
Richard Smithf48fdb02011-12-09 22:58:01 +00001701 if (!LVal.Base) {
1702 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001703 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1704 return false;
1705 }
1706
Richard Smith83587db2012-02-15 02:18:13 +00001707 CallStackFrame *Frame = 0;
1708 if (LVal.CallIndex) {
1709 Frame = Info.getCallFrame(LVal.CallIndex);
1710 if (!Frame) {
1711 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1712 NoteLValueLocation(Info, LVal.Base);
1713 return false;
1714 }
1715 }
1716
Richard Smith7098cbd2011-12-21 05:04:46 +00001717 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1718 // is not a constant expression (even if the object is non-volatile). We also
1719 // apply this rule to C++98, in order to conform to the expected 'volatile'
1720 // semantics.
1721 if (Type.isVolatileQualified()) {
1722 if (Info.getLangOpts().CPlusPlus)
1723 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1724 else
1725 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001726 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001727 }
Richard Smithc49bd112011-10-28 17:51:58 +00001728
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001729 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001730 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1731 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001732 // expressions are constant expressions too. Inside constexpr functions,
1733 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001734 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001735 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001736 if (const VarDecl *VDef = VD->getDefinition())
1737 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001738 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001739 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001740 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001741 }
1742
Richard Smith7098cbd2011-12-21 05:04:46 +00001743 // DR1313: If the object is volatile-qualified but the glvalue was not,
1744 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001745 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001746 if (VT.isVolatileQualified()) {
1747 if (Info.getLangOpts().CPlusPlus) {
1748 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1749 Info.Note(VD->getLocation(), diag::note_declared_at);
1750 } else {
1751 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001752 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001753 return false;
1754 }
1755
1756 if (!isa<ParmVarDecl>(VD)) {
1757 if (VD->isConstexpr()) {
1758 // OK, we can read this variable.
1759 } else if (VT->isIntegralOrEnumerationType()) {
1760 if (!VT.isConstQualified()) {
1761 if (Info.getLangOpts().CPlusPlus) {
1762 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1763 Info.Note(VD->getLocation(), diag::note_declared_at);
1764 } else {
1765 Info.Diag(Loc);
1766 }
1767 return false;
1768 }
1769 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1770 // We support folding of const floating-point types, in order to make
1771 // static const data members of such types (supported as an extension)
1772 // more useful.
1773 if (Info.getLangOpts().CPlusPlus0x) {
1774 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1775 Info.Note(VD->getLocation(), diag::note_declared_at);
1776 } else {
1777 Info.CCEDiag(Loc);
1778 }
1779 } else {
1780 // FIXME: Allow folding of values of any literal type in all languages.
1781 if (Info.getLangOpts().CPlusPlus0x) {
1782 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1783 Info.Note(VD->getLocation(), diag::note_declared_at);
1784 } else {
1785 Info.Diag(Loc);
1786 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001787 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001788 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001789 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001790
Richard Smithf48fdb02011-12-09 22:58:01 +00001791 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001792 return false;
1793
Richard Smith47a1eed2011-10-29 20:57:55 +00001794 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001795 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001796
1797 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1798 // conversion. This happens when the declaration and the lvalue should be
1799 // considered synonymous, for instance when initializing an array of char
1800 // from a string literal. Continue as if the initializer lvalue was the
1801 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001802 assert(RVal.getLValueOffset().isZero() &&
1803 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001804 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001805
1806 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1807 Frame = Info.getCallFrame(CallIndex);
1808 if (!Frame) {
1809 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1810 NoteLValueLocation(Info, RVal.getLValueBase());
1811 return false;
1812 }
1813 } else {
1814 Frame = 0;
1815 }
Richard Smithc49bd112011-10-28 17:51:58 +00001816 }
1817
Richard Smith7098cbd2011-12-21 05:04:46 +00001818 // Volatile temporary objects cannot be read in constant expressions.
1819 if (Base->getType().isVolatileQualified()) {
1820 if (Info.getLangOpts().CPlusPlus) {
1821 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1822 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1823 } else {
1824 Info.Diag(Loc);
1825 }
1826 return false;
1827 }
1828
Richard Smithcc5d4f62011-11-07 09:22:26 +00001829 if (Frame) {
1830 // If this is a temporary expression with a nontrivial initializer, grab the
1831 // value from the relevant stack frame.
1832 RVal = Frame->Temporaries[Base];
1833 } else if (const CompoundLiteralExpr *CLE
1834 = dyn_cast<CompoundLiteralExpr>(Base)) {
1835 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1836 // initializer until now for such expressions. Such an expression can't be
1837 // an ICE in C, so this only matters for fold.
1838 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1839 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1840 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001841 } else if (isa<StringLiteral>(Base)) {
1842 // We represent a string literal array as an lvalue pointing at the
1843 // corresponding expression, rather than building an array of chars.
1844 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001845 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001846 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001847 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001848 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001849 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001850
Richard Smithf48fdb02011-12-09 22:58:01 +00001851 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1852 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001853}
1854
Richard Smith59efe262011-11-11 04:05:33 +00001855/// Build an lvalue for the object argument of a member function call.
1856static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1857 LValue &This) {
1858 if (Object->getType()->isPointerType())
1859 return EvaluatePointer(Object, This, Info);
1860
1861 if (Object->isGLValue())
1862 return EvaluateLValue(Object, This, Info);
1863
Richard Smithe24f5fc2011-11-17 22:56:20 +00001864 if (Object->getType()->isLiteralType())
1865 return EvaluateTemporary(Object, This, Info);
1866
1867 return false;
1868}
1869
1870/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1871/// lvalue referring to the result.
1872///
1873/// \param Info - Information about the ongoing evaluation.
1874/// \param BO - The member pointer access operation.
1875/// \param LV - Filled in with a reference to the resulting object.
1876/// \param IncludeMember - Specifies whether the member itself is included in
1877/// the resulting LValue subobject designator. This is not possible when
1878/// creating a bound member function.
1879/// \return The field or method declaration to which the member pointer refers,
1880/// or 0 if evaluation fails.
1881static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1882 const BinaryOperator *BO,
1883 LValue &LV,
1884 bool IncludeMember = true) {
1885 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1886
Richard Smith745f5142012-01-27 01:14:48 +00001887 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1888 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001889 return 0;
1890
1891 MemberPtr MemPtr;
1892 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1893 return 0;
1894
1895 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1896 // member value, the behavior is undefined.
1897 if (!MemPtr.getDecl())
1898 return 0;
1899
Richard Smith745f5142012-01-27 01:14:48 +00001900 if (!EvalObjOK)
1901 return 0;
1902
Richard Smithe24f5fc2011-11-17 22:56:20 +00001903 if (MemPtr.isDerivedMember()) {
1904 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001905 // The end of the derived-to-base path for the base object must match the
1906 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001907 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001908 LV.Designator.Entries.size())
1909 return 0;
1910 unsigned PathLengthToMember =
1911 LV.Designator.Entries.size() - MemPtr.Path.size();
1912 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1913 const CXXRecordDecl *LVDecl = getAsBaseClass(
1914 LV.Designator.Entries[PathLengthToMember + I]);
1915 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1916 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1917 return 0;
1918 }
1919
1920 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001921 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1922 PathLengthToMember))
1923 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001924 } else if (!MemPtr.Path.empty()) {
1925 // Extend the LValue path with the member pointer's path.
1926 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1927 MemPtr.Path.size() + IncludeMember);
1928
1929 // Walk down to the appropriate base class.
1930 QualType LVType = BO->getLHS()->getType();
1931 if (const PointerType *PT = LVType->getAs<PointerType>())
1932 LVType = PT->getPointeeType();
1933 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1934 assert(RD && "member pointer access on non-class-type expression");
1935 // The first class in the path is that of the lvalue.
1936 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1937 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001938 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001939 RD = Base;
1940 }
1941 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001942 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001943 }
1944
1945 // Add the member. Note that we cannot build bound member functions here.
1946 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001947 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1948 HandleLValueMember(Info, BO, LV, FD);
1949 else if (const IndirectFieldDecl *IFD =
1950 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1951 HandleLValueIndirectMember(Info, BO, LV, IFD);
1952 else
1953 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001954 }
1955
1956 return MemPtr.getDecl();
1957}
1958
1959/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1960/// the provided lvalue, which currently refers to the base object.
1961static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1962 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001963 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001964 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001965 return false;
1966
Richard Smithb4e85ed2012-01-06 16:39:00 +00001967 QualType TargetQT = E->getType();
1968 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1969 TargetQT = PT->getPointeeType();
1970
1971 // Check this cast lands within the final derived-to-base subobject path.
1972 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1973 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1974 << D.MostDerivedType << TargetQT;
1975 return false;
1976 }
1977
Richard Smithe24f5fc2011-11-17 22:56:20 +00001978 // Check the type of the final cast. We don't need to check the path,
1979 // since a cast can only be formed if the path is unique.
1980 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001981 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1982 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001983 if (NewEntriesSize == D.MostDerivedPathLength)
1984 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1985 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001987 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1988 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1989 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001991 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001992
1993 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001994 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00001995}
1996
Mike Stumpc4c90452009-10-27 22:09:17 +00001997namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00001998enum EvalStmtResult {
1999 /// Evaluation failed.
2000 ESR_Failed,
2001 /// Hit a 'return' statement.
2002 ESR_Returned,
2003 /// Evaluation succeeded.
2004 ESR_Succeeded
2005};
2006}
2007
2008// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002009static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002010 const Stmt *S) {
2011 switch (S->getStmtClass()) {
2012 default:
2013 return ESR_Failed;
2014
2015 case Stmt::NullStmtClass:
2016 case Stmt::DeclStmtClass:
2017 return ESR_Succeeded;
2018
Richard Smithc1c5f272011-12-13 06:39:58 +00002019 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002020 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002021 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002022 return ESR_Failed;
2023 return ESR_Returned;
2024 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002025
2026 case Stmt::CompoundStmtClass: {
2027 const CompoundStmt *CS = cast<CompoundStmt>(S);
2028 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2029 BE = CS->body_end(); BI != BE; ++BI) {
2030 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2031 if (ESR != ESR_Succeeded)
2032 return ESR;
2033 }
2034 return ESR_Succeeded;
2035 }
2036 }
2037}
2038
Richard Smith61802452011-12-22 02:22:31 +00002039/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2040/// default constructor. If so, we'll fold it whether or not it's marked as
2041/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2042/// so we need special handling.
2043static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002044 const CXXConstructorDecl *CD,
2045 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002046 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2047 return false;
2048
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002049 // Value-initialization does not call a trivial default constructor, so such a
2050 // call is a core constant expression whether or not the constructor is
2051 // constexpr.
2052 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002053 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002054 // FIXME: If DiagDecl is an implicitly-declared special member function,
2055 // we should be much more explicit about why it's not constexpr.
2056 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2057 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2058 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002059 } else {
2060 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2061 }
2062 }
2063 return true;
2064}
2065
Richard Smithc1c5f272011-12-13 06:39:58 +00002066/// CheckConstexprFunction - Check that a function can be called in a constant
2067/// expression.
2068static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2069 const FunctionDecl *Declaration,
2070 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002071 // Potential constant expressions can contain calls to declared, but not yet
2072 // defined, constexpr functions.
2073 if (Info.CheckingPotentialConstantExpression && !Definition &&
2074 Declaration->isConstexpr())
2075 return false;
2076
Richard Smithc1c5f272011-12-13 06:39:58 +00002077 // Can we evaluate this function call?
2078 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2079 return true;
2080
2081 if (Info.getLangOpts().CPlusPlus0x) {
2082 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002083 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2084 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002085 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2086 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2087 << DiagDecl;
2088 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2089 } else {
2090 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2091 }
2092 return false;
2093}
2094
Richard Smith180f4792011-11-10 06:34:14 +00002095namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002096typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002097}
2098
2099/// EvaluateArgs - Evaluate the arguments to a function call.
2100static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2101 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002102 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002103 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002104 I != E; ++I) {
2105 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2106 // If we're checking for a potential constant expression, evaluate all
2107 // initializers even if some of them fail.
2108 if (!Info.keepEvaluatingAfterFailure())
2109 return false;
2110 Success = false;
2111 }
2112 }
2113 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002114}
2115
Richard Smithd0dccea2011-10-28 22:34:42 +00002116/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002117static bool HandleFunctionCall(SourceLocation CallLoc,
2118 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002119 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002120 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002121 ArgVector ArgValues(Args.size());
2122 if (!EvaluateArgs(Args, ArgValues, Info))
2123 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002124
Richard Smith745f5142012-01-27 01:14:48 +00002125 if (!Info.CheckCallLimit(CallLoc))
2126 return false;
2127
2128 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002129 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2130}
2131
Richard Smith180f4792011-11-10 06:34:14 +00002132/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002133static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002134 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002135 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002136 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002137 ArgVector ArgValues(Args.size());
2138 if (!EvaluateArgs(Args, ArgValues, Info))
2139 return false;
2140
Richard Smith745f5142012-01-27 01:14:48 +00002141 if (!Info.CheckCallLimit(CallLoc))
2142 return false;
2143
Richard Smith86c3ae42012-02-13 03:54:03 +00002144 const CXXRecordDecl *RD = Definition->getParent();
2145 if (RD->getNumVBases()) {
2146 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2147 return false;
2148 }
2149
Richard Smith745f5142012-01-27 01:14:48 +00002150 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002151
2152 // If it's a delegating constructor, just delegate.
2153 if (Definition->isDelegatingConstructor()) {
2154 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002155 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002156 }
2157
Richard Smith610a60c2012-01-10 04:32:03 +00002158 // For a trivial copy or move constructor, perform an APValue copy. This is
2159 // essential for unions, where the operations performed by the constructor
2160 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002161 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002162 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2163 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002164 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002165 RHS.setFrom(Info.Ctx, ArgValues[0]);
2166 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2167 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002168 }
2169
2170 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002171 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002172 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2173 std::distance(RD->field_begin(), RD->field_end()));
2174
2175 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2176
Richard Smith745f5142012-01-27 01:14:48 +00002177 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002178 unsigned BasesSeen = 0;
2179#ifndef NDEBUG
2180 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2181#endif
2182 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2183 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002184 LValue Subobject = This;
2185 APValue *Value = &Result;
2186
2187 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002188 if ((*I)->isBaseInitializer()) {
2189 QualType BaseType((*I)->getBaseClass(), 0);
2190#ifndef NDEBUG
2191 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002192 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002193 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2194 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2195 "base class initializers not in expected order");
2196 ++BaseIt;
2197#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002198 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002199 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002200 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002201 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002202 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002203 if (RD->isUnion()) {
2204 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002205 Value = &Result.getUnionValue();
2206 } else {
2207 Value = &Result.getStructField(FD->getFieldIndex());
2208 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002209 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002210 // Walk the indirect field decl's chain to find the object to initialize,
2211 // and make sure we've initialized every step along it.
2212 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2213 CE = IFD->chain_end();
2214 C != CE; ++C) {
2215 FieldDecl *FD = cast<FieldDecl>(*C);
2216 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2217 // Switch the union field if it differs. This happens if we had
2218 // preceding zero-initialization, and we're now initializing a union
2219 // subobject other than the first.
2220 // FIXME: In this case, the values of the other subobjects are
2221 // specified, since zero-initialization sets all padding bits to zero.
2222 if (Value->isUninit() ||
2223 (Value->isUnion() && Value->getUnionField() != FD)) {
2224 if (CD->isUnion())
2225 *Value = APValue(FD);
2226 else
2227 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2228 std::distance(CD->field_begin(), CD->field_end()));
2229 }
Richard Smith745f5142012-01-27 01:14:48 +00002230 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002231 if (CD->isUnion())
2232 Value = &Value->getUnionValue();
2233 else
2234 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002235 }
Richard Smith180f4792011-11-10 06:34:14 +00002236 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002237 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002238 }
Richard Smith745f5142012-01-27 01:14:48 +00002239
Richard Smith83587db2012-02-15 02:18:13 +00002240 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2241 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002242 ? CCEK_Constant : CCEK_MemberInit)) {
2243 // If we're checking for a potential constant expression, evaluate all
2244 // initializers even if some of them fail.
2245 if (!Info.keepEvaluatingAfterFailure())
2246 return false;
2247 Success = false;
2248 }
Richard Smith180f4792011-11-10 06:34:14 +00002249 }
2250
Richard Smith745f5142012-01-27 01:14:48 +00002251 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002252}
2253
Richard Smithd0dccea2011-10-28 22:34:42 +00002254namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002255class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002256 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002257 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002258public:
2259
Richard Smith1e12c592011-10-16 21:26:27 +00002260 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002261
2262 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002263 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002264 return true;
2265 }
2266
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2268 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002269 return Visit(E->getResultExpr());
2270 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002271 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002272 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002273 return true;
2274 return false;
2275 }
John McCallf85e1932011-06-15 23:02:42 +00002276 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002277 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002278 return true;
2279 return false;
2280 }
2281 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002282 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002283 return true;
2284 return false;
2285 }
2286
Mike Stumpc4c90452009-10-27 22:09:17 +00002287 // We don't want to evaluate BlockExprs multiple times, as they generate
2288 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2290 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2291 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002292 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2294 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2295 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2296 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2297 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2298 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002299 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002301 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002302 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002303 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2305 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2306 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2307 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002308 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2310 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2311 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2312 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2313 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002314 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002315 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002316 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002317 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002318 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002319
2320 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002321 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002322 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2323 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002325 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002326 return false;
2327 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002328
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002330};
2331
John McCall56ca35d2011-02-17 10:25:35 +00002332class OpaqueValueEvaluation {
2333 EvalInfo &info;
2334 OpaqueValueExpr *opaqueValue;
2335
2336public:
2337 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2338 Expr *value)
2339 : info(info), opaqueValue(opaqueValue) {
2340
2341 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002342 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002343 this->opaqueValue = 0;
2344 return;
2345 }
John McCall56ca35d2011-02-17 10:25:35 +00002346 }
2347
2348 bool hasError() const { return opaqueValue == 0; }
2349
2350 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002351 // FIXME: For a recursive constexpr call, an outer stack frame might have
2352 // been using this opaque value too, and will now have to re-evaluate the
2353 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002354 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2355 }
2356};
2357
Mike Stumpc4c90452009-10-27 22:09:17 +00002358} // end anonymous namespace
2359
Eli Friedman4efaa272008-11-12 09:44:48 +00002360//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002361// Generic Evaluation
2362//===----------------------------------------------------------------------===//
2363namespace {
2364
Richard Smithf48fdb02011-12-09 22:58:01 +00002365// FIXME: RetTy is always bool. Remove it.
2366template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002367class ExprEvaluatorBase
2368 : public ConstStmtVisitor<Derived, RetTy> {
2369private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002370 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 return static_cast<Derived*>(this)->Success(V, E);
2372 }
Richard Smith51201882011-12-30 21:15:51 +00002373 RetTy DerivedZeroInitialization(const Expr *E) {
2374 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002375 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376
Richard Smith74e1ad92012-02-16 02:46:34 +00002377 // Check whether a conditional operator with a non-constant condition is a
2378 // potential constant expression. If neither arm is a potential constant
2379 // expression, then the conditional operator is not either.
2380 template<typename ConditionalOperator>
2381 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2382 assert(Info.CheckingPotentialConstantExpression);
2383
2384 // Speculatively evaluate both arms.
2385 {
2386 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2387 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2388
2389 StmtVisitorTy::Visit(E->getFalseExpr());
2390 if (Diag.empty())
2391 return;
2392
2393 Diag.clear();
2394 StmtVisitorTy::Visit(E->getTrueExpr());
2395 if (Diag.empty())
2396 return;
2397 }
2398
2399 Error(E, diag::note_constexpr_conditional_never_const);
2400 }
2401
2402
2403 template<typename ConditionalOperator>
2404 bool HandleConditionalOperator(const ConditionalOperator *E) {
2405 bool BoolResult;
2406 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2407 if (Info.CheckingPotentialConstantExpression)
2408 CheckPotentialConstantConditional(E);
2409 return false;
2410 }
2411
2412 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2413 return StmtVisitorTy::Visit(EvalExpr);
2414 }
2415
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002416protected:
2417 EvalInfo &Info;
2418 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2419 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2420
Richard Smithdd1f29b2011-12-12 09:28:41 +00002421 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002422 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002423 }
2424
2425 /// Report an evaluation error. This should only be called when an error is
2426 /// first discovered. When propagating an error, just return false.
2427 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002428 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002429 return false;
2430 }
2431 bool Error(const Expr *E) {
2432 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2433 }
2434
Richard Smith51201882011-12-30 21:15:51 +00002435 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002436
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002437public:
2438 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2439
2440 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002441 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442 }
2443 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002444 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002445 }
2446
2447 RetTy VisitParenExpr(const ParenExpr *E)
2448 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2449 RetTy VisitUnaryExtension(const UnaryOperator *E)
2450 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2451 RetTy VisitUnaryPlus(const UnaryOperator *E)
2452 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2453 RetTy VisitChooseExpr(const ChooseExpr *E)
2454 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2455 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2456 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002457 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2458 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002459 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2460 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002461 // We cannot create any objects for which cleanups are required, so there is
2462 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2463 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2464 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002465
Richard Smithc216a012011-12-12 12:46:16 +00002466 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2467 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2468 return static_cast<Derived*>(this)->VisitCastExpr(E);
2469 }
2470 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2471 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2472 return static_cast<Derived*>(this)->VisitCastExpr(E);
2473 }
2474
Richard Smithe24f5fc2011-11-17 22:56:20 +00002475 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2476 switch (E->getOpcode()) {
2477 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002478 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002479
2480 case BO_Comma:
2481 VisitIgnoredValue(E->getLHS());
2482 return StmtVisitorTy::Visit(E->getRHS());
2483
2484 case BO_PtrMemD:
2485 case BO_PtrMemI: {
2486 LValue Obj;
2487 if (!HandleMemberPointerAccess(Info, E, Obj))
2488 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002489 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002490 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491 return false;
2492 return DerivedSuccess(Result, E);
2493 }
2494 }
2495 }
2496
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002497 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002498 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002499 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2500 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002501 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002502
Richard Smith74e1ad92012-02-16 02:46:34 +00002503 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002504 }
2505
2506 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002507 bool IsBcpCall = false;
2508 // If the condition (ignoring parens) is a __builtin_constant_p call,
2509 // the result is a constant expression if it can be folded without
2510 // side-effects. This is an important GNU extension. See GCC PR38377
2511 // for discussion.
2512 if (const CallExpr *CallCE =
2513 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2514 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2515 IsBcpCall = true;
2516
2517 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2518 // constant expression; we can't check whether it's potentially foldable.
2519 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2520 return false;
2521
2522 FoldConstant Fold(Info);
2523
Richard Smith74e1ad92012-02-16 02:46:34 +00002524 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002525 return false;
2526
2527 if (IsBcpCall)
2528 Fold.Fold(Info);
2529
2530 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002531 }
2532
2533 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002534 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002535 if (!Value) {
2536 const Expr *Source = E->getSourceExpr();
2537 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002538 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002539 if (Source == E) { // sanity checking.
2540 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002541 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002542 }
2543 return StmtVisitorTy::Visit(Source);
2544 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002545 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002546 }
Richard Smithf10d9172011-10-11 21:43:33 +00002547
Richard Smithd0dccea2011-10-28 22:34:42 +00002548 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002549 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002550 QualType CalleeType = Callee->getType();
2551
Richard Smithd0dccea2011-10-28 22:34:42 +00002552 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002553 LValue *This = 0, ThisVal;
2554 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002555 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002556
Richard Smith59efe262011-11-11 04:05:33 +00002557 // Extract function decl and 'this' pointer from the callee.
2558 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002559 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002560 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2561 // Explicit bound member calls, such as x.f() or p->g();
2562 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002563 return false;
2564 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002565 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002566 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002567 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2568 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002569 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2570 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002573 return Error(Callee);
2574
2575 FD = dyn_cast<FunctionDecl>(Member);
2576 if (!FD)
2577 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002578 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002579 LValue Call;
2580 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002581 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002582
Richard Smithb4e85ed2012-01-06 16:39:00 +00002583 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002584 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002585 FD = dyn_cast_or_null<FunctionDecl>(
2586 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002587 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002588 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002589
2590 // Overloaded operator calls to member functions are represented as normal
2591 // calls with '*this' as the first argument.
2592 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2593 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002594 // FIXME: When selecting an implicit conversion for an overloaded
2595 // operator delete, we sometimes try to evaluate calls to conversion
2596 // operators without a 'this' parameter!
2597 if (Args.empty())
2598 return Error(E);
2599
Richard Smith59efe262011-11-11 04:05:33 +00002600 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2601 return false;
2602 This = &ThisVal;
2603 Args = Args.slice(1);
2604 }
2605
2606 // Don't call function pointers which have been cast to some other type.
2607 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002608 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002609 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002610 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002611
Richard Smithb04035a2012-02-01 02:39:43 +00002612 if (This && !This->checkSubobject(Info, E, CSK_This))
2613 return false;
2614
Richard Smith86c3ae42012-02-13 03:54:03 +00002615 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2616 // calls to such functions in constant expressions.
2617 if (This && !HasQualifier &&
2618 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2619 return Error(E, diag::note_constexpr_virtual_call);
2620
Richard Smithc1c5f272011-12-13 06:39:58 +00002621 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002622 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002623 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002624
Richard Smithc1c5f272011-12-13 06:39:58 +00002625 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002626 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2627 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002628 return false;
2629
Richard Smith83587db2012-02-15 02:18:13 +00002630 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002631 }
2632
Richard Smithc49bd112011-10-28 17:51:58 +00002633 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2634 return StmtVisitorTy::Visit(E->getInitializer());
2635 }
Richard Smithf10d9172011-10-11 21:43:33 +00002636 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002637 if (E->getNumInits() == 0)
2638 return DerivedZeroInitialization(E);
2639 if (E->getNumInits() == 1)
2640 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002641 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002642 }
2643 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002644 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002645 }
2646 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002647 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002648 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002649 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002650 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002651 }
Richard Smithf10d9172011-10-11 21:43:33 +00002652
Richard Smith180f4792011-11-10 06:34:14 +00002653 /// A member expression where the object is a prvalue is itself a prvalue.
2654 RetTy VisitMemberExpr(const MemberExpr *E) {
2655 assert(!E->isArrow() && "missing call to bound member function?");
2656
Richard Smith1aa0be82012-03-03 22:46:17 +00002657 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002658 if (!Evaluate(Val, Info, E->getBase()))
2659 return false;
2660
2661 QualType BaseTy = E->getBase()->getType();
2662
2663 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002664 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002665 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2666 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2667 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2668
Richard Smithb4e85ed2012-01-06 16:39:00 +00002669 SubobjectDesignator Designator(BaseTy);
2670 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002671
Richard Smithf48fdb02011-12-09 22:58:01 +00002672 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002673 DerivedSuccess(Val, E);
2674 }
2675
Richard Smithc49bd112011-10-28 17:51:58 +00002676 RetTy VisitCastExpr(const CastExpr *E) {
2677 switch (E->getCastKind()) {
2678 default:
2679 break;
2680
David Chisnall7a7ee302012-01-16 17:27:18 +00002681 case CK_AtomicToNonAtomic:
2682 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002683 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002684 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002685 return StmtVisitorTy::Visit(E->getSubExpr());
2686
2687 case CK_LValueToRValue: {
2688 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002689 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2690 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002691 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002692 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2693 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2694 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002695 return false;
2696 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002697 }
2698 }
2699
Richard Smithf48fdb02011-12-09 22:58:01 +00002700 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002701 }
2702
Richard Smith8327fad2011-10-24 18:44:57 +00002703 /// Visit a value which is evaluated, but whose value is ignored.
2704 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002705 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002706 if (!Evaluate(Scratch, Info, E))
2707 Info.EvalStatus.HasSideEffects = true;
2708 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002709};
2710
2711}
2712
2713//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002714// Common base class for lvalue and temporary evaluation.
2715//===----------------------------------------------------------------------===//
2716namespace {
2717template<class Derived>
2718class LValueExprEvaluatorBase
2719 : public ExprEvaluatorBase<Derived, bool> {
2720protected:
2721 LValue &Result;
2722 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2723 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2724
2725 bool Success(APValue::LValueBase B) {
2726 Result.set(B);
2727 return true;
2728 }
2729
2730public:
2731 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2732 ExprEvaluatorBaseTy(Info), Result(Result) {}
2733
Richard Smith1aa0be82012-03-03 22:46:17 +00002734 bool Success(const APValue &V, const Expr *E) {
2735 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002736 return true;
2737 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002738
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739 bool VisitMemberExpr(const MemberExpr *E) {
2740 // Handle non-static data members.
2741 QualType BaseTy;
2742 if (E->isArrow()) {
2743 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2744 return false;
2745 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002746 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002747 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002748 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2749 return false;
2750 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002751 } else {
2752 if (!this->Visit(E->getBase()))
2753 return false;
2754 BaseTy = E->getBase()->getType();
2755 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002756
Richard Smithd9b02e72012-01-25 22:15:11 +00002757 const ValueDecl *MD = E->getMemberDecl();
2758 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2759 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2760 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2761 (void)BaseTy;
2762 HandleLValueMember(this->Info, E, Result, FD);
2763 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2764 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2765 } else
2766 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002767
Richard Smithd9b02e72012-01-25 22:15:11 +00002768 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002769 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002770 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771 RefValue))
2772 return false;
2773 return Success(RefValue, E);
2774 }
2775 return true;
2776 }
2777
2778 bool VisitBinaryOperator(const BinaryOperator *E) {
2779 switch (E->getOpcode()) {
2780 default:
2781 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2782
2783 case BO_PtrMemD:
2784 case BO_PtrMemI:
2785 return HandleMemberPointerAccess(this->Info, E, Result);
2786 }
2787 }
2788
2789 bool VisitCastExpr(const CastExpr *E) {
2790 switch (E->getCastKind()) {
2791 default:
2792 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2793
2794 case CK_DerivedToBase:
2795 case CK_UncheckedDerivedToBase: {
2796 if (!this->Visit(E->getSubExpr()))
2797 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002798
2799 // Now figure out the necessary offset to add to the base LV to get from
2800 // the derived class to the base class.
2801 QualType Type = E->getSubExpr()->getType();
2802
2803 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2804 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002805 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002806 *PathI))
2807 return false;
2808 Type = (*PathI)->getType();
2809 }
2810
2811 return true;
2812 }
2813 }
2814 }
2815};
2816}
2817
2818//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002819// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002820//
2821// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2822// function designators (in C), decl references to void objects (in C), and
2823// temporaries (if building with -Wno-address-of-temporary).
2824//
2825// LValue evaluation produces values comprising a base expression of one of the
2826// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002827// - Declarations
2828// * VarDecl
2829// * FunctionDecl
2830// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002831// * CompoundLiteralExpr in C
2832// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002833// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002834// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002835// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002836// * ObjCEncodeExpr
2837// * AddrLabelExpr
2838// * BlockExpr
2839// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002840// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002841// * Any Expr, with a CallIndex indicating the function in which the temporary
2842// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002843// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002844//===----------------------------------------------------------------------===//
2845namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002846class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002847 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002848public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002849 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2850 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002851
Richard Smithc49bd112011-10-28 17:51:58 +00002852 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2853
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002854 bool VisitDeclRefExpr(const DeclRefExpr *E);
2855 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002856 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002857 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2858 bool VisitMemberExpr(const MemberExpr *E);
2859 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2860 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002861 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002862 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2863 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002864 bool VisitUnaryReal(const UnaryOperator *E);
2865 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002866
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002867 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002868 switch (E->getCastKind()) {
2869 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002870 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002871
Eli Friedmandb924222011-10-11 00:13:24 +00002872 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002873 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002874 if (!Visit(E->getSubExpr()))
2875 return false;
2876 Result.Designator.setInvalid();
2877 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002878
Richard Smithe24f5fc2011-11-17 22:56:20 +00002879 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002880 if (!Visit(E->getSubExpr()))
2881 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002882 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002883 }
2884 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002885};
2886} // end anonymous namespace
2887
Richard Smithc49bd112011-10-28 17:51:58 +00002888/// Evaluate an expression as an lvalue. This can be legitimately called on
2889/// expressions which are not glvalues, in a few cases:
2890/// * function designators in C,
2891/// * "extern void" objects,
2892/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002893static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002894 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2895 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2896 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002897 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002898}
2899
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002900bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002901 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2902 return Success(FD);
2903 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002904 return VisitVarDecl(E, VD);
2905 return Error(E);
2906}
Richard Smith436c8892011-10-24 23:14:33 +00002907
Richard Smithc49bd112011-10-28 17:51:58 +00002908bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002909 if (!VD->getType()->isReferenceType()) {
2910 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002911 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002912 return true;
2913 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002914 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002915 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002916
Richard Smith1aa0be82012-03-03 22:46:17 +00002917 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002918 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2919 return false;
2920 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002921}
2922
Richard Smithbd552ef2011-10-31 05:52:43 +00002923bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2924 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002925 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002926 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002927 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2928
Richard Smith83587db2012-02-15 02:18:13 +00002929 Result.set(E, Info.CurrentCall->Index);
2930 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2931 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932 }
2933
2934 // Materialization of an lvalue temporary occurs when we need to force a copy
2935 // (for instance, if it's a bitfield).
2936 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2937 if (!Visit(E->GetTemporaryExpr()))
2938 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002939 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002940 Info.CurrentCall->Temporaries[E]))
2941 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002942 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002943 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002944}
2945
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002946bool
2947LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002948 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2949 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2950 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002951 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002952}
2953
Richard Smith47d21452011-12-27 12:18:28 +00002954bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2955 if (E->isTypeOperand())
2956 return Success(E);
2957 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2958 if (RD && RD->isPolymorphic()) {
2959 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2960 << E->getExprOperand()->getType()
2961 << E->getExprOperand()->getSourceRange();
2962 return false;
2963 }
2964 return Success(E);
2965}
2966
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002967bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002968 // Handle static data members.
2969 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2970 VisitIgnoredValue(E->getBase());
2971 return VisitVarDecl(E, VD);
2972 }
2973
Richard Smithd0dccea2011-10-28 22:34:42 +00002974 // Handle static member functions.
2975 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2976 if (MD->isStatic()) {
2977 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002978 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002979 }
2980 }
2981
Richard Smith180f4792011-11-10 06:34:14 +00002982 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002983 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002984}
2985
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002986bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002987 // FIXME: Deal with vectors as array subscript bases.
2988 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002989 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002990
Anders Carlsson3068d112008-11-16 19:01:22 +00002991 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002992 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002993
Anders Carlsson3068d112008-11-16 19:01:22 +00002994 APSInt Index;
2995 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002996 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002997 int64_t IndexValue
2998 = Index.isSigned() ? Index.getSExtValue()
2999 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003000
Richard Smithb4e85ed2012-01-06 16:39:00 +00003001 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003002}
Eli Friedman4efaa272008-11-12 09:44:48 +00003003
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003004bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003005 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003006}
3007
Richard Smith86024012012-02-18 22:04:06 +00003008bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3009 if (!Visit(E->getSubExpr()))
3010 return false;
3011 // __real is a no-op on scalar lvalues.
3012 if (E->getSubExpr()->getType()->isAnyComplexType())
3013 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3014 return true;
3015}
3016
3017bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3018 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3019 "lvalue __imag__ on scalar?");
3020 if (!Visit(E->getSubExpr()))
3021 return false;
3022 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3023 return true;
3024}
3025
Eli Friedman4efaa272008-11-12 09:44:48 +00003026//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003027// Pointer Evaluation
3028//===----------------------------------------------------------------------===//
3029
Anders Carlssonc754aa62008-07-08 05:13:58 +00003030namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003031class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003032 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003033 LValue &Result;
3034
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003035 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003036 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003037 return true;
3038 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003039public:
Mike Stump1eb44332009-09-09 15:08:12 +00003040
John McCallefdb83e2010-05-07 21:00:08 +00003041 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003042 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003043
Richard Smith1aa0be82012-03-03 22:46:17 +00003044 bool Success(const APValue &V, const Expr *E) {
3045 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046 return true;
3047 }
Richard Smith51201882011-12-30 21:15:51 +00003048 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003049 return Success((Expr*)0);
3050 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003051
John McCallefdb83e2010-05-07 21:00:08 +00003052 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003053 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003054 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003055 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003056 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003057 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3058 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003060 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003061 bool VisitCallExpr(const CallExpr *E);
3062 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003063 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003064 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003065 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003066 }
Richard Smith180f4792011-11-10 06:34:14 +00003067 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3068 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003069 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003070 Result = *Info.CurrentCall->This;
3071 return true;
3072 }
John McCall56ca35d2011-02-17 10:25:35 +00003073
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003074 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003075};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003076} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003077
John McCallefdb83e2010-05-07 21:00:08 +00003078static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003079 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003080 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003081}
3082
John McCallefdb83e2010-05-07 21:00:08 +00003083bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003084 if (E->getOpcode() != BO_Add &&
3085 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003086 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003087
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003088 const Expr *PExp = E->getLHS();
3089 const Expr *IExp = E->getRHS();
3090 if (IExp->getType()->isPointerType())
3091 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Richard Smith745f5142012-01-27 01:14:48 +00003093 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3094 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003095 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003096
John McCallefdb83e2010-05-07 21:00:08 +00003097 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003098 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003099 return false;
3100 int64_t AdditionalOffset
3101 = Offset.isSigned() ? Offset.getSExtValue()
3102 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003103 if (E->getOpcode() == BO_Sub)
3104 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003105
Richard Smith180f4792011-11-10 06:34:14 +00003106 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003107 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3108 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003109}
Eli Friedman4efaa272008-11-12 09:44:48 +00003110
John McCallefdb83e2010-05-07 21:00:08 +00003111bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3112 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003113}
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003115bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3116 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003117
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003118 switch (E->getCastKind()) {
3119 default:
3120 break;
3121
John McCall2de56d12010-08-25 11:45:40 +00003122 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003123 case CK_CPointerToObjCPointerCast:
3124 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003125 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003126 if (!Visit(SubExpr))
3127 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003128 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3129 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3130 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003131 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003132 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003133 if (SubExpr->getType()->isVoidPointerType())
3134 CCEDiag(E, diag::note_constexpr_invalid_cast)
3135 << 3 << SubExpr->getType();
3136 else
3137 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3138 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003139 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003140
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003141 case CK_DerivedToBase:
3142 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003143 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003144 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003145 if (!Result.Base && Result.Offset.isZero())
3146 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003147
Richard Smith180f4792011-11-10 06:34:14 +00003148 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003149 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003150 QualType Type =
3151 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003152
Richard Smith180f4792011-11-10 06:34:14 +00003153 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003154 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003155 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3156 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003157 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003158 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003159 }
3160
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161 return true;
3162 }
3163
Richard Smithe24f5fc2011-11-17 22:56:20 +00003164 case CK_BaseToDerived:
3165 if (!Visit(E->getSubExpr()))
3166 return false;
3167 if (!Result.Base && Result.Offset.isZero())
3168 return true;
3169 return HandleBaseToDerivedCast(Info, E, Result);
3170
Richard Smith47a1eed2011-10-29 20:57:55 +00003171 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003172 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003173
John McCall2de56d12010-08-25 11:45:40 +00003174 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003175 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3176
Richard Smith1aa0be82012-03-03 22:46:17 +00003177 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003178 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003179 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003180
John McCallefdb83e2010-05-07 21:00:08 +00003181 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003182 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3183 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003184 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003185 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003186 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003187 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003188 return true;
3189 } else {
3190 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003191 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003192 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003193 }
3194 }
John McCall2de56d12010-08-25 11:45:40 +00003195 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003196 if (SubExpr->isGLValue()) {
3197 if (!EvaluateLValue(SubExpr, Result, Info))
3198 return false;
3199 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003200 Result.set(SubExpr, Info.CurrentCall->Index);
3201 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3202 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003203 return false;
3204 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003205 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003206 if (const ConstantArrayType *CAT
3207 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3208 Result.addArray(Info, E, CAT);
3209 else
3210 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003211 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003212
John McCall2de56d12010-08-25 11:45:40 +00003213 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003214 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003215 }
3216
Richard Smithc49bd112011-10-28 17:51:58 +00003217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003218}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003219
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003220bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003221 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003222 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003223
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003224 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003225}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003226
3227//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003228// Member Pointer Evaluation
3229//===----------------------------------------------------------------------===//
3230
3231namespace {
3232class MemberPointerExprEvaluator
3233 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3234 MemberPtr &Result;
3235
3236 bool Success(const ValueDecl *D) {
3237 Result = MemberPtr(D);
3238 return true;
3239 }
3240public:
3241
3242 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3243 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3244
Richard Smith1aa0be82012-03-03 22:46:17 +00003245 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003246 Result.setFrom(V);
3247 return true;
3248 }
Richard Smith51201882011-12-30 21:15:51 +00003249 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003250 return Success((const ValueDecl*)0);
3251 }
3252
3253 bool VisitCastExpr(const CastExpr *E);
3254 bool VisitUnaryAddrOf(const UnaryOperator *E);
3255};
3256} // end anonymous namespace
3257
3258static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3259 EvalInfo &Info) {
3260 assert(E->isRValue() && E->getType()->isMemberPointerType());
3261 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3262}
3263
3264bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3265 switch (E->getCastKind()) {
3266 default:
3267 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3268
3269 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003270 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003271
3272 case CK_BaseToDerivedMemberPointer: {
3273 if (!Visit(E->getSubExpr()))
3274 return false;
3275 if (E->path_empty())
3276 return true;
3277 // Base-to-derived member pointer casts store the path in derived-to-base
3278 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3279 // the wrong end of the derived->base arc, so stagger the path by one class.
3280 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3281 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3282 PathI != PathE; ++PathI) {
3283 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3284 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3285 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003286 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003287 }
3288 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3289 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003290 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 return true;
3292 }
3293
3294 case CK_DerivedToBaseMemberPointer:
3295 if (!Visit(E->getSubExpr()))
3296 return false;
3297 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3298 PathE = E->path_end(); PathI != PathE; ++PathI) {
3299 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3300 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3301 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003302 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003303 }
3304 return true;
3305 }
3306}
3307
3308bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3309 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3310 // member can be formed.
3311 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3312}
3313
3314//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003315// Record Evaluation
3316//===----------------------------------------------------------------------===//
3317
3318namespace {
3319 class RecordExprEvaluator
3320 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3321 const LValue &This;
3322 APValue &Result;
3323 public:
3324
3325 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3326 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3327
Richard Smith1aa0be82012-03-03 22:46:17 +00003328 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003329 Result = V;
3330 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003331 }
Richard Smith51201882011-12-30 21:15:51 +00003332 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003333
Richard Smith59efe262011-11-11 04:05:33 +00003334 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003335 bool VisitInitListExpr(const InitListExpr *E);
3336 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3337 };
3338}
3339
Richard Smith51201882011-12-30 21:15:51 +00003340/// Perform zero-initialization on an object of non-union class type.
3341/// C++11 [dcl.init]p5:
3342/// To zero-initialize an object or reference of type T means:
3343/// [...]
3344/// -- if T is a (possibly cv-qualified) non-union class type,
3345/// each non-static data member and each base-class subobject is
3346/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003347static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3348 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003349 const LValue &This, APValue &Result) {
3350 assert(!RD->isUnion() && "Expected non-union class type");
3351 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3352 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3353 std::distance(RD->field_begin(), RD->field_end()));
3354
3355 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3356
3357 if (CD) {
3358 unsigned Index = 0;
3359 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003360 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003361 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3362 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003363 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3364 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003365 Result.getStructBase(Index)))
3366 return false;
3367 }
3368 }
3369
Richard Smithb4e85ed2012-01-06 16:39:00 +00003370 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3371 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003372 // -- if T is a reference type, no initialization is performed.
3373 if ((*I)->getType()->isReferenceType())
3374 continue;
3375
3376 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003377 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003378
3379 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003380 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003381 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3382 return false;
3383 }
3384
3385 return true;
3386}
3387
3388bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3389 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3390 if (RD->isUnion()) {
3391 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3392 // object's first non-static named data member is zero-initialized
3393 RecordDecl::field_iterator I = RD->field_begin();
3394 if (I == RD->field_end()) {
3395 Result = APValue((const FieldDecl*)0);
3396 return true;
3397 }
3398
3399 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003400 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003401 Result = APValue(*I);
3402 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003403 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003404 }
3405
Richard Smithce582fe2012-02-17 00:44:16 +00003406 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3407 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3408 return false;
3409 }
3410
Richard Smithb4e85ed2012-01-06 16:39:00 +00003411 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003412}
3413
Richard Smith59efe262011-11-11 04:05:33 +00003414bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3415 switch (E->getCastKind()) {
3416 default:
3417 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3418
3419 case CK_ConstructorConversion:
3420 return Visit(E->getSubExpr());
3421
3422 case CK_DerivedToBase:
3423 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003424 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003425 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003426 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003427 if (!DerivedObject.isStruct())
3428 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003429
3430 // Derived-to-base rvalue conversion: just slice off the derived part.
3431 APValue *Value = &DerivedObject;
3432 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3433 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3434 PathE = E->path_end(); PathI != PathE; ++PathI) {
3435 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3436 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3437 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3438 RD = Base;
3439 }
3440 Result = *Value;
3441 return true;
3442 }
3443 }
3444}
3445
Richard Smith180f4792011-11-10 06:34:14 +00003446bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003447 // Cannot constant-evaluate std::initializer_list inits.
3448 if (E->initializesStdInitializerList())
3449 return false;
3450
Richard Smith180f4792011-11-10 06:34:14 +00003451 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3452 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3453
3454 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003455 const FieldDecl *Field = E->getInitializedFieldInUnion();
3456 Result = APValue(Field);
3457 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003458 return true;
Richard Smithec789162012-01-12 18:54:33 +00003459
3460 // If the initializer list for a union does not contain any elements, the
3461 // first element of the union is value-initialized.
3462 ImplicitValueInitExpr VIE(Field->getType());
3463 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3464
Richard Smith180f4792011-11-10 06:34:14 +00003465 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003466 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003467 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003468 }
3469
3470 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3471 "initializer list for class with base classes");
3472 Result = APValue(APValue::UninitStruct(), 0,
3473 std::distance(RD->field_begin(), RD->field_end()));
3474 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003475 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003476 for (RecordDecl::field_iterator Field = RD->field_begin(),
3477 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3478 // Anonymous bit-fields are not considered members of the class for
3479 // purposes of aggregate initialization.
3480 if (Field->isUnnamedBitfield())
3481 continue;
3482
3483 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003484
Richard Smith745f5142012-01-27 01:14:48 +00003485 bool HaveInit = ElementNo < E->getNumInits();
3486
3487 // FIXME: Diagnostics here should point to the end of the initializer
3488 // list, not the start.
3489 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3490 *Field, &Layout);
3491
3492 // Perform an implicit value-initialization for members beyond the end of
3493 // the initializer list.
3494 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3495
Richard Smith83587db2012-02-15 02:18:13 +00003496 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003497 Result.getStructField((*Field)->getFieldIndex()),
3498 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3499 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003500 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003501 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003502 }
3503 }
3504
Richard Smith745f5142012-01-27 01:14:48 +00003505 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003506}
3507
3508bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3509 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003510 bool ZeroInit = E->requiresZeroInitialization();
3511 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003512 // If we've already performed zero-initialization, we're already done.
3513 if (!Result.isUninit())
3514 return true;
3515
Richard Smith51201882011-12-30 21:15:51 +00003516 if (ZeroInit)
3517 return ZeroInitialization(E);
3518
Richard Smith61802452011-12-22 02:22:31 +00003519 const CXXRecordDecl *RD = FD->getParent();
3520 if (RD->isUnion())
3521 Result = APValue((FieldDecl*)0);
3522 else
3523 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3524 std::distance(RD->field_begin(), RD->field_end()));
3525 return true;
3526 }
3527
Richard Smith180f4792011-11-10 06:34:14 +00003528 const FunctionDecl *Definition = 0;
3529 FD->getBody(Definition);
3530
Richard Smithc1c5f272011-12-13 06:39:58 +00003531 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3532 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003533
Richard Smith610a60c2012-01-10 04:32:03 +00003534 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003535 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003536 if (const MaterializeTemporaryExpr *ME
3537 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3538 return Visit(ME->GetTemporaryExpr());
3539
Richard Smith51201882011-12-30 21:15:51 +00003540 if (ZeroInit && !ZeroInitialization(E))
3541 return false;
3542
Richard Smith180f4792011-11-10 06:34:14 +00003543 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003544 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003545 cast<CXXConstructorDecl>(Definition), Info,
3546 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003547}
3548
3549static bool EvaluateRecord(const Expr *E, const LValue &This,
3550 APValue &Result, EvalInfo &Info) {
3551 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003552 "can't evaluate expression as a record rvalue");
3553 return RecordExprEvaluator(Info, This, Result).Visit(E);
3554}
3555
3556//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003557// Temporary Evaluation
3558//
3559// Temporaries are represented in the AST as rvalues, but generally behave like
3560// lvalues. The full-object of which the temporary is a subobject is implicitly
3561// materialized so that a reference can bind to it.
3562//===----------------------------------------------------------------------===//
3563namespace {
3564class TemporaryExprEvaluator
3565 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3566public:
3567 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3568 LValueExprEvaluatorBaseTy(Info, Result) {}
3569
3570 /// Visit an expression which constructs the value of this temporary.
3571 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003572 Result.set(E, Info.CurrentCall->Index);
3573 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003574 }
3575
3576 bool VisitCastExpr(const CastExpr *E) {
3577 switch (E->getCastKind()) {
3578 default:
3579 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3580
3581 case CK_ConstructorConversion:
3582 return VisitConstructExpr(E->getSubExpr());
3583 }
3584 }
3585 bool VisitInitListExpr(const InitListExpr *E) {
3586 return VisitConstructExpr(E);
3587 }
3588 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3589 return VisitConstructExpr(E);
3590 }
3591 bool VisitCallExpr(const CallExpr *E) {
3592 return VisitConstructExpr(E);
3593 }
3594};
3595} // end anonymous namespace
3596
3597/// Evaluate an expression of record type as a temporary.
3598static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003599 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003600 return TemporaryExprEvaluator(Info, Result).Visit(E);
3601}
3602
3603//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003604// Vector Evaluation
3605//===----------------------------------------------------------------------===//
3606
3607namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003608 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003609 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3610 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003611 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003612
Richard Smith07fc6572011-10-22 21:10:00 +00003613 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3614 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003615
Richard Smith07fc6572011-10-22 21:10:00 +00003616 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3617 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3618 // FIXME: remove this APValue copy.
3619 Result = APValue(V.data(), V.size());
3620 return true;
3621 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003622 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003623 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003624 Result = V;
3625 return true;
3626 }
Richard Smith51201882011-12-30 21:15:51 +00003627 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003628
Richard Smith07fc6572011-10-22 21:10:00 +00003629 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003630 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003631 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003632 bool VisitInitListExpr(const InitListExpr *E);
3633 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003634 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003635 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003636 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003637 };
3638} // end anonymous namespace
3639
3640static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003641 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003642 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003643}
3644
Richard Smith07fc6572011-10-22 21:10:00 +00003645bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3646 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003647 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003648
Richard Smithd62ca372011-12-06 22:44:34 +00003649 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003650 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003651
Eli Friedman46a52322011-03-25 00:43:55 +00003652 switch (E->getCastKind()) {
3653 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003654 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003655 if (SETy->isIntegerType()) {
3656 APSInt IntResult;
3657 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003658 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003659 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003660 } else if (SETy->isRealFloatingType()) {
3661 APFloat F(0.0);
3662 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003663 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003664 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003665 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003666 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003667 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003668
3669 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003670 SmallVector<APValue, 4> Elts(NElts, Val);
3671 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003672 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003673 case CK_BitCast: {
3674 // Evaluate the operand into an APInt we can extract from.
3675 llvm::APInt SValInt;
3676 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3677 return false;
3678 // Extract the elements
3679 QualType EltTy = VTy->getElementType();
3680 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3681 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3682 SmallVector<APValue, 4> Elts;
3683 if (EltTy->isRealFloatingType()) {
3684 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3685 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3686 unsigned FloatEltSize = EltSize;
3687 if (&Sem == &APFloat::x87DoubleExtended)
3688 FloatEltSize = 80;
3689 for (unsigned i = 0; i < NElts; i++) {
3690 llvm::APInt Elt;
3691 if (BigEndian)
3692 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3693 else
3694 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3695 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3696 }
3697 } else if (EltTy->isIntegerType()) {
3698 for (unsigned i = 0; i < NElts; i++) {
3699 llvm::APInt Elt;
3700 if (BigEndian)
3701 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3702 else
3703 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3704 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3705 }
3706 } else {
3707 return Error(E);
3708 }
3709 return Success(Elts, E);
3710 }
Eli Friedman46a52322011-03-25 00:43:55 +00003711 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003712 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003713 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003714}
3715
Richard Smith07fc6572011-10-22 21:10:00 +00003716bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003717VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003718 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003719 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003720 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003721
Nate Begeman59b5da62009-01-18 03:20:47 +00003722 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003723 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003724
Eli Friedman3edd5a92012-01-03 23:24:20 +00003725 // The number of initializers can be less than the number of
3726 // vector elements. For OpenCL, this can be due to nested vector
3727 // initialization. For GCC compatibility, missing trailing elements
3728 // should be initialized with zeroes.
3729 unsigned CountInits = 0, CountElts = 0;
3730 while (CountElts < NumElements) {
3731 // Handle nested vector initialization.
3732 if (CountInits < NumInits
3733 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3734 APValue v;
3735 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3736 return Error(E);
3737 unsigned vlen = v.getVectorLength();
3738 for (unsigned j = 0; j < vlen; j++)
3739 Elements.push_back(v.getVectorElt(j));
3740 CountElts += vlen;
3741 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003742 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003743 if (CountInits < NumInits) {
3744 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3745 return Error(E);
3746 } else // trailing integer zero.
3747 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3748 Elements.push_back(APValue(sInt));
3749 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003750 } else {
3751 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003752 if (CountInits < NumInits) {
3753 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3754 return Error(E);
3755 } else // trailing float zero.
3756 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3757 Elements.push_back(APValue(f));
3758 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003759 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003760 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003761 }
Richard Smith07fc6572011-10-22 21:10:00 +00003762 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003763}
3764
Richard Smith07fc6572011-10-22 21:10:00 +00003765bool
Richard Smith51201882011-12-30 21:15:51 +00003766VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003767 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003768 QualType EltTy = VT->getElementType();
3769 APValue ZeroElement;
3770 if (EltTy->isIntegerType())
3771 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3772 else
3773 ZeroElement =
3774 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3775
Chris Lattner5f9e2722011-07-23 10:55:15 +00003776 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003777 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003778}
3779
Richard Smith07fc6572011-10-22 21:10:00 +00003780bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003781 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003782 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003783}
3784
Nate Begeman59b5da62009-01-18 03:20:47 +00003785//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003786// Array Evaluation
3787//===----------------------------------------------------------------------===//
3788
3789namespace {
3790 class ArrayExprEvaluator
3791 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003792 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003793 APValue &Result;
3794 public:
3795
Richard Smith180f4792011-11-10 06:34:14 +00003796 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3797 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003798
3799 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003800 assert((V.isArray() || V.isLValue()) &&
3801 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003802 Result = V;
3803 return true;
3804 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805
Richard Smith51201882011-12-30 21:15:51 +00003806 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003807 const ConstantArrayType *CAT =
3808 Info.Ctx.getAsConstantArrayType(E->getType());
3809 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003810 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003811
3812 Result = APValue(APValue::UninitArray(), 0,
3813 CAT->getSize().getZExtValue());
3814 if (!Result.hasArrayFiller()) return true;
3815
Richard Smith51201882011-12-30 21:15:51 +00003816 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003817 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003818 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003819 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003820 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003821 }
3822
Richard Smithcc5d4f62011-11-07 09:22:26 +00003823 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003824 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003825 };
3826} // end anonymous namespace
3827
Richard Smith180f4792011-11-10 06:34:14 +00003828static bool EvaluateArray(const Expr *E, const LValue &This,
3829 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003830 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003831 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003832}
3833
3834bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3835 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3836 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003837 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003838
Richard Smith974c5f92011-12-22 01:07:19 +00003839 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3840 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003841 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003842 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3843 LValue LV;
3844 if (!EvaluateLValue(E->getInit(0), LV, Info))
3845 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003846 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003847 LV.moveInto(Val);
3848 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003849 }
3850
Richard Smith745f5142012-01-27 01:14:48 +00003851 bool Success = true;
3852
Richard Smithcc5d4f62011-11-07 09:22:26 +00003853 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3854 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003855 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003856 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003857 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003858 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003859 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003860 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3861 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003862 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3863 CAT->getElementType(), 1)) {
3864 if (!Info.keepEvaluatingAfterFailure())
3865 return false;
3866 Success = false;
3867 }
Richard Smith180f4792011-11-10 06:34:14 +00003868 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003869
Richard Smith745f5142012-01-27 01:14:48 +00003870 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003871 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003872 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3873 // but sometimes does:
3874 // struct S { constexpr S() : p(&p) {} void *p; };
3875 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003876 return EvaluateInPlace(Result.getArrayFiller(), Info,
3877 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003878}
3879
Richard Smithe24f5fc2011-11-17 22:56:20 +00003880bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3881 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3882 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003883 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003884
Richard Smithec789162012-01-12 18:54:33 +00003885 bool HadZeroInit = !Result.isUninit();
3886 if (!HadZeroInit)
3887 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003888 if (!Result.hasArrayFiller())
3889 return true;
3890
3891 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003892
Richard Smith51201882011-12-30 21:15:51 +00003893 bool ZeroInit = E->requiresZeroInitialization();
3894 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003895 if (HadZeroInit)
3896 return true;
3897
Richard Smith51201882011-12-30 21:15:51 +00003898 if (ZeroInit) {
3899 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003900 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003901 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003902 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003903 }
3904
Richard Smith61802452011-12-22 02:22:31 +00003905 const CXXRecordDecl *RD = FD->getParent();
3906 if (RD->isUnion())
3907 Result.getArrayFiller() = APValue((FieldDecl*)0);
3908 else
3909 Result.getArrayFiller() =
3910 APValue(APValue::UninitStruct(), RD->getNumBases(),
3911 std::distance(RD->field_begin(), RD->field_end()));
3912 return true;
3913 }
3914
Richard Smithe24f5fc2011-11-17 22:56:20 +00003915 const FunctionDecl *Definition = 0;
3916 FD->getBody(Definition);
3917
Richard Smithc1c5f272011-12-13 06:39:58 +00003918 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3919 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003920
3921 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3922 // but sometimes does:
3923 // struct S { constexpr S() : p(&p) {} void *p; };
3924 // S s[10];
3925 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003926 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003927
Richard Smithec789162012-01-12 18:54:33 +00003928 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003929 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003930 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003931 return false;
3932 }
3933
Richard Smithe24f5fc2011-11-17 22:56:20 +00003934 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003935 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003936 cast<CXXConstructorDecl>(Definition),
3937 Info, Result.getArrayFiller());
3938}
3939
Richard Smithcc5d4f62011-11-07 09:22:26 +00003940//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003941// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003942//
3943// As a GNU extension, we support casting pointers to sufficiently-wide integer
3944// types and back in constant folding. Integer values are thus represented
3945// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003946//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003947
3948namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003949class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003950 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003951 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003952public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003953 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003954 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003955
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003956 bool Success(const llvm::APSInt &SI, const Expr *E) {
3957 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003958 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003959 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003960 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003961 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003962 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003963 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003964 return true;
3965 }
3966
Daniel Dunbar131eb432009-02-19 09:06:44 +00003967 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003968 assert(E->getType()->isIntegralOrEnumerationType() &&
3969 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003970 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003971 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003972 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003973 Result.getInt().setIsUnsigned(
3974 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003975 return true;
3976 }
3977
3978 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003979 assert(E->getType()->isIntegralOrEnumerationType() &&
3980 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003981 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003982 return true;
3983 }
3984
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003985 bool Success(CharUnits Size, const Expr *E) {
3986 return Success(Size.getQuantity(), E);
3987 }
3988
Richard Smith1aa0be82012-03-03 22:46:17 +00003989 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003990 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003991 Result = V;
3992 return true;
3993 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003994 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003995 }
Mike Stump1eb44332009-09-09 15:08:12 +00003996
Richard Smith51201882011-12-30 21:15:51 +00003997 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003998
Argyrios Kyrtzidisc1b66e62012-02-27 23:18:37 +00003999 // FIXME: See EvalInfo::IntExprEvaluatorDepth.
4000 bool Visit(const Expr *E) {
4001 SaveAndRestore<unsigned> Depth(Info.IntExprEvaluatorDepth,
4002 Info.IntExprEvaluatorDepth+1);
4003 const unsigned MaxDepth = 512;
4004 if (Depth.get() > MaxDepth) {
4005 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4006 diag::err_intexpr_depth_limit_exceeded);
4007 return false;
4008 }
4009
4010 return ExprEvaluatorBaseTy::Visit(E);
4011 }
4012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004013 //===--------------------------------------------------------------------===//
4014 // Visitor Methods
4015 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004016
Chris Lattner4c4867e2008-07-12 00:38:25 +00004017 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004018 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004019 }
4020 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004021 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004022 }
Eli Friedman04309752009-11-24 05:28:59 +00004023
4024 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4025 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004026 if (CheckReferencedDecl(E, E->getDecl()))
4027 return true;
4028
4029 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004030 }
4031 bool VisitMemberExpr(const MemberExpr *E) {
4032 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004033 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004034 return true;
4035 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004036
4037 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004038 }
4039
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004040 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004041 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004042 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004043 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004044
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004045 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004046 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004047
Anders Carlsson3068d112008-11-16 19:01:22 +00004048 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004049 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004050 }
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004052 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4053 return Success(E->getValue(), E);
4054 }
4055
Richard Smithf10d9172011-10-11 21:43:33 +00004056 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004057 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004058 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004059 }
4060
Sebastian Redl64b45f72009-01-05 20:52:13 +00004061 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004062 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004063 }
4064
Francois Pichet6ad6f282010-12-07 00:08:36 +00004065 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4066 return Success(E->getValue(), E);
4067 }
4068
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004069 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4070 return Success(E->getValue(), E);
4071 }
4072
John Wiegley21ff2e52011-04-28 00:16:57 +00004073 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4074 return Success(E->getValue(), E);
4075 }
4076
John Wiegley55262202011-04-25 06:54:41 +00004077 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4078 return Success(E->getValue(), E);
4079 }
4080
Eli Friedman722c7172009-02-28 03:59:05 +00004081 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004082 bool VisitUnaryImag(const UnaryOperator *E);
4083
Sebastian Redl295995c2010-09-10 20:55:47 +00004084 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004085 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004086
Chris Lattnerfcee0012008-07-11 21:24:13 +00004087private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004088 CharUnits GetAlignOfExpr(const Expr *E);
4089 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004090 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004091 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004092 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004093};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004094} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004095
Richard Smithc49bd112011-10-28 17:51:58 +00004096/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4097/// produce either the integer value or a pointer.
4098///
4099/// GCC has a heinous extension which folds casts between pointer types and
4100/// pointer-sized integral types. We support this by allowing the evaluation of
4101/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4102/// Some simple arithmetic on such values is supported (they are treated much
4103/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004104static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004105 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004106 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004107 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004108}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004109
Richard Smithf48fdb02011-12-09 22:58:01 +00004110static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004111 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004112 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004113 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004114 if (!Val.isInt()) {
4115 // FIXME: It would be better to produce the diagnostic for casting
4116 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004117 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004118 return false;
4119 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004120 Result = Val.getInt();
4121 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004122}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004123
Richard Smithf48fdb02011-12-09 22:58:01 +00004124/// Check whether the given declaration can be directly converted to an integral
4125/// rvalue. If not, no diagnostic is produced; there are other things we can
4126/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004127bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004128 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004129 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004130 // Check for signedness/width mismatches between E type and ECD value.
4131 bool SameSign = (ECD->getInitVal().isSigned()
4132 == E->getType()->isSignedIntegerOrEnumerationType());
4133 bool SameWidth = (ECD->getInitVal().getBitWidth()
4134 == Info.Ctx.getIntWidth(E->getType()));
4135 if (SameSign && SameWidth)
4136 return Success(ECD->getInitVal(), E);
4137 else {
4138 // Get rid of mismatch (otherwise Success assertions will fail)
4139 // by computing a new value matching the type of E.
4140 llvm::APSInt Val = ECD->getInitVal();
4141 if (!SameSign)
4142 Val.setIsSigned(!ECD->getInitVal().isSigned());
4143 if (!SameWidth)
4144 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4145 return Success(Val, E);
4146 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004147 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004148 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004149}
4150
Chris Lattnera4d55d82008-10-06 06:40:35 +00004151/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4152/// as GCC.
4153static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4154 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004155 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004156 enum gcc_type_class {
4157 no_type_class = -1,
4158 void_type_class, integer_type_class, char_type_class,
4159 enumeral_type_class, boolean_type_class,
4160 pointer_type_class, reference_type_class, offset_type_class,
4161 real_type_class, complex_type_class,
4162 function_type_class, method_type_class,
4163 record_type_class, union_type_class,
4164 array_type_class, string_type_class,
4165 lang_type_class
4166 };
Mike Stump1eb44332009-09-09 15:08:12 +00004167
4168 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004169 // ideal, however it is what gcc does.
4170 if (E->getNumArgs() == 0)
4171 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004172
Chris Lattnera4d55d82008-10-06 06:40:35 +00004173 QualType ArgTy = E->getArg(0)->getType();
4174 if (ArgTy->isVoidType())
4175 return void_type_class;
4176 else if (ArgTy->isEnumeralType())
4177 return enumeral_type_class;
4178 else if (ArgTy->isBooleanType())
4179 return boolean_type_class;
4180 else if (ArgTy->isCharType())
4181 return string_type_class; // gcc doesn't appear to use char_type_class
4182 else if (ArgTy->isIntegerType())
4183 return integer_type_class;
4184 else if (ArgTy->isPointerType())
4185 return pointer_type_class;
4186 else if (ArgTy->isReferenceType())
4187 return reference_type_class;
4188 else if (ArgTy->isRealType())
4189 return real_type_class;
4190 else if (ArgTy->isComplexType())
4191 return complex_type_class;
4192 else if (ArgTy->isFunctionType())
4193 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004194 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004195 return record_type_class;
4196 else if (ArgTy->isUnionType())
4197 return union_type_class;
4198 else if (ArgTy->isArrayType())
4199 return array_type_class;
4200 else if (ArgTy->isUnionType())
4201 return union_type_class;
4202 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004203 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004204}
4205
Richard Smith80d4b552011-12-28 19:48:30 +00004206/// EvaluateBuiltinConstantPForLValue - Determine the result of
4207/// __builtin_constant_p when applied to the given lvalue.
4208///
4209/// An lvalue is only "constant" if it is a pointer or reference to the first
4210/// character of a string literal.
4211template<typename LValue>
4212static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4213 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4214 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4215}
4216
4217/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4218/// GCC as we can manage.
4219static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4220 QualType ArgType = Arg->getType();
4221
4222 // __builtin_constant_p always has one operand. The rules which gcc follows
4223 // are not precisely documented, but are as follows:
4224 //
4225 // - If the operand is of integral, floating, complex or enumeration type,
4226 // and can be folded to a known value of that type, it returns 1.
4227 // - If the operand and can be folded to a pointer to the first character
4228 // of a string literal (or such a pointer cast to an integral type), it
4229 // returns 1.
4230 //
4231 // Otherwise, it returns 0.
4232 //
4233 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4234 // its support for this does not currently work.
4235 if (ArgType->isIntegralOrEnumerationType()) {
4236 Expr::EvalResult Result;
4237 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4238 return false;
4239
4240 APValue &V = Result.Val;
4241 if (V.getKind() == APValue::Int)
4242 return true;
4243
4244 return EvaluateBuiltinConstantPForLValue(V);
4245 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4246 return Arg->isEvaluatable(Ctx);
4247 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4248 LValue LV;
4249 Expr::EvalStatus Status;
4250 EvalInfo Info(Ctx, Status);
4251 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4252 : EvaluatePointer(Arg, LV, Info)) &&
4253 !Status.HasSideEffects)
4254 return EvaluateBuiltinConstantPForLValue(LV);
4255 }
4256
4257 // Anything else isn't considered to be sufficiently constant.
4258 return false;
4259}
4260
John McCall42c8f872010-05-10 23:27:23 +00004261/// Retrieves the "underlying object type" of the given expression,
4262/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004263QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4264 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4265 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004266 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004267 } else if (const Expr *E = B.get<const Expr*>()) {
4268 if (isa<CompoundLiteralExpr>(E))
4269 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004270 }
4271
4272 return QualType();
4273}
4274
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004275bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004276 // TODO: Perhaps we should let LLVM lower this?
4277 LValue Base;
4278 if (!EvaluatePointer(E->getArg(0), Base, Info))
4279 return false;
4280
4281 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004282 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004283
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004284 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004285 if (T.isNull() ||
4286 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004287 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004288 T->isVariablyModifiedType() ||
4289 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004291
4292 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4293 CharUnits Offset = Base.getLValueOffset();
4294
4295 if (!Offset.isNegative() && Offset <= Size)
4296 Size -= Offset;
4297 else
4298 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004299 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004300}
4301
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004302bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004303 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004304 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004305 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004306
4307 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004308 if (TryEvaluateBuiltinObjectSize(E))
4309 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004310
Eric Christopherb2aaf512010-01-19 22:58:35 +00004311 // If evaluating the argument has side-effects we can't determine
4312 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004313 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004314 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004315 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004316 return Success(0, E);
4317 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004318
Richard Smithf48fdb02011-12-09 22:58:01 +00004319 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004320 }
4321
Chris Lattner019f4e82008-10-06 05:28:25 +00004322 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004323 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Richard Smith80d4b552011-12-28 19:48:30 +00004325 case Builtin::BI__builtin_constant_p:
4326 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004327
Chris Lattner21fb98e2009-09-23 06:06:36 +00004328 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004329 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004330 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004331 return Success(Operand, E);
4332 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004333
4334 case Builtin::BI__builtin_expect:
4335 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004336
Douglas Gregor5726d402010-09-10 06:27:15 +00004337 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004338 // A call to strlen is not a constant expression.
4339 if (Info.getLangOpts().CPlusPlus0x)
4340 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4341 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4342 else
4343 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4344 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004345 case Builtin::BI__builtin_strlen:
4346 // As an extension, we support strlen() and __builtin_strlen() as constant
4347 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004348 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004349 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4350 // The string literal may have embedded null characters. Find the first
4351 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004352 StringRef Str = S->getString();
4353 StringRef::size_type Pos = Str.find(0);
4354 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004355 Str = Str.substr(0, Pos);
4356
4357 return Success(Str.size(), E);
4358 }
4359
Richard Smithf48fdb02011-12-09 22:58:01 +00004360 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004361
4362 case Builtin::BI__atomic_is_lock_free: {
4363 APSInt SizeVal;
4364 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4365 return false;
4366
4367 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4368 // of two less than the maximum inline atomic width, we know it is
4369 // lock-free. If the size isn't a power of two, or greater than the
4370 // maximum alignment where we promote atomics, we know it is not lock-free
4371 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4372 // the answer can only be determined at runtime; for example, 16-byte
4373 // atomics have lock-free implementations on some, but not all,
4374 // x86-64 processors.
4375
4376 // Check power-of-two.
4377 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4378 if (!Size.isPowerOfTwo())
4379#if 0
4380 // FIXME: Suppress this folding until the ABI for the promotion width
4381 // settles.
4382 return Success(0, E);
4383#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004384 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004385#endif
4386
4387#if 0
4388 // Check against promotion width.
4389 // FIXME: Suppress this folding until the ABI for the promotion width
4390 // settles.
4391 unsigned PromoteWidthBits =
4392 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4393 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4394 return Success(0, E);
4395#endif
4396
4397 // Check against inlining width.
4398 unsigned InlineWidthBits =
4399 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4400 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4401 return Success(1, E);
4402
Richard Smithf48fdb02011-12-09 22:58:01 +00004403 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004404 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004405 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004406}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004407
Richard Smith625b8072011-10-31 01:37:14 +00004408static bool HasSameBase(const LValue &A, const LValue &B) {
4409 if (!A.getLValueBase())
4410 return !B.getLValueBase();
4411 if (!B.getLValueBase())
4412 return false;
4413
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004414 if (A.getLValueBase().getOpaqueValue() !=
4415 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004416 const Decl *ADecl = GetLValueBaseDecl(A);
4417 if (!ADecl)
4418 return false;
4419 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004420 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004421 return false;
4422 }
4423
4424 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004425 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004426}
4427
Richard Smith7b48a292012-02-01 05:53:12 +00004428/// Perform the given integer operation, which is known to need at most BitWidth
4429/// bits, and check for overflow in the original type (if that type was not an
4430/// unsigned type).
4431template<typename Operation>
4432static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4433 const APSInt &LHS, const APSInt &RHS,
4434 unsigned BitWidth, Operation Op) {
4435 if (LHS.isUnsigned())
4436 return Op(LHS, RHS);
4437
4438 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4439 APSInt Result = Value.trunc(LHS.getBitWidth());
4440 if (Result.extend(BitWidth) != Value)
4441 HandleOverflow(Info, E, Value, E->getType());
4442 return Result;
4443}
4444
Chris Lattnerb542afe2008-07-11 19:10:17 +00004445bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004446 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004447 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004448
John McCall2de56d12010-08-25 11:45:40 +00004449 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004450 VisitIgnoredValue(E->getLHS());
4451 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004452 }
4453
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004454 if (E->isLogicalOp()) {
4455 // These need to be handled specially because the operands aren't
4456 // necessarily integral nor evaluated.
4457 bool lhsResult, rhsResult;
4458
4459 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4460 // We were able to evaluate the LHS, see if we can get away with not
4461 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4462 if (lhsResult == (E->getOpcode() == BO_LOr))
4463 return Success(lhsResult, E);
4464
4465 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4466 if (E->getOpcode() == BO_LOr)
4467 return Success(lhsResult || rhsResult, E);
4468 else
4469 return Success(lhsResult && rhsResult, E);
4470 }
4471 } else {
4472 // Since we weren't able to evaluate the left hand side, it
4473 // must have had side effects.
4474 Info.EvalStatus.HasSideEffects = true;
4475
4476 // Suppress diagnostics from this arm.
4477 SpeculativeEvaluationRAII Speculative(Info);
4478 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4479 // We can't evaluate the LHS; however, sometimes the result
4480 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4481 if (rhsResult == (E->getOpcode() == BO_LOr))
4482 return Success(rhsResult, E);
4483 }
4484 }
4485
4486 return false;
4487 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004488
Anders Carlsson286f85e2008-11-16 07:17:21 +00004489 QualType LHSTy = E->getLHS()->getType();
4490 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004491
4492 if (LHSTy->isAnyComplexType()) {
4493 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004494 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004495
Richard Smith745f5142012-01-27 01:14:48 +00004496 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4497 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004498 return false;
4499
Richard Smith745f5142012-01-27 01:14:48 +00004500 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004501 return false;
4502
4503 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004504 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004505 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004506 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004507 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4508
John McCall2de56d12010-08-25 11:45:40 +00004509 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004510 return Success((CR_r == APFloat::cmpEqual &&
4511 CR_i == APFloat::cmpEqual), E);
4512 else {
John McCall2de56d12010-08-25 11:45:40 +00004513 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004514 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004515 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004516 CR_r == APFloat::cmpLessThan ||
4517 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004518 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004519 CR_i == APFloat::cmpLessThan ||
4520 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004521 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004522 } else {
John McCall2de56d12010-08-25 11:45:40 +00004523 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004524 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4525 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4526 else {
John McCall2de56d12010-08-25 11:45:40 +00004527 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004528 "Invalid compex comparison.");
4529 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4530 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4531 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004532 }
4533 }
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Anders Carlsson286f85e2008-11-16 07:17:21 +00004535 if (LHSTy->isRealFloatingType() &&
4536 RHSTy->isRealFloatingType()) {
4537 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004538
Richard Smith745f5142012-01-27 01:14:48 +00004539 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4540 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004541 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004542
Richard Smith745f5142012-01-27 01:14:48 +00004543 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004544 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004545
Anders Carlsson286f85e2008-11-16 07:17:21 +00004546 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004547
Anders Carlsson286f85e2008-11-16 07:17:21 +00004548 switch (E->getOpcode()) {
4549 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004550 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004551 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004552 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004553 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004554 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004555 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004556 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004557 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004558 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004559 E);
John McCall2de56d12010-08-25 11:45:40 +00004560 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004561 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004562 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004563 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004564 || CR == APFloat::cmpLessThan
4565 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004566 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004567 }
Mike Stump1eb44332009-09-09 15:08:12 +00004568
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004569 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004570 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004571 LValue LHSValue, RHSValue;
4572
4573 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4574 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004575 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004576
Richard Smith745f5142012-01-27 01:14:48 +00004577 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004578 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004579
Richard Smith625b8072011-10-31 01:37:14 +00004580 // Reject differing bases from the normal codepath; we special-case
4581 // comparisons to null.
4582 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004583 if (E->getOpcode() == BO_Sub) {
4584 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004585 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4586 return false;
4587 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4588 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4589 if (!LHSExpr || !RHSExpr)
4590 return false;
4591 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4592 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4593 if (!LHSAddrExpr || !RHSAddrExpr)
4594 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004595 // Make sure both labels come from the same function.
4596 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4597 RHSAddrExpr->getLabel()->getDeclContext())
4598 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004599 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004600 return true;
4601 }
Richard Smith9e36b532011-10-31 05:11:32 +00004602 // Inequalities and subtractions between unrelated pointers have
4603 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004604 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004605 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004606 // A constant address may compare equal to the address of a symbol.
4607 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004608 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004609 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4610 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004611 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004612 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004613 // distinct addresses. In clang, the result of such a comparison is
4614 // unspecified, so it is not a constant expression. However, we do know
4615 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004616 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4617 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004618 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004619 // We can't tell whether weak symbols will end up pointing to the same
4620 // object.
4621 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004622 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004623 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004624 // (Note that clang defaults to -fmerge-all-constants, which can
4625 // lead to inconsistent results for comparisons involving the address
4626 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004627 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004628 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004629
Richard Smith15efc4d2012-02-01 08:10:20 +00004630 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4631 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4632
Richard Smithf15fda02012-02-02 01:16:57 +00004633 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4634 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4635
John McCall2de56d12010-08-25 11:45:40 +00004636 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004637 // C++11 [expr.add]p6:
4638 // Unless both pointers point to elements of the same array object, or
4639 // one past the last element of the array object, the behavior is
4640 // undefined.
4641 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4642 !AreElementsOfSameArray(getType(LHSValue.Base),
4643 LHSDesignator, RHSDesignator))
4644 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4645
Chris Lattner4992bdd2010-04-20 17:13:14 +00004646 QualType Type = E->getLHS()->getType();
4647 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004648
Richard Smith180f4792011-11-10 06:34:14 +00004649 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004650 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004651 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004652
Richard Smith15efc4d2012-02-01 08:10:20 +00004653 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4654 // and produce incorrect results when it overflows. Such behavior
4655 // appears to be non-conforming, but is common, so perhaps we should
4656 // assume the standard intended for such cases to be undefined behavior
4657 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004658
Richard Smith15efc4d2012-02-01 08:10:20 +00004659 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4660 // overflow in the final conversion to ptrdiff_t.
4661 APSInt LHS(
4662 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4663 APSInt RHS(
4664 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4665 APSInt ElemSize(
4666 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4667 APSInt TrueResult = (LHS - RHS) / ElemSize;
4668 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4669
4670 if (Result.extend(65) != TrueResult)
4671 HandleOverflow(Info, E, TrueResult, E->getType());
4672 return Success(Result, E);
4673 }
Richard Smith82f28582012-01-31 06:41:30 +00004674
4675 // C++11 [expr.rel]p3:
4676 // Pointers to void (after pointer conversions) can be compared, with a
4677 // result defined as follows: If both pointers represent the same
4678 // address or are both the null pointer value, the result is true if the
4679 // operator is <= or >= and false otherwise; otherwise the result is
4680 // unspecified.
4681 // We interpret this as applying to pointers to *cv* void.
4682 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004683 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004684 CCEDiag(E, diag::note_constexpr_void_comparison);
4685
Richard Smithf15fda02012-02-02 01:16:57 +00004686 // C++11 [expr.rel]p2:
4687 // - If two pointers point to non-static data members of the same object,
4688 // or to subobjects or array elements fo such members, recursively, the
4689 // pointer to the later declared member compares greater provided the
4690 // two members have the same access control and provided their class is
4691 // not a union.
4692 // [...]
4693 // - Otherwise pointer comparisons are unspecified.
4694 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4695 E->isRelationalOp()) {
4696 bool WasArrayIndex;
4697 unsigned Mismatch =
4698 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4699 RHSDesignator, WasArrayIndex);
4700 // At the point where the designators diverge, the comparison has a
4701 // specified value if:
4702 // - we are comparing array indices
4703 // - we are comparing fields of a union, or fields with the same access
4704 // Otherwise, the result is unspecified and thus the comparison is not a
4705 // constant expression.
4706 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4707 Mismatch < RHSDesignator.Entries.size()) {
4708 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4709 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4710 if (!LF && !RF)
4711 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4712 else if (!LF)
4713 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4714 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4715 << RF->getParent() << RF;
4716 else if (!RF)
4717 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4718 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4719 << LF->getParent() << LF;
4720 else if (!LF->getParent()->isUnion() &&
4721 LF->getAccess() != RF->getAccess())
4722 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4723 << LF << LF->getAccess() << RF << RF->getAccess()
4724 << LF->getParent();
4725 }
4726 }
4727
Richard Smith625b8072011-10-31 01:37:14 +00004728 switch (E->getOpcode()) {
4729 default: llvm_unreachable("missing comparison operator");
4730 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4731 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4732 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4733 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4734 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4735 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004736 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004737 }
4738 }
Richard Smithb02e4622012-02-01 01:42:44 +00004739
4740 if (LHSTy->isMemberPointerType()) {
4741 assert(E->isEqualityOp() && "unexpected member pointer operation");
4742 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4743
4744 MemberPtr LHSValue, RHSValue;
4745
4746 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4747 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4748 return false;
4749
4750 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4751 return false;
4752
4753 // C++11 [expr.eq]p2:
4754 // If both operands are null, they compare equal. Otherwise if only one is
4755 // null, they compare unequal.
4756 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4757 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4758 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4759 }
4760
4761 // Otherwise if either is a pointer to a virtual member function, the
4762 // result is unspecified.
4763 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4764 if (MD->isVirtual())
4765 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4766 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4767 if (MD->isVirtual())
4768 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4769
4770 // Otherwise they compare equal if and only if they would refer to the
4771 // same member of the same most derived object or the same subobject if
4772 // they were dereferenced with a hypothetical object of the associated
4773 // class type.
4774 bool Equal = LHSValue == RHSValue;
4775 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4776 }
4777
Richard Smith26f2cac2012-02-14 22:35:28 +00004778 if (LHSTy->isNullPtrType()) {
4779 assert(E->isComparisonOp() && "unexpected nullptr operation");
4780 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4781 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4782 // are compared, the result is true of the operator is <=, >= or ==, and
4783 // false otherwise.
4784 BinaryOperator::Opcode Opcode = E->getOpcode();
4785 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4786 }
4787
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004788 if (!LHSTy->isIntegralOrEnumerationType() ||
4789 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004790 // We can't continue from here for non-integral types.
4791 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004792 }
4793
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004794 // The LHS of a constant expr is always evaluated and needed.
Richard Smith1aa0be82012-03-03 22:46:17 +00004795 APValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004796
4797 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4798 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004799 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004800
Richard Smith745f5142012-01-27 01:14:48 +00004801 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004802 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004803
Richard Smith1aa0be82012-03-03 22:46:17 +00004804 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004805
4806 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004807 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004808 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4809 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004810 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004811 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004812 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004813 LHSVal.getLValueOffset() -= AdditionalOffset;
4814 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004815 return true;
4816 }
4817
4818 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004819 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004820 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004821 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4822 LHSVal.getInt().getZExtValue());
4823 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004824 return true;
4825 }
4826
Eli Friedman65639282012-01-04 23:13:47 +00004827 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4828 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004829 if (!LHSVal.getLValueOffset().isZero() ||
4830 !RHSVal.getLValueOffset().isZero())
4831 return false;
4832 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4833 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4834 if (!LHSExpr || !RHSExpr)
4835 return false;
4836 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4837 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4838 if (!LHSAddrExpr || !RHSAddrExpr)
4839 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004840 // Make sure both labels come from the same function.
4841 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4842 RHSAddrExpr->getLabel()->getDeclContext())
4843 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004844 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004845 return true;
4846 }
4847
Eli Friedman42edd0d2009-03-24 01:14:50 +00004848 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004849 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004850 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004851
Richard Smithc49bd112011-10-28 17:51:58 +00004852 APSInt &LHS = LHSVal.getInt();
4853 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004854
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004855 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004856 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004857 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004858 case BO_Mul:
4859 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4860 LHS.getBitWidth() * 2,
4861 std::multiplies<APSInt>()), E);
4862 case BO_Add:
4863 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4864 LHS.getBitWidth() + 1,
4865 std::plus<APSInt>()), E);
4866 case BO_Sub:
4867 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4868 LHS.getBitWidth() + 1,
4869 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004870 case BO_And: return Success(LHS & RHS, E);
4871 case BO_Xor: return Success(LHS ^ RHS, E);
4872 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004873 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004875 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004876 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004877 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4878 // actually undefined behavior in C++11 due to a language defect.
4879 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4880 LHS.isSigned() && LHS.isMinSignedValue())
4881 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4882 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004883 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004884 // During constant-folding, a negative shift is an opposite shift. Such a
4885 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004886 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004887 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004888 RHS = -RHS;
4889 goto shift_right;
4890 }
4891
4892 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004893 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4894 // shifted type.
4895 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4896 if (SA != RHS) {
4897 CCEDiag(E, diag::note_constexpr_large_shift)
4898 << RHS << E->getType() << LHS.getBitWidth();
4899 } else if (LHS.isSigned()) {
4900 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004901 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004902 if (LHS.isNegative())
4903 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004904 else if (LHS.countLeadingZeros() < SA)
4905 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004906 }
4907
Richard Smithc49bd112011-10-28 17:51:58 +00004908 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004909 }
John McCall2de56d12010-08-25 11:45:40 +00004910 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004911 // During constant-folding, a negative shift is an opposite shift. Such a
4912 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004913 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004914 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004915 RHS = -RHS;
4916 goto shift_left;
4917 }
4918
4919 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004920 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4921 // shifted type.
4922 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4923 if (SA != RHS)
4924 CCEDiag(E, diag::note_constexpr_large_shift)
4925 << RHS << E->getType() << LHS.getBitWidth();
4926
Richard Smithc49bd112011-10-28 17:51:58 +00004927 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004928 }
Mike Stump1eb44332009-09-09 15:08:12 +00004929
Richard Smithc49bd112011-10-28 17:51:58 +00004930 case BO_LT: return Success(LHS < RHS, E);
4931 case BO_GT: return Success(LHS > RHS, E);
4932 case BO_LE: return Success(LHS <= RHS, E);
4933 case BO_GE: return Success(LHS >= RHS, E);
4934 case BO_EQ: return Success(LHS == RHS, E);
4935 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004936 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004937}
4938
Ken Dyck8b752f12010-01-27 17:10:57 +00004939CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004940 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4941 // result shall be the alignment of the referenced type."
4942 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4943 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004944
4945 // __alignof is defined to return the preferred alignment.
4946 return Info.Ctx.toCharUnitsFromBits(
4947 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004948}
4949
Ken Dyck8b752f12010-01-27 17:10:57 +00004950CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004951 E = E->IgnoreParens();
4952
4953 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004954 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004955 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004956 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4957 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004958
Chris Lattneraf707ab2009-01-24 21:53:27 +00004959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004960 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4961 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004962
Chris Lattnere9feb472009-01-24 21:09:06 +00004963 return GetAlignOfType(E->getType());
4964}
4965
4966
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004967/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4968/// a result as the expression's type.
4969bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4970 const UnaryExprOrTypeTraitExpr *E) {
4971 switch(E->getKind()) {
4972 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004973 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004974 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004975 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004976 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004977 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004978
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004979 case UETT_VecStep: {
4980 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004981
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004982 if (Ty->isVectorType()) {
4983 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004984
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004985 // The vec_step built-in functions that take a 3-component
4986 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4987 if (n == 3)
4988 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004989
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004990 return Success(n, E);
4991 } else
4992 return Success(1, E);
4993 }
4994
4995 case UETT_SizeOf: {
4996 QualType SrcTy = E->getTypeOfArgument();
4997 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4998 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004999 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5000 SrcTy = Ref->getPointeeType();
5001
Richard Smith180f4792011-11-10 06:34:14 +00005002 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005003 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005004 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005005 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005006 }
5007 }
5008
5009 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005010}
5011
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005012bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005013 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005014 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005015 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005016 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005017 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005018 for (unsigned i = 0; i != n; ++i) {
5019 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5020 switch (ON.getKind()) {
5021 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005022 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005023 APSInt IdxResult;
5024 if (!EvaluateInteger(Idx, IdxResult, Info))
5025 return false;
5026 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5027 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005028 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005029 CurrentType = AT->getElementType();
5030 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5031 Result += IdxResult.getSExtValue() * ElementSize;
5032 break;
5033 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005034
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005035 case OffsetOfExpr::OffsetOfNode::Field: {
5036 FieldDecl *MemberDecl = ON.getField();
5037 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005038 if (!RT)
5039 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005040 RecordDecl *RD = RT->getDecl();
5041 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005042 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005043 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005044 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005045 CurrentType = MemberDecl->getType().getNonReferenceType();
5046 break;
5047 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005048
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005049 case OffsetOfExpr::OffsetOfNode::Identifier:
5050 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005051
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005052 case OffsetOfExpr::OffsetOfNode::Base: {
5053 CXXBaseSpecifier *BaseSpec = ON.getBase();
5054 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005055 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005056
5057 // Find the layout of the class whose base we are looking into.
5058 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005059 if (!RT)
5060 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005061 RecordDecl *RD = RT->getDecl();
5062 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5063
5064 // Find the base class itself.
5065 CurrentType = BaseSpec->getType();
5066 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5067 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005068 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005069
5070 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005071 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005072 break;
5073 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005074 }
5075 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005076 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005077}
5078
Chris Lattnerb542afe2008-07-11 19:10:17 +00005079bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005080 switch (E->getOpcode()) {
5081 default:
5082 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5083 // See C99 6.6p3.
5084 return Error(E);
5085 case UO_Extension:
5086 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5087 // If so, we could clear the diagnostic ID.
5088 return Visit(E->getSubExpr());
5089 case UO_Plus:
5090 // The result is just the value.
5091 return Visit(E->getSubExpr());
5092 case UO_Minus: {
5093 if (!Visit(E->getSubExpr()))
5094 return false;
5095 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005096 const APSInt &Value = Result.getInt();
5097 if (Value.isSigned() && Value.isMinSignedValue())
5098 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5099 E->getType());
5100 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005101 }
5102 case UO_Not: {
5103 if (!Visit(E->getSubExpr()))
5104 return false;
5105 if (!Result.isInt()) return Error(E);
5106 return Success(~Result.getInt(), E);
5107 }
5108 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005109 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005110 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005111 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005112 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005113 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005114 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005115}
Mike Stump1eb44332009-09-09 15:08:12 +00005116
Chris Lattner732b2232008-07-12 01:15:53 +00005117/// HandleCast - This is used to evaluate implicit or explicit casts where the
5118/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005119bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5120 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005121 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005122 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005123
Eli Friedman46a52322011-03-25 00:43:55 +00005124 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005125 case CK_BaseToDerived:
5126 case CK_DerivedToBase:
5127 case CK_UncheckedDerivedToBase:
5128 case CK_Dynamic:
5129 case CK_ToUnion:
5130 case CK_ArrayToPointerDecay:
5131 case CK_FunctionToPointerDecay:
5132 case CK_NullToPointer:
5133 case CK_NullToMemberPointer:
5134 case CK_BaseToDerivedMemberPointer:
5135 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005136 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005137 case CK_ConstructorConversion:
5138 case CK_IntegralToPointer:
5139 case CK_ToVoid:
5140 case CK_VectorSplat:
5141 case CK_IntegralToFloating:
5142 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005143 case CK_CPointerToObjCPointerCast:
5144 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005145 case CK_AnyPointerToBlockPointerCast:
5146 case CK_ObjCObjectLValueCast:
5147 case CK_FloatingRealToComplex:
5148 case CK_FloatingComplexToReal:
5149 case CK_FloatingComplexCast:
5150 case CK_FloatingComplexToIntegralComplex:
5151 case CK_IntegralRealToComplex:
5152 case CK_IntegralComplexCast:
5153 case CK_IntegralComplexToFloatingComplex:
5154 llvm_unreachable("invalid cast kind for integral value");
5155
Eli Friedmane50c2972011-03-25 19:07:11 +00005156 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005157 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005158 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005159 case CK_ARCProduceObject:
5160 case CK_ARCConsumeObject:
5161 case CK_ARCReclaimReturnedObject:
5162 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005163 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005164 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005165
Richard Smith7d580a42012-01-17 21:17:26 +00005166 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005167 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005168 case CK_AtomicToNonAtomic:
5169 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005170 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005171 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005172
5173 case CK_MemberPointerToBoolean:
5174 case CK_PointerToBoolean:
5175 case CK_IntegralToBoolean:
5176 case CK_FloatingToBoolean:
5177 case CK_FloatingComplexToBoolean:
5178 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005179 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005180 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005181 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005182 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005183 }
5184
Eli Friedman46a52322011-03-25 00:43:55 +00005185 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005186 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005187 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005188
Eli Friedmanbe265702009-02-20 01:15:07 +00005189 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005190 // Allow casts of address-of-label differences if they are no-ops
5191 // or narrowing. (The narrowing case isn't actually guaranteed to
5192 // be constant-evaluatable except in some narrow cases which are hard
5193 // to detect here. We let it through on the assumption the user knows
5194 // what they are doing.)
5195 if (Result.isAddrLabelDiff())
5196 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005197 // Only allow casts of lvalues if they are lossless.
5198 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5199 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005200
Richard Smithf72fccf2012-01-30 22:27:01 +00005201 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5202 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005203 }
Mike Stump1eb44332009-09-09 15:08:12 +00005204
Eli Friedman46a52322011-03-25 00:43:55 +00005205 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005206 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5207
John McCallefdb83e2010-05-07 21:00:08 +00005208 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005209 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005210 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005211
Daniel Dunbardd211642009-02-19 22:24:01 +00005212 if (LV.getLValueBase()) {
5213 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005214 // FIXME: Allow a larger integer size than the pointer size, and allow
5215 // narrowing back down to pointer width in subsequent integral casts.
5216 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005217 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005218 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005219
Richard Smithb755a9d2011-11-16 07:18:12 +00005220 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005221 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005222 return true;
5223 }
5224
Ken Dycka7305832010-01-15 12:37:54 +00005225 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5226 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005227 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005228 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005229
Eli Friedman46a52322011-03-25 00:43:55 +00005230 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005231 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005232 if (!EvaluateComplex(SubExpr, C, Info))
5233 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005234 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005235 }
Eli Friedman2217c872009-02-22 11:46:18 +00005236
Eli Friedman46a52322011-03-25 00:43:55 +00005237 case CK_FloatingToIntegral: {
5238 APFloat F(0.0);
5239 if (!EvaluateFloat(SubExpr, F, Info))
5240 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005241
Richard Smithc1c5f272011-12-13 06:39:58 +00005242 APSInt Value;
5243 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5244 return false;
5245 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005246 }
5247 }
Mike Stump1eb44332009-09-09 15:08:12 +00005248
Eli Friedman46a52322011-03-25 00:43:55 +00005249 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005250}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005251
Eli Friedman722c7172009-02-28 03:59:05 +00005252bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5253 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005254 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005255 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5256 return false;
5257 if (!LV.isComplexInt())
5258 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005259 return Success(LV.getComplexIntReal(), E);
5260 }
5261
5262 return Visit(E->getSubExpr());
5263}
5264
Eli Friedman664a1042009-02-27 04:45:43 +00005265bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005266 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005267 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005268 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5269 return false;
5270 if (!LV.isComplexInt())
5271 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005272 return Success(LV.getComplexIntImag(), E);
5273 }
5274
Richard Smith8327fad2011-10-24 18:44:57 +00005275 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005276 return Success(0, E);
5277}
5278
Douglas Gregoree8aff02011-01-04 17:33:58 +00005279bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5280 return Success(E->getPackLength(), E);
5281}
5282
Sebastian Redl295995c2010-09-10 20:55:47 +00005283bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5284 return Success(E->getValue(), E);
5285}
5286
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005287//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005288// Float Evaluation
5289//===----------------------------------------------------------------------===//
5290
5291namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005292class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005293 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005294 APFloat &Result;
5295public:
5296 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005297 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005298
Richard Smith1aa0be82012-03-03 22:46:17 +00005299 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005300 Result = V.getFloat();
5301 return true;
5302 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005303
Richard Smith51201882011-12-30 21:15:51 +00005304 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005305 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5306 return true;
5307 }
5308
Chris Lattner019f4e82008-10-06 05:28:25 +00005309 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005310
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005311 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005312 bool VisitBinaryOperator(const BinaryOperator *E);
5313 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005314 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005315
John McCallabd3a852010-05-07 22:08:54 +00005316 bool VisitUnaryReal(const UnaryOperator *E);
5317 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005318
Richard Smith51201882011-12-30 21:15:51 +00005319 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005320};
5321} // end anonymous namespace
5322
5323static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005324 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005325 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005326}
5327
Jay Foad4ba2a172011-01-12 09:06:06 +00005328static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005329 QualType ResultTy,
5330 const Expr *Arg,
5331 bool SNaN,
5332 llvm::APFloat &Result) {
5333 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5334 if (!S) return false;
5335
5336 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5337
5338 llvm::APInt fill;
5339
5340 // Treat empty strings as if they were zero.
5341 if (S->getString().empty())
5342 fill = llvm::APInt(32, 0);
5343 else if (S->getString().getAsInteger(0, fill))
5344 return false;
5345
5346 if (SNaN)
5347 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5348 else
5349 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5350 return true;
5351}
5352
Chris Lattner019f4e82008-10-06 05:28:25 +00005353bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005354 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005355 default:
5356 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5357
Chris Lattner019f4e82008-10-06 05:28:25 +00005358 case Builtin::BI__builtin_huge_val:
5359 case Builtin::BI__builtin_huge_valf:
5360 case Builtin::BI__builtin_huge_vall:
5361 case Builtin::BI__builtin_inf:
5362 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005363 case Builtin::BI__builtin_infl: {
5364 const llvm::fltSemantics &Sem =
5365 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005366 Result = llvm::APFloat::getInf(Sem);
5367 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005368 }
Mike Stump1eb44332009-09-09 15:08:12 +00005369
John McCalldb7b72a2010-02-28 13:00:19 +00005370 case Builtin::BI__builtin_nans:
5371 case Builtin::BI__builtin_nansf:
5372 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005373 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5374 true, Result))
5375 return Error(E);
5376 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005377
Chris Lattner9e621712008-10-06 06:31:58 +00005378 case Builtin::BI__builtin_nan:
5379 case Builtin::BI__builtin_nanf:
5380 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005381 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005382 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005383 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5384 false, Result))
5385 return Error(E);
5386 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005387
5388 case Builtin::BI__builtin_fabs:
5389 case Builtin::BI__builtin_fabsf:
5390 case Builtin::BI__builtin_fabsl:
5391 if (!EvaluateFloat(E->getArg(0), Result, Info))
5392 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005393
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005394 if (Result.isNegative())
5395 Result.changeSign();
5396 return true;
5397
Mike Stump1eb44332009-09-09 15:08:12 +00005398 case Builtin::BI__builtin_copysign:
5399 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005400 case Builtin::BI__builtin_copysignl: {
5401 APFloat RHS(0.);
5402 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5403 !EvaluateFloat(E->getArg(1), RHS, Info))
5404 return false;
5405 Result.copySign(RHS);
5406 return true;
5407 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005408 }
5409}
5410
John McCallabd3a852010-05-07 22:08:54 +00005411bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005412 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5413 ComplexValue CV;
5414 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5415 return false;
5416 Result = CV.FloatReal;
5417 return true;
5418 }
5419
5420 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005421}
5422
5423bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005424 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5425 ComplexValue CV;
5426 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5427 return false;
5428 Result = CV.FloatImag;
5429 return true;
5430 }
5431
Richard Smith8327fad2011-10-24 18:44:57 +00005432 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005433 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5434 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005435 return true;
5436}
5437
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005438bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005439 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005440 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005441 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005442 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005443 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005444 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5445 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005446 Result.changeSign();
5447 return true;
5448 }
5449}
Chris Lattner019f4e82008-10-06 05:28:25 +00005450
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005451bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005452 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5453 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005454
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005455 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005456 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5457 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005458 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005459 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005460 return false;
5461
5462 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005463 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005464 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005465 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005466 break;
John McCall2de56d12010-08-25 11:45:40 +00005467 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005468 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005469 break;
John McCall2de56d12010-08-25 11:45:40 +00005470 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005471 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005472 break;
John McCall2de56d12010-08-25 11:45:40 +00005473 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005474 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005475 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005476 }
Richard Smith7b48a292012-02-01 05:53:12 +00005477
5478 if (Result.isInfinity() || Result.isNaN())
5479 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5480 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005481}
5482
5483bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5484 Result = E->getValue();
5485 return true;
5486}
5487
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005488bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5489 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005490
Eli Friedman2a523ee2011-03-25 00:54:52 +00005491 switch (E->getCastKind()) {
5492 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005493 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005494
5495 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005496 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005497 return EvaluateInteger(SubExpr, IntResult, Info) &&
5498 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5499 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005500 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005501
5502 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005503 if (!Visit(SubExpr))
5504 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005505 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5506 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005507 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005508
Eli Friedman2a523ee2011-03-25 00:54:52 +00005509 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005510 ComplexValue V;
5511 if (!EvaluateComplex(SubExpr, V, Info))
5512 return false;
5513 Result = V.getComplexFloatReal();
5514 return true;
5515 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005516 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005517}
5518
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005519//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005520// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005521//===----------------------------------------------------------------------===//
5522
5523namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005524class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005525 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005526 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005528public:
John McCallf4cf1a12010-05-07 17:22:02 +00005529 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005530 : ExprEvaluatorBaseTy(info), Result(Result) {}
5531
Richard Smith1aa0be82012-03-03 22:46:17 +00005532 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005533 Result.setFrom(V);
5534 return true;
5535 }
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Eli Friedman7ead5c72012-01-10 04:58:17 +00005537 bool ZeroInitialization(const Expr *E);
5538
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005539 //===--------------------------------------------------------------------===//
5540 // Visitor Methods
5541 //===--------------------------------------------------------------------===//
5542
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005543 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005544 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005545 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005546 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005547 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005548};
5549} // end anonymous namespace
5550
John McCallf4cf1a12010-05-07 17:22:02 +00005551static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5552 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005553 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005554 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005555}
5556
Eli Friedman7ead5c72012-01-10 04:58:17 +00005557bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005558 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005559 if (ElemTy->isRealFloatingType()) {
5560 Result.makeComplexFloat();
5561 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5562 Result.FloatReal = Zero;
5563 Result.FloatImag = Zero;
5564 } else {
5565 Result.makeComplexInt();
5566 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5567 Result.IntReal = Zero;
5568 Result.IntImag = Zero;
5569 }
5570 return true;
5571}
5572
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005573bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5574 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005575
5576 if (SubExpr->getType()->isRealFloatingType()) {
5577 Result.makeComplexFloat();
5578 APFloat &Imag = Result.FloatImag;
5579 if (!EvaluateFloat(SubExpr, Imag, Info))
5580 return false;
5581
5582 Result.FloatReal = APFloat(Imag.getSemantics());
5583 return true;
5584 } else {
5585 assert(SubExpr->getType()->isIntegerType() &&
5586 "Unexpected imaginary literal.");
5587
5588 Result.makeComplexInt();
5589 APSInt &Imag = Result.IntImag;
5590 if (!EvaluateInteger(SubExpr, Imag, Info))
5591 return false;
5592
5593 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5594 return true;
5595 }
5596}
5597
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005598bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005599
John McCall8786da72010-12-14 17:51:41 +00005600 switch (E->getCastKind()) {
5601 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005602 case CK_BaseToDerived:
5603 case CK_DerivedToBase:
5604 case CK_UncheckedDerivedToBase:
5605 case CK_Dynamic:
5606 case CK_ToUnion:
5607 case CK_ArrayToPointerDecay:
5608 case CK_FunctionToPointerDecay:
5609 case CK_NullToPointer:
5610 case CK_NullToMemberPointer:
5611 case CK_BaseToDerivedMemberPointer:
5612 case CK_DerivedToBaseMemberPointer:
5613 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005614 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005615 case CK_ConstructorConversion:
5616 case CK_IntegralToPointer:
5617 case CK_PointerToIntegral:
5618 case CK_PointerToBoolean:
5619 case CK_ToVoid:
5620 case CK_VectorSplat:
5621 case CK_IntegralCast:
5622 case CK_IntegralToBoolean:
5623 case CK_IntegralToFloating:
5624 case CK_FloatingToIntegral:
5625 case CK_FloatingToBoolean:
5626 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005627 case CK_CPointerToObjCPointerCast:
5628 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005629 case CK_AnyPointerToBlockPointerCast:
5630 case CK_ObjCObjectLValueCast:
5631 case CK_FloatingComplexToReal:
5632 case CK_FloatingComplexToBoolean:
5633 case CK_IntegralComplexToReal:
5634 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005635 case CK_ARCProduceObject:
5636 case CK_ARCConsumeObject:
5637 case CK_ARCReclaimReturnedObject:
5638 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005639 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005640 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005641
John McCall8786da72010-12-14 17:51:41 +00005642 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005643 case CK_AtomicToNonAtomic:
5644 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005645 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005646 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005647
5648 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005649 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005650 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005651 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005652
5653 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005654 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005655 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005656 return false;
5657
John McCall8786da72010-12-14 17:51:41 +00005658 Result.makeComplexFloat();
5659 Result.FloatImag = APFloat(Real.getSemantics());
5660 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005661 }
5662
John McCall8786da72010-12-14 17:51:41 +00005663 case CK_FloatingComplexCast: {
5664 if (!Visit(E->getSubExpr()))
5665 return false;
5666
5667 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5668 QualType From
5669 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5670
Richard Smithc1c5f272011-12-13 06:39:58 +00005671 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5672 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005673 }
5674
5675 case CK_FloatingComplexToIntegralComplex: {
5676 if (!Visit(E->getSubExpr()))
5677 return false;
5678
5679 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5680 QualType From
5681 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5682 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005683 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5684 To, Result.IntReal) &&
5685 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5686 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005687 }
5688
5689 case CK_IntegralRealToComplex: {
5690 APSInt &Real = Result.IntReal;
5691 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5692 return false;
5693
5694 Result.makeComplexInt();
5695 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5696 return true;
5697 }
5698
5699 case CK_IntegralComplexCast: {
5700 if (!Visit(E->getSubExpr()))
5701 return false;
5702
5703 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5704 QualType From
5705 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5706
Richard Smithf72fccf2012-01-30 22:27:01 +00005707 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5708 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005709 return true;
5710 }
5711
5712 case CK_IntegralComplexToFloatingComplex: {
5713 if (!Visit(E->getSubExpr()))
5714 return false;
5715
5716 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5717 QualType From
5718 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5719 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005720 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5721 To, Result.FloatReal) &&
5722 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5723 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005724 }
5725 }
5726
5727 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005728}
5729
John McCallf4cf1a12010-05-07 17:22:02 +00005730bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005731 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005732 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5733
Richard Smith745f5142012-01-27 01:14:48 +00005734 bool LHSOK = Visit(E->getLHS());
5735 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005737
John McCallf4cf1a12010-05-07 17:22:02 +00005738 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005739 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005740 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005741
Daniel Dunbar3f279872009-01-29 01:32:56 +00005742 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5743 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005744 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005745 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005746 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005747 if (Result.isComplexFloat()) {
5748 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5749 APFloat::rmNearestTiesToEven);
5750 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5751 APFloat::rmNearestTiesToEven);
5752 } else {
5753 Result.getComplexIntReal() += RHS.getComplexIntReal();
5754 Result.getComplexIntImag() += RHS.getComplexIntImag();
5755 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005756 break;
John McCall2de56d12010-08-25 11:45:40 +00005757 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005758 if (Result.isComplexFloat()) {
5759 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5760 APFloat::rmNearestTiesToEven);
5761 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5762 APFloat::rmNearestTiesToEven);
5763 } else {
5764 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5765 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5766 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005767 break;
John McCall2de56d12010-08-25 11:45:40 +00005768 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005769 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005770 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005771 APFloat &LHS_r = LHS.getComplexFloatReal();
5772 APFloat &LHS_i = LHS.getComplexFloatImag();
5773 APFloat &RHS_r = RHS.getComplexFloatReal();
5774 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005775
Daniel Dunbar3f279872009-01-29 01:32:56 +00005776 APFloat Tmp = LHS_r;
5777 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5778 Result.getComplexFloatReal() = Tmp;
5779 Tmp = LHS_i;
5780 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5781 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5782
5783 Tmp = LHS_r;
5784 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5785 Result.getComplexFloatImag() = Tmp;
5786 Tmp = LHS_i;
5787 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5788 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5789 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005790 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005791 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005792 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5793 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005794 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005795 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5796 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5797 }
5798 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005799 case BO_Div:
5800 if (Result.isComplexFloat()) {
5801 ComplexValue LHS = Result;
5802 APFloat &LHS_r = LHS.getComplexFloatReal();
5803 APFloat &LHS_i = LHS.getComplexFloatImag();
5804 APFloat &RHS_r = RHS.getComplexFloatReal();
5805 APFloat &RHS_i = RHS.getComplexFloatImag();
5806 APFloat &Res_r = Result.getComplexFloatReal();
5807 APFloat &Res_i = Result.getComplexFloatImag();
5808
5809 APFloat Den = RHS_r;
5810 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5811 APFloat Tmp = RHS_i;
5812 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5813 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5814
5815 Res_r = LHS_r;
5816 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5817 Tmp = LHS_i;
5818 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5819 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5820 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5821
5822 Res_i = LHS_i;
5823 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5824 Tmp = LHS_r;
5825 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5826 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5827 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5828 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005829 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5830 return Error(E, diag::note_expr_divide_by_zero);
5831
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005832 ComplexValue LHS = Result;
5833 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5834 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5835 Result.getComplexIntReal() =
5836 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5837 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5838 Result.getComplexIntImag() =
5839 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5840 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5841 }
5842 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005843 }
5844
John McCallf4cf1a12010-05-07 17:22:02 +00005845 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005846}
5847
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005848bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5849 // Get the operand value into 'Result'.
5850 if (!Visit(E->getSubExpr()))
5851 return false;
5852
5853 switch (E->getOpcode()) {
5854 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005855 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005856 case UO_Extension:
5857 return true;
5858 case UO_Plus:
5859 // The result is always just the subexpr.
5860 return true;
5861 case UO_Minus:
5862 if (Result.isComplexFloat()) {
5863 Result.getComplexFloatReal().changeSign();
5864 Result.getComplexFloatImag().changeSign();
5865 }
5866 else {
5867 Result.getComplexIntReal() = -Result.getComplexIntReal();
5868 Result.getComplexIntImag() = -Result.getComplexIntImag();
5869 }
5870 return true;
5871 case UO_Not:
5872 if (Result.isComplexFloat())
5873 Result.getComplexFloatImag().changeSign();
5874 else
5875 Result.getComplexIntImag() = -Result.getComplexIntImag();
5876 return true;
5877 }
5878}
5879
Eli Friedman7ead5c72012-01-10 04:58:17 +00005880bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5881 if (E->getNumInits() == 2) {
5882 if (E->getType()->isComplexType()) {
5883 Result.makeComplexFloat();
5884 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5885 return false;
5886 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5887 return false;
5888 } else {
5889 Result.makeComplexInt();
5890 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5891 return false;
5892 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5893 return false;
5894 }
5895 return true;
5896 }
5897 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5898}
5899
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005900//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005901// Void expression evaluation, primarily for a cast to void on the LHS of a
5902// comma operator
5903//===----------------------------------------------------------------------===//
5904
5905namespace {
5906class VoidExprEvaluator
5907 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5908public:
5909 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5910
Richard Smith1aa0be82012-03-03 22:46:17 +00005911 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005912
5913 bool VisitCastExpr(const CastExpr *E) {
5914 switch (E->getCastKind()) {
5915 default:
5916 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5917 case CK_ToVoid:
5918 VisitIgnoredValue(E->getSubExpr());
5919 return true;
5920 }
5921 }
5922};
5923} // end anonymous namespace
5924
5925static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5926 assert(E->isRValue() && E->getType()->isVoidType());
5927 return VoidExprEvaluator(Info).Visit(E);
5928}
5929
5930//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005931// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005932//===----------------------------------------------------------------------===//
5933
Richard Smith1aa0be82012-03-03 22:46:17 +00005934static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005935 // In C, function designators are not lvalues, but we evaluate them as if they
5936 // are.
5937 if (E->isGLValue() || E->getType()->isFunctionType()) {
5938 LValue LV;
5939 if (!EvaluateLValue(E, LV, Info))
5940 return false;
5941 LV.moveInto(Result);
5942 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005943 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005944 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005945 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005946 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005947 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005948 } else if (E->getType()->hasPointerRepresentation()) {
5949 LValue LV;
5950 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005951 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005952 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005953 } else if (E->getType()->isRealFloatingType()) {
5954 llvm::APFloat F(0.0);
5955 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005956 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005957 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005958 } else if (E->getType()->isAnyComplexType()) {
5959 ComplexValue C;
5960 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005961 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005962 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005963 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005964 MemberPtr P;
5965 if (!EvaluateMemberPointer(E, P, Info))
5966 return false;
5967 P.moveInto(Result);
5968 return true;
Richard Smith51201882011-12-30 21:15:51 +00005969 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005970 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005971 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005972 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005973 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005974 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005975 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005976 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005977 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005978 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5979 return false;
5980 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005981 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005982 if (Info.getLangOpts().CPlusPlus0x)
5983 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5984 << E->getType();
5985 else
5986 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005987 if (!EvaluateVoid(E, Info))
5988 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005989 } else if (Info.getLangOpts().CPlusPlus0x) {
5990 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5991 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005992 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00005993 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005994 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005995 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005996
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005997 return true;
5998}
5999
Richard Smith83587db2012-02-15 02:18:13 +00006000/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6001/// cases, the in-place evaluation is essential, since later initializers for
6002/// an object can indirectly refer to subobjects which were initialized earlier.
6003static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6004 const Expr *E, CheckConstantExpressionKind CCEK,
6005 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006006 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006007 return false;
6008
6009 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006010 // Evaluate arrays and record types in-place, so that later initializers can
6011 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006012 if (E->getType()->isArrayType())
6013 return EvaluateArray(E, This, Result, Info);
6014 else if (E->getType()->isRecordType())
6015 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006016 }
6017
6018 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006019 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006020}
6021
Richard Smithf48fdb02011-12-09 22:58:01 +00006022/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6023/// lvalue-to-rvalue cast if it is an lvalue.
6024static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006025 if (!CheckLiteralType(Info, E))
6026 return false;
6027
Richard Smith1aa0be82012-03-03 22:46:17 +00006028 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006029 return false;
6030
6031 if (E->isGLValue()) {
6032 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006033 LV.setFrom(Info.Ctx, Result);
6034 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006035 return false;
6036 }
6037
Richard Smith1aa0be82012-03-03 22:46:17 +00006038 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006039 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006040}
Richard Smithc49bd112011-10-28 17:51:58 +00006041
Richard Smith51f47082011-10-29 00:50:52 +00006042/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006043/// any crazy technique (that has nothing to do with language standards) that
6044/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006045/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6046/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006047bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006048 // Fast-path evaluations of integer literals, since we sometimes see files
6049 // containing vast quantities of these.
6050 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6051 Result.Val = APValue(APSInt(L->getValue(),
6052 L->getType()->isUnsignedIntegerType()));
6053 return true;
6054 }
6055
Richard Smith2d6a5672012-01-14 04:30:29 +00006056 // FIXME: Evaluating values of large array and record types can cause
6057 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006058 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6059 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006060 return false;
6061
Richard Smithf48fdb02011-12-09 22:58:01 +00006062 EvalInfo Info(Ctx, Result);
6063 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006064}
6065
Jay Foad4ba2a172011-01-12 09:06:06 +00006066bool Expr::EvaluateAsBooleanCondition(bool &Result,
6067 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006068 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006069 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006070 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006071}
6072
Richard Smith80d4b552011-12-28 19:48:30 +00006073bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6074 SideEffectsKind AllowSideEffects) const {
6075 if (!getType()->isIntegralOrEnumerationType())
6076 return false;
6077
Richard Smithc49bd112011-10-28 17:51:58 +00006078 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006079 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6080 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006081 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006082
Richard Smithc49bd112011-10-28 17:51:58 +00006083 Result = ExprResult.Val.getInt();
6084 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006085}
6086
Jay Foad4ba2a172011-01-12 09:06:06 +00006087bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006088 EvalInfo Info(Ctx, Result);
6089
John McCallefdb83e2010-05-07 21:00:08 +00006090 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006091 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6092 !CheckLValueConstantExpression(Info, getExprLoc(),
6093 Ctx.getLValueReferenceType(getType()), LV))
6094 return false;
6095
Richard Smith1aa0be82012-03-03 22:46:17 +00006096 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006097 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006098}
6099
Richard Smith099e7f62011-12-19 06:19:21 +00006100bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6101 const VarDecl *VD,
6102 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006103 // FIXME: Evaluating initializers for large array and record types can cause
6104 // performance problems. Only do so in C++11 for now.
6105 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6106 !Ctx.getLangOptions().CPlusPlus0x)
6107 return false;
6108
Richard Smith099e7f62011-12-19 06:19:21 +00006109 Expr::EvalStatus EStatus;
6110 EStatus.Diag = &Notes;
6111
6112 EvalInfo InitInfo(Ctx, EStatus);
6113 InitInfo.setEvaluatingDecl(VD, Value);
6114
6115 LValue LVal;
6116 LVal.set(VD);
6117
Richard Smith51201882011-12-30 21:15:51 +00006118 // C++11 [basic.start.init]p2:
6119 // Variables with static storage duration or thread storage duration shall be
6120 // zero-initialized before any other initialization takes place.
6121 // This behavior is not present in C.
6122 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6123 !VD->getType()->isReferenceType()) {
6124 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006125 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6126 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006127 return false;
6128 }
6129
Richard Smith83587db2012-02-15 02:18:13 +00006130 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6131 /*AllowNonLiteralTypes=*/true) ||
6132 EStatus.HasSideEffects)
6133 return false;
6134
6135 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6136 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006137}
6138
Richard Smith51f47082011-10-29 00:50:52 +00006139/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6140/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006141bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006142 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006143 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006144}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006145
Jay Foad4ba2a172011-01-12 09:06:06 +00006146bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006147 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006148}
6149
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006150APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006151 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006152 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006153 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006154 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006155 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006156
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006157 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006158}
John McCalld905f5a2010-05-07 05:32:02 +00006159
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006160 bool Expr::EvalResult::isGlobalLValue() const {
6161 assert(Val.isLValue());
6162 return IsGlobalLValue(Val.getLValueBase());
6163 }
6164
6165
John McCalld905f5a2010-05-07 05:32:02 +00006166/// isIntegerConstantExpr - this recursive routine will test if an expression is
6167/// an integer constant expression.
6168
6169/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6170/// comma, etc
6171///
6172/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6173/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6174/// cast+dereference.
6175
6176// CheckICE - This function does the fundamental ICE checking: the returned
6177// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6178// Note that to reduce code duplication, this helper does no evaluation
6179// itself; the caller checks whether the expression is evaluatable, and
6180// in the rare cases where CheckICE actually cares about the evaluated
6181// value, it calls into Evalute.
6182//
6183// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006184// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006185// 1: This expression is not an ICE, but if it isn't evaluated, it's
6186// a legal subexpression for an ICE. This return value is used to handle
6187// the comma operator in C99 mode.
6188// 2: This expression is not an ICE, and is not a legal subexpression for one.
6189
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006190namespace {
6191
John McCalld905f5a2010-05-07 05:32:02 +00006192struct ICEDiag {
6193 unsigned Val;
6194 SourceLocation Loc;
6195
6196 public:
6197 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6198 ICEDiag() : Val(0) {}
6199};
6200
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006201}
6202
6203static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006204
6205static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6206 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006207 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006208 !EVResult.Val.isInt()) {
6209 return ICEDiag(2, E->getLocStart());
6210 }
6211 return NoDiag();
6212}
6213
6214static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6215 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006216 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006217 return ICEDiag(2, E->getLocStart());
6218 }
6219
6220 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006221#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006222#define STMT(Node, Base) case Expr::Node##Class:
6223#define EXPR(Node, Base)
6224#include "clang/AST/StmtNodes.inc"
6225 case Expr::PredefinedExprClass:
6226 case Expr::FloatingLiteralClass:
6227 case Expr::ImaginaryLiteralClass:
6228 case Expr::StringLiteralClass:
6229 case Expr::ArraySubscriptExprClass:
6230 case Expr::MemberExprClass:
6231 case Expr::CompoundAssignOperatorClass:
6232 case Expr::CompoundLiteralExprClass:
6233 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006234 case Expr::DesignatedInitExprClass:
6235 case Expr::ImplicitValueInitExprClass:
6236 case Expr::ParenListExprClass:
6237 case Expr::VAArgExprClass:
6238 case Expr::AddrLabelExprClass:
6239 case Expr::StmtExprClass:
6240 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006241 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006242 case Expr::CXXDynamicCastExprClass:
6243 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006244 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006245 case Expr::CXXNullPtrLiteralExprClass:
6246 case Expr::CXXThisExprClass:
6247 case Expr::CXXThrowExprClass:
6248 case Expr::CXXNewExprClass:
6249 case Expr::CXXDeleteExprClass:
6250 case Expr::CXXPseudoDestructorExprClass:
6251 case Expr::UnresolvedLookupExprClass:
6252 case Expr::DependentScopeDeclRefExprClass:
6253 case Expr::CXXConstructExprClass:
6254 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006255 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006256 case Expr::CXXTemporaryObjectExprClass:
6257 case Expr::CXXUnresolvedConstructExprClass:
6258 case Expr::CXXDependentScopeMemberExprClass:
6259 case Expr::UnresolvedMemberExprClass:
6260 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006261 case Expr::ObjCNumericLiteralClass:
6262 case Expr::ObjCArrayLiteralClass:
6263 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006264 case Expr::ObjCEncodeExprClass:
6265 case Expr::ObjCMessageExprClass:
6266 case Expr::ObjCSelectorExprClass:
6267 case Expr::ObjCProtocolExprClass:
6268 case Expr::ObjCIvarRefExprClass:
6269 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006270 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006271 case Expr::ObjCIsaExprClass:
6272 case Expr::ShuffleVectorExprClass:
6273 case Expr::BlockExprClass:
6274 case Expr::BlockDeclRefExprClass:
6275 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006276 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006277 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006278 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006279 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006280 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006281 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006282 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006283 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006284 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006285 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006286 return ICEDiag(2, E->getLocStart());
6287
Douglas Gregoree8aff02011-01-04 17:33:58 +00006288 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006289 case Expr::GNUNullExprClass:
6290 // GCC considers the GNU __null value to be an integral constant expression.
6291 return NoDiag();
6292
John McCall91a57552011-07-15 05:09:51 +00006293 case Expr::SubstNonTypeTemplateParmExprClass:
6294 return
6295 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6296
John McCalld905f5a2010-05-07 05:32:02 +00006297 case Expr::ParenExprClass:
6298 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006299 case Expr::GenericSelectionExprClass:
6300 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006301 case Expr::IntegerLiteralClass:
6302 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006303 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006304 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006305 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006306 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006307 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006308 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006309 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006310 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006311 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006312 return NoDiag();
6313 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006314 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006315 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6316 // constant expressions, but they can never be ICEs because an ICE cannot
6317 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006318 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006319 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006320 return CheckEvalInICE(E, Ctx);
6321 return ICEDiag(2, E->getLocStart());
6322 }
Richard Smith359c89d2012-02-24 22:12:32 +00006323 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006324 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6325 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006326 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
6327 if (Ctx.getLangOptions().CPlusPlus &&
6328 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006329 // Parameter variables are never constants. Without this check,
6330 // getAnyInitializer() can find a default argument, which leads
6331 // to chaos.
6332 if (isa<ParmVarDecl>(D))
6333 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6334
6335 // C++ 7.1.5.1p2
6336 // A variable of non-volatile const-qualified integral or enumeration
6337 // type initialized by an ICE can be used in ICEs.
6338 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006339 if (!Dcl->getType()->isIntegralOrEnumerationType())
6340 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6341
Richard Smith099e7f62011-12-19 06:19:21 +00006342 const VarDecl *VD;
6343 // Look for a declaration of this variable that has an initializer, and
6344 // check whether it is an ICE.
6345 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6346 return NoDiag();
6347 else
6348 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006349 }
6350 }
6351 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006352 }
John McCalld905f5a2010-05-07 05:32:02 +00006353 case Expr::UnaryOperatorClass: {
6354 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6355 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006356 case UO_PostInc:
6357 case UO_PostDec:
6358 case UO_PreInc:
6359 case UO_PreDec:
6360 case UO_AddrOf:
6361 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006362 // C99 6.6/3 allows increment and decrement within unevaluated
6363 // subexpressions of constant expressions, but they can never be ICEs
6364 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006365 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006366 case UO_Extension:
6367 case UO_LNot:
6368 case UO_Plus:
6369 case UO_Minus:
6370 case UO_Not:
6371 case UO_Real:
6372 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006373 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006374 }
6375
6376 // OffsetOf falls through here.
6377 }
6378 case Expr::OffsetOfExprClass: {
6379 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006380 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006381 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006382 // compliance: we should warn earlier for offsetof expressions with
6383 // array subscripts that aren't ICEs, and if the array subscripts
6384 // are ICEs, the value of the offsetof must be an integer constant.
6385 return CheckEvalInICE(E, Ctx);
6386 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006387 case Expr::UnaryExprOrTypeTraitExprClass: {
6388 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6389 if ((Exp->getKind() == UETT_SizeOf) &&
6390 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006391 return ICEDiag(2, E->getLocStart());
6392 return NoDiag();
6393 }
6394 case Expr::BinaryOperatorClass: {
6395 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6396 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006397 case BO_PtrMemD:
6398 case BO_PtrMemI:
6399 case BO_Assign:
6400 case BO_MulAssign:
6401 case BO_DivAssign:
6402 case BO_RemAssign:
6403 case BO_AddAssign:
6404 case BO_SubAssign:
6405 case BO_ShlAssign:
6406 case BO_ShrAssign:
6407 case BO_AndAssign:
6408 case BO_XorAssign:
6409 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006410 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6411 // constant expressions, but they can never be ICEs because an ICE cannot
6412 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006413 return ICEDiag(2, E->getLocStart());
6414
John McCall2de56d12010-08-25 11:45:40 +00006415 case BO_Mul:
6416 case BO_Div:
6417 case BO_Rem:
6418 case BO_Add:
6419 case BO_Sub:
6420 case BO_Shl:
6421 case BO_Shr:
6422 case BO_LT:
6423 case BO_GT:
6424 case BO_LE:
6425 case BO_GE:
6426 case BO_EQ:
6427 case BO_NE:
6428 case BO_And:
6429 case BO_Xor:
6430 case BO_Or:
6431 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006432 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6433 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006434 if (Exp->getOpcode() == BO_Div ||
6435 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006436 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006437 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006438 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006439 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006440 if (REval == 0)
6441 return ICEDiag(1, E->getLocStart());
6442 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006443 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006444 if (LEval.isMinSignedValue())
6445 return ICEDiag(1, E->getLocStart());
6446 }
6447 }
6448 }
John McCall2de56d12010-08-25 11:45:40 +00006449 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006450 if (Ctx.getLangOptions().C99) {
6451 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6452 // if it isn't evaluated.
6453 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6454 return ICEDiag(1, E->getLocStart());
6455 } else {
6456 // In both C89 and C++, commas in ICEs are illegal.
6457 return ICEDiag(2, E->getLocStart());
6458 }
6459 }
6460 if (LHSResult.Val >= RHSResult.Val)
6461 return LHSResult;
6462 return RHSResult;
6463 }
John McCall2de56d12010-08-25 11:45:40 +00006464 case BO_LAnd:
6465 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006466 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6467 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6468 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6469 // Rare case where the RHS has a comma "side-effect"; we need
6470 // to actually check the condition to see whether the side
6471 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006472 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006473 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006474 return RHSResult;
6475 return NoDiag();
6476 }
6477
6478 if (LHSResult.Val >= RHSResult.Val)
6479 return LHSResult;
6480 return RHSResult;
6481 }
6482 }
6483 }
6484 case Expr::ImplicitCastExprClass:
6485 case Expr::CStyleCastExprClass:
6486 case Expr::CXXFunctionalCastExprClass:
6487 case Expr::CXXStaticCastExprClass:
6488 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006489 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006490 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006491 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006492 if (isa<ExplicitCastExpr>(E)) {
6493 if (const FloatingLiteral *FL
6494 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6495 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6496 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6497 APSInt IgnoredVal(DestWidth, !DestSigned);
6498 bool Ignored;
6499 // If the value does not fit in the destination type, the behavior is
6500 // undefined, so we are not required to treat it as a constant
6501 // expression.
6502 if (FL->getValue().convertToInteger(IgnoredVal,
6503 llvm::APFloat::rmTowardZero,
6504 &Ignored) & APFloat::opInvalidOp)
6505 return ICEDiag(2, E->getLocStart());
6506 return NoDiag();
6507 }
6508 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006509 switch (cast<CastExpr>(E)->getCastKind()) {
6510 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006511 case CK_AtomicToNonAtomic:
6512 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006513 case CK_NoOp:
6514 case CK_IntegralToBoolean:
6515 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006516 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006517 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006518 return ICEDiag(2, E->getLocStart());
6519 }
John McCalld905f5a2010-05-07 05:32:02 +00006520 }
John McCall56ca35d2011-02-17 10:25:35 +00006521 case Expr::BinaryConditionalOperatorClass: {
6522 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6523 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6524 if (CommonResult.Val == 2) return CommonResult;
6525 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6526 if (FalseResult.Val == 2) return FalseResult;
6527 if (CommonResult.Val == 1) return CommonResult;
6528 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006529 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006530 return FalseResult;
6531 }
John McCalld905f5a2010-05-07 05:32:02 +00006532 case Expr::ConditionalOperatorClass: {
6533 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6534 // If the condition (ignoring parens) is a __builtin_constant_p call,
6535 // then only the true side is actually considered in an integer constant
6536 // expression, and it is fully evaluated. This is an important GNU
6537 // extension. See GCC PR38377 for discussion.
6538 if (const CallExpr *CallCE
6539 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006540 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6541 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006542 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006543 if (CondResult.Val == 2)
6544 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006545
Richard Smithf48fdb02011-12-09 22:58:01 +00006546 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6547 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006548
John McCalld905f5a2010-05-07 05:32:02 +00006549 if (TrueResult.Val == 2)
6550 return TrueResult;
6551 if (FalseResult.Val == 2)
6552 return FalseResult;
6553 if (CondResult.Val == 1)
6554 return CondResult;
6555 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6556 return NoDiag();
6557 // Rare case where the diagnostics depend on which side is evaluated
6558 // Note that if we get here, CondResult is 0, and at least one of
6559 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006560 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006561 return FalseResult;
6562 }
6563 return TrueResult;
6564 }
6565 case Expr::CXXDefaultArgExprClass:
6566 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6567 case Expr::ChooseExprClass: {
6568 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6569 }
6570 }
6571
David Blaikie30263482012-01-20 21:50:17 +00006572 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006573}
6574
Richard Smithf48fdb02011-12-09 22:58:01 +00006575/// Evaluate an expression as a C++11 integral constant expression.
6576static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6577 const Expr *E,
6578 llvm::APSInt *Value,
6579 SourceLocation *Loc) {
6580 if (!E->getType()->isIntegralOrEnumerationType()) {
6581 if (Loc) *Loc = E->getExprLoc();
6582 return false;
6583 }
6584
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006585 APValue Result;
6586 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006587 return false;
6588
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006589 assert(Result.isInt() && "pointer cast to int is not an ICE");
6590 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006591 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006592}
6593
Richard Smithdd1f29b2011-12-12 09:28:41 +00006594bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006595 if (Ctx.getLangOptions().CPlusPlus0x)
6596 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6597
John McCalld905f5a2010-05-07 05:32:02 +00006598 ICEDiag d = CheckICE(this, Ctx);
6599 if (d.Val != 0) {
6600 if (Loc) *Loc = d.Loc;
6601 return false;
6602 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006603 return true;
6604}
6605
6606bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6607 SourceLocation *Loc, bool isEvaluated) const {
6608 if (Ctx.getLangOptions().CPlusPlus0x)
6609 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6610
6611 if (!isIntegerConstantExpr(Ctx, Loc))
6612 return false;
6613 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006614 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006615 return true;
6616}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006617
Richard Smith70488e22012-02-14 21:38:30 +00006618bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6619 return CheckICE(this, Ctx).Val == 0;
6620}
6621
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006622bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6623 SourceLocation *Loc) const {
6624 // We support this checking in C++98 mode in order to diagnose compatibility
6625 // issues.
6626 assert(Ctx.getLangOptions().CPlusPlus);
6627
Richard Smith70488e22012-02-14 21:38:30 +00006628 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006629 Expr::EvalStatus Status;
6630 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6631 Status.Diag = &Diags;
6632 EvalInfo Info(Ctx, Status);
6633
6634 APValue Scratch;
6635 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6636
6637 if (!Diags.empty()) {
6638 IsConstExpr = false;
6639 if (Loc) *Loc = Diags[0].first;
6640 } else if (!IsConstExpr) {
6641 // FIXME: This shouldn't happen.
6642 if (Loc) *Loc = getExprLoc();
6643 }
6644
6645 return IsConstExpr;
6646}
Richard Smith745f5142012-01-27 01:14:48 +00006647
6648bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6649 llvm::SmallVectorImpl<
6650 PartialDiagnosticAt> &Diags) {
6651 // FIXME: It would be useful to check constexpr function templates, but at the
6652 // moment the constant expression evaluator cannot cope with the non-rigorous
6653 // ASTs which we build for dependent expressions.
6654 if (FD->isDependentContext())
6655 return true;
6656
6657 Expr::EvalStatus Status;
6658 Status.Diag = &Diags;
6659
6660 EvalInfo Info(FD->getASTContext(), Status);
6661 Info.CheckingPotentialConstantExpression = true;
6662
6663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6664 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6665
6666 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6667 // is a temporary being used as the 'this' pointer.
6668 LValue This;
6669 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006670 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006671
Richard Smith745f5142012-01-27 01:14:48 +00006672 ArrayRef<const Expr*> Args;
6673
6674 SourceLocation Loc = FD->getLocation();
6675
Richard Smith1aa0be82012-03-03 22:46:17 +00006676 APValue Scratch;
6677 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006678 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006679 else
Richard Smith745f5142012-01-27 01:14:48 +00006680 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6681 Args, FD->getBody(), Info, Scratch);
6682
6683 return Diags.empty();
6684}