blob: 4ef169d18995cab25e136096e19fce2d593ebdc6 [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"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smithd0dccea2011-10-28 22:34:42 +0000267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000272 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000273
Richard Smith08d6e032011-12-16 19:06:07 +0000274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
Richard Smith83587db2012-02-15 02:18:13 +0000280 /// Index - The call index of this call.
281 unsigned Index;
282
Richard Smith180f4792011-11-10 06:34:14 +0000283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
Richard Smithd0dccea2011-10-28 22:34:42 +0000286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000288 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000289
Richard Smith1aa0be82012-03-03 22:46:17 +0000290 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000291 typedef MapTy::const_iterator temp_iterator;
292 /// Temporaries - Temporary lvalues materialized within this stack frame.
293 MapTy Temporaries;
294
Richard Smith08d6e032011-12-16 19:06:07 +0000295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
296 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000297 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000298 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000299 };
300
Richard Smithdd1f29b2011-12-12 09:28:41 +0000301 /// A partial diagnostic which we might know in advance that we are not going
302 /// to emit.
303 class OptionalDiagnostic {
304 PartialDiagnostic *Diag;
305
306 public:
307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
308
309 template<typename T>
310 OptionalDiagnostic &operator<<(const T &v) {
311 if (Diag)
312 *Diag << v;
313 return *this;
314 }
Richard Smith789f9b62012-01-31 04:08:20 +0000315
316 OptionalDiagnostic &operator<<(const APSInt &I) {
317 if (Diag) {
318 llvm::SmallVector<char, 32> Buffer;
319 I.toString(Buffer);
320 *Diag << StringRef(Buffer.data(), Buffer.size());
321 }
322 return *this;
323 }
324
325 OptionalDiagnostic &operator<<(const APFloat &F) {
326 if (Diag) {
327 llvm::SmallVector<char, 32> Buffer;
328 F.toString(Buffer);
329 *Diag << StringRef(Buffer.data(), Buffer.size());
330 }
331 return *this;
332 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000333 };
334
Richard Smith83587db2012-02-15 02:18:13 +0000335 /// EvalInfo - This is a private struct used by the evaluator to capture
336 /// information about a subexpression as it is folded. It retains information
337 /// about the AST context, but also maintains information about the folded
338 /// expression.
339 ///
340 /// If an expression could be evaluated, it is still possible it is not a C
341 /// "integer constant expression" or constant expression. If not, this struct
342 /// captures information about how and why not.
343 ///
344 /// One bit of information passed *into* the request for constant folding
345 /// indicates whether the subexpression is "evaluated" or not according to C
346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
347 /// evaluate the expression regardless of what the RHS is, but C only allows
348 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000349 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000350 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000351
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 /// EvalStatus - Contains information about the evaluation.
353 Expr::EvalStatus &EvalStatus;
354
355 /// CurrentCall - The top of the constexpr call stack.
356 CallStackFrame *CurrentCall;
357
Richard Smithbd552ef2011-10-31 05:52:43 +0000358 /// CallStackDepth - The number of calls in the call stack right now.
359 unsigned CallStackDepth;
360
Richard Smith83587db2012-02-15 02:18:13 +0000361 /// NextCallIndex - The next call index to assign.
362 unsigned NextCallIndex;
363
Richard Smith1aa0be82012-03-03 22:46:17 +0000364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000365 /// OpaqueValues - Values used as the common expression in a
366 /// BinaryConditionalOperator.
367 MapTy OpaqueValues;
368
369 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000370 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 CallStackFrame BottomFrame;
372
Richard Smith180f4792011-11-10 06:34:14 +0000373 /// EvaluatingDecl - This is the declaration whose initializer is being
374 /// evaluated, if any.
375 const VarDecl *EvaluatingDecl;
376
377 /// EvaluatingDeclValue - This is the value being constructed for the
378 /// declaration whose initializer is being evaluated, if any.
379 APValue *EvaluatingDeclValue;
380
Richard Smithc1c5f272011-12-13 06:39:58 +0000381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
382 /// notes attached to it will also be stored, otherwise they will not be.
383 bool HasActiveDiagnostic;
384
Richard Smith745f5142012-01-27 01:14:48 +0000385 /// CheckingPotentialConstantExpression - Are we checking whether the
386 /// expression is a potential constant expression? If so, some diagnostics
387 /// are suppressed.
388 bool CheckingPotentialConstantExpression;
389
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000392 CallStackDepth(0), NextCallIndex(1),
393 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000395 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
Richard Smith1aa0be82012-03-03 22:46:17 +0000397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 MapTy::const_iterator i = OpaqueValues.find(e);
399 if (i == OpaqueValues.end()) return 0;
400 return &i->second;
401 }
402
Richard Smith180f4792011-11-10 06:34:14 +0000403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
404 EvaluatingDecl = VD;
405 EvaluatingDeclValue = &Value;
406 }
407
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000409
Richard Smithc1c5f272011-12-13 06:39:58 +0000410 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000411 // Don't perform any constexpr calls (other than the call we're checking)
412 // when checking a potential constant expression.
413 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
414 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000415 if (NextCallIndex == 0) {
416 // NextCallIndex has wrapped around.
417 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
418 return false;
419 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
421 return true;
422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
423 << getLangOpts().ConstexprCallDepth;
424 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000425 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000426
Richard Smith83587db2012-02-15 02:18:13 +0000427 CallStackFrame *getCallFrame(unsigned CallIndex) {
428 assert(CallIndex && "no call index in getCallFrame");
429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
430 // be null in this loop.
431 CallStackFrame *Frame = CurrentCall;
432 while (Frame->Index > CallIndex)
433 Frame = Frame->Caller;
434 return (Frame->Index == CallIndex) ? Frame : 0;
435 }
436
Richard Smithc1c5f272011-12-13 06:39:58 +0000437 private:
438 /// Add a diagnostic to the diagnostics list.
439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
442 return EvalStatus.Diag->back().second;
443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 /// Add notes containing a call stack to the current point of evaluation.
446 void addCallStack(unsigned Limit);
447
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
451 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 // If we have a prior diagnostic, it will be noting that the expression
454 // isn't a constant expression. This diagnostic is more important.
455 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000457 unsigned CallStackNotes = CallStackDepth - 1;
458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
459 if (Limit)
460 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000461 if (CheckingPotentialConstantExpression)
462 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000463
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
467 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (!CheckingPotentialConstantExpression)
469 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000471 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 return OptionalDiagnostic();
474 }
475
Richard Smith5cfc7d82012-03-15 04:53:45 +0000476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
477 = diag::note_invalid_subexpr_in_const_expr,
478 unsigned ExtraNotes = 0) {
479 if (EvalStatus.Diag)
480 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
481 HasActiveDiagnostic = false;
482 return OptionalDiagnostic();
483 }
484
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 /// Diagnose that the evaluation does not produce a C++11 core constant
486 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000487 template<typename LocArg>
488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000489 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
493 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000494 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000495 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 return Diag(Loc, DiagId, ExtraNotes);
497 }
498
499 /// Add a note to a prior diagnostic.
500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
501 if (!HasActiveDiagnostic)
502 return OptionalDiagnostic();
503 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000504 }
Richard Smith099e7f62011-12-19 06:19:21 +0000505
506 /// Add a stack of notes to a prior diagnostic.
507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
508 if (HasActiveDiagnostic) {
509 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
510 Diags.begin(), Diags.end());
511 }
512 }
Richard Smith745f5142012-01-27 01:14:48 +0000513
514 /// Should we continue evaluation as much as possible after encountering a
515 /// construct which can't be folded?
516 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000517 return CheckingPotentialConstantExpression &&
518 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000519 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000520 };
Richard Smithf15fda02012-02-02 01:16:57 +0000521
522 /// Object used to treat all foldable expressions as constant expressions.
523 struct FoldConstant {
524 bool Enabled;
525
526 explicit FoldConstant(EvalInfo &Info)
527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects) {
529 }
530 // Treat the value we've computed since this object was created as constant.
531 void Fold(EvalInfo &Info) {
532 if (Enabled && !Info.EvalStatus.Diag->empty() &&
533 !Info.EvalStatus.HasSideEffects)
534 Info.EvalStatus.Diag->clear();
535 }
536 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000537
538 /// RAII object used to suppress diagnostics and side-effects from a
539 /// speculative evaluation.
540 class SpeculativeEvaluationRAII {
541 EvalInfo &Info;
542 Expr::EvalStatus Old;
543
544 public:
545 SpeculativeEvaluationRAII(EvalInfo &Info,
546 llvm::SmallVectorImpl<PartialDiagnosticAt>
547 *NewDiag = 0)
548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
598static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
646 llvm::SmallVector<char, 128> Buffer;
647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
749 if (!Info.getLangOpts().CPlusPlus0x)
750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000937 return true;
938 case Expr::CallExprClass:
939 return IsStringLiteralCall(cast<CallExpr>(E));
940 // For GCC compatibility, &&label has static storage duration.
941 case Expr::AddrLabelExprClass:
942 return true;
943 // A Block literal expression may be used as the initialization value for
944 // Block variables at global or local static scope.
945 case Expr::BlockExprClass:
946 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000947 case Expr::ImplicitValueInitExprClass:
948 // FIXME:
949 // We can never form an lvalue with an implicit value initialization as its
950 // base through expression evaluation, so these only appear in one case: the
951 // implicit variable declaration we invent when checking whether a constexpr
952 // constructor can produce a constant expression. We must assume that such
953 // an expression might be a global lvalue.
954 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000955 }
John McCall42c8f872010-05-10 23:27:23 +0000956}
957
Richard Smith83587db2012-02-15 02:18:13 +0000958static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
959 assert(Base && "no location for a null lvalue");
960 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
961 if (VD)
962 Info.Note(VD->getLocation(), diag::note_declared_at);
963 else
964 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
965 diag::note_constexpr_temporary_here);
966}
967
Richard Smith9a17a682011-11-07 05:07:52 +0000968/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000969/// value for an address or reference constant expression. Return true if we
970/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000971static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
972 QualType Type, const LValue &LVal) {
973 bool IsReferenceType = Type->isReferenceType();
974
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 APValue::LValueBase Base = LVal.getLValueBase();
976 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
977
Richard Smithb78ae972012-02-18 04:58:18 +0000978 // Check that the object is a global. Note that the fake 'this' object we
979 // manufacture when checking potential constant expressions is conservatively
980 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000981 if (!IsGlobalLValue(Base)) {
982 if (Info.getLangOpts().CPlusPlus0x) {
983 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000984 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
985 << IsReferenceType << !Designator.Entries.empty()
986 << !!VD << VD;
987 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000988 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000989 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000990 }
Richard Smith61e61622012-01-12 06:08:57 +0000991 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000992 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000993 }
Richard Smith83587db2012-02-15 02:18:13 +0000994 assert((Info.CheckingPotentialConstantExpression ||
995 LVal.getLValueCallIndex() == 0) &&
996 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000997
998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001006 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001007 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001008 }
1009
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001011 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001015 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 }
1017
Richard Smith9a17a682011-11-07 05:07:52 +00001018 return true;
1019}
1020
Richard Smith51201882011-12-30 21:15:51 +00001021/// Check that this core constant expression is of literal type, and if not,
1022/// produce an appropriate diagnostic.
1023static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001029 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001030 << E->getType();
1031 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001033 return false;
1034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001037/// constant expression. If not, report an appropriate diagnostic. Does not
1038/// check that the expression is of literal type.
1039static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001055 }
Richard Smith83587db2012-02-15 02:18:13 +00001056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
1074 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1075 Value.getStructField((*I)->getFieldIndex())))
1076 return false;
1077 }
1078 }
1079
1080 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001081 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001082 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1084 }
1085
1086 // Everything else is fine.
1087 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001088}
1089
Richard Smith9e36b532011-10-31 05:11:32 +00001090const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001091 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001092}
1093
1094static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001096}
1097
Richard Smith65ac5982011-11-01 21:06:14 +00001098static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001100 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001101}
1102
Richard Smith1aa0be82012-03-03 22:46:17 +00001103static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001108 return true;
1109 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001110
Richard Smithe24f5fc2011-11-17 22:56:20 +00001111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001113 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001115 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001116}
1117
Richard Smith1aa0be82012-03-03 22:46:17 +00001118static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1121 return false;
1122 case APValue::Int:
1123 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001124 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001127 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1131 return true;
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1135 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1140 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001141 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001142 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001143 case APValue::Struct:
1144 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001145 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001146 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001147 }
1148
Richard Smithc49bd112011-10-28 17:51:58 +00001149 llvm_unreachable("unknown APValue kind");
1150}
1151
1152static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1153 EvalInfo &Info) {
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001155 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001156 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001157 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001158 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001159}
1160
Richard Smithc1c5f272011-12-13 06:39:58 +00001161template<typename T>
1162static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1163 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001164 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001165 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001166 return false;
1167}
1168
1169static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1170 QualType SrcType, const APFloat &Value,
1171 QualType DestType, APSInt &Result) {
1172 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001174 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Richard Smithc1c5f272011-12-13 06:39:58 +00001176 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001177 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001178 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1179 & APFloat::opInvalidOp)
1180 return HandleOverflow(Info, E, Value, DestType);
1181 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001182}
1183
Richard Smithc1c5f272011-12-13 06:39:58 +00001184static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1185 QualType SrcType, QualType DestType,
1186 APFloat &Result) {
1187 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1190 APFloat::rmNearestTiesToEven, &ignored)
1191 & APFloat::opOverflow)
1192 return HandleOverflow(Info, E, Value, DestType);
1193 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194}
1195
Richard Smithf72fccf2012-01-30 22:27:01 +00001196static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1197 QualType DestType, QualType SrcType,
1198 APSInt &Value) {
1199 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001200 APSInt Result = Value;
1201 // Figure out if this is a truncate, extend or noop cast.
1202 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001203 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001204 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001205 return Result;
1206}
1207
Richard Smithc1c5f272011-12-13 06:39:58 +00001208static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1209 QualType SrcType, const APSInt &Value,
1210 QualType DestType, APFloat &Result) {
1211 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1212 if (Result.convertFromAPInt(Value, Value.isSigned(),
1213 APFloat::rmNearestTiesToEven)
1214 & APFloat::opOverflow)
1215 return HandleOverflow(Info, E, Value, DestType);
1216 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001217}
1218
Eli Friedmane6a24e82011-12-22 03:51:45 +00001219static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1220 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001221 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001222 if (!Evaluate(SVal, Info, E))
1223 return false;
1224 if (SVal.isInt()) {
1225 Res = SVal.getInt();
1226 return true;
1227 }
1228 if (SVal.isFloat()) {
1229 Res = SVal.getFloat().bitcastToAPInt();
1230 return true;
1231 }
1232 if (SVal.isVector()) {
1233 QualType VecTy = E->getType();
1234 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1235 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1236 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1237 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1238 Res = llvm::APInt::getNullValue(VecSize);
1239 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1240 APValue &Elt = SVal.getVectorElt(i);
1241 llvm::APInt EltAsInt;
1242 if (Elt.isInt()) {
1243 EltAsInt = Elt.getInt();
1244 } else if (Elt.isFloat()) {
1245 EltAsInt = Elt.getFloat().bitcastToAPInt();
1246 } else {
1247 // Don't try to handle vectors of anything other than int or float
1248 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001249 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001250 return false;
1251 }
1252 unsigned BaseEltSize = EltAsInt.getBitWidth();
1253 if (BigEndian)
1254 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1255 else
1256 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1257 }
1258 return true;
1259 }
1260 // Give up if the input isn't an int, float, or vector. For example, we
1261 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001262 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001263 return false;
1264}
1265
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266/// Cast an lvalue referring to a base subobject to a derived class, by
1267/// truncating the lvalue's path to the given length.
1268static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1269 const RecordDecl *TruncatedType,
1270 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001271 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272
1273 // Check we actually point to a derived class object.
1274 if (TruncatedElements == D.Entries.size())
1275 return true;
1276 assert(TruncatedElements >= D.MostDerivedPathLength &&
1277 "not casting to a derived class");
1278 if (!Result.checkSubobject(Info, E, CSK_Derived))
1279 return false;
1280
1281 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001282 const RecordDecl *RD = TruncatedType;
1283 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001287 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 else
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getBaseClassOffset(Base);
1290 RD = Base;
1291 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001293 return true;
1294}
1295
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
1300 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1301 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001303}
1304
Richard Smithb4e85ed2012-01-06 16:39:00 +00001305static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001306 const CXXRecordDecl *DerivedDecl,
1307 const CXXBaseSpecifier *Base) {
1308 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1309
1310 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001312 return true;
1313 }
1314
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 SubobjectDesignator &D = Obj.Designator;
1316 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001317 return false;
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 // Extract most-derived object and corresponding type.
1320 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1321 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1322 return false;
1323
1324 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001325 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1326 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001328 return true;
1329}
1330
1331/// Update LVal to refer to the given field, which must be a member of the type
1332/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001334 const FieldDecl *FD,
1335 const ASTRecordLayout *RL = 0) {
1336 if (!RL)
1337 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1338
1339 unsigned I = FD->getFieldIndex();
1340 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001341 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001342}
1343
Richard Smithd9b02e72012-01-25 22:15:11 +00001344/// Update LVal to refer to the given indirect field.
1345static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1346 LValue &LVal,
1347 const IndirectFieldDecl *IFD) {
1348 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1349 CE = IFD->chain_end(); C != CE; ++C)
1350 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1351}
1352
Richard Smith180f4792011-11-10 06:34:14 +00001353/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001354static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1355 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001356 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1357 // extension.
1358 if (Type->isVoidType() || Type->isFunctionType()) {
1359 Size = CharUnits::One();
1360 return true;
1361 }
1362
1363 if (!Type->isConstantSizeType()) {
1364 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001365 // FIXME: Better diagnostic.
1366 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001367 return false;
1368 }
1369
1370 Size = Info.Ctx.getTypeSizeInChars(Type);
1371 return true;
1372}
1373
1374/// Update a pointer value to model pointer arithmetic.
1375/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001376/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001377/// \param LVal - The pointer value to be updated.
1378/// \param EltTy - The pointee type represented by LVal.
1379/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001380static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1381 LValue &LVal, QualType EltTy,
1382 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001383 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001384 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001385 return false;
1386
1387 // Compute the new offset in the appropriate width.
1388 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001390 return true;
1391}
1392
Richard Smith86024012012-02-18 22:04:06 +00001393/// Update an lvalue to refer to a component of a complex number.
1394/// \param Info - Information about the ongoing evaluation.
1395/// \param LVal - The lvalue to be updated.
1396/// \param EltTy - The complex number's component type.
1397/// \param Imag - False for the real component, true for the imaginary.
1398static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1399 LValue &LVal, QualType EltTy,
1400 bool Imag) {
1401 if (Imag) {
1402 CharUnits SizeOfComponent;
1403 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1404 return false;
1405 LVal.Offset += SizeOfComponent;
1406 }
1407 LVal.addComplex(Info, E, EltTy, Imag);
1408 return true;
1409}
1410
Richard Smith03f96112011-10-24 17:54:18 +00001411/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001412static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1413 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001414 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001415 // If this is a parameter to an active constexpr function call, perform
1416 // argument substitution.
1417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001418 // Assume arguments of a potential constant expression are unknown
1419 // constant expressions.
1420 if (Info.CheckingPotentialConstantExpression)
1421 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001423 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001424 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001425 }
Richard Smith177dce72011-11-01 16:57:24 +00001426 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1427 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001428 }
Richard Smith03f96112011-10-24 17:54:18 +00001429
Richard Smith099e7f62011-12-19 06:19:21 +00001430 // Dig out the initializer, and use the declaration which it's attached to.
1431 const Expr *Init = VD->getAnyInitializer(VD);
1432 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001433 // If we're checking a potential constant expression, the variable could be
1434 // initialized later.
1435 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001436 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001437 return false;
1438 }
1439
Richard Smith180f4792011-11-10 06:34:14 +00001440 // If we're currently evaluating the initializer of this declaration, use that
1441 // in-flight value.
1442 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001443 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001444 return !Result.isUninit();
1445 }
1446
Richard Smith65ac5982011-11-01 21:06:14 +00001447 // Never evaluate the initializer of a weak variable. We can't be sure that
1448 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001450 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001451 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001452 }
Richard Smith65ac5982011-11-01 21:06:14 +00001453
Richard Smith099e7f62011-12-19 06:19:21 +00001454 // Check that we can fold the initializer. In C++, we will have already done
1455 // this in the cases where it matters for conformance.
1456 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1457 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001458 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001459 Notes.size() + 1) << VD;
1460 Info.Note(VD->getLocation(), diag::note_declared_at);
1461 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001462 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001463 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001464 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001465 Notes.size() + 1) << VD;
1466 Info.Note(VD->getLocation(), diag::note_declared_at);
1467 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001468 }
Richard Smith03f96112011-10-24 17:54:18 +00001469
Richard Smith1aa0be82012-03-03 22:46:17 +00001470 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001471 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001472}
1473
Richard Smithc49bd112011-10-28 17:51:58 +00001474static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001475 Qualifiers Quals = T.getQualifiers();
1476 return Quals.hasConst() && !Quals.hasVolatile();
1477}
1478
Richard Smith59efe262011-11-11 04:05:33 +00001479/// Get the base index of the given base class within an APValue representing
1480/// the given derived class.
1481static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1482 const CXXRecordDecl *Base) {
1483 Base = Base->getCanonicalDecl();
1484 unsigned Index = 0;
1485 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1486 E = Derived->bases_end(); I != E; ++I, ++Index) {
1487 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1488 return Index;
1489 }
1490
1491 llvm_unreachable("base class missing from derived class's bases list");
1492}
1493
Richard Smithf3908f22012-02-17 03:35:37 +00001494/// Extract the value of a character from a string literal.
1495static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1496 uint64_t Index) {
1497 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1498 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1499 assert(S && "unexpected string literal expression kind");
1500
1501 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1502 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1503 if (Index < S->getLength())
1504 Value = S->getCodeUnit(Index);
1505 return Value;
1506}
1507
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001509static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001510 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001511 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001512 if (Sub.Invalid)
1513 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001514 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001515 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001516 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001517 (unsigned)diag::note_constexpr_read_past_end :
1518 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001519 return false;
1520 }
Richard Smithf64699e2011-11-11 08:28:03 +00001521 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001522 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001523 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1524 // This object might be initialized later.
1525 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526
Richard Smith0069b842012-03-10 00:28:11 +00001527 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001528 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001531 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001533 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001535 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 // Note, it should not be possible to form a pointer with a valid
1537 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001538 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001539 (unsigned)diag::note_constexpr_read_past_end :
1540 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001542 }
Richard Smithf3908f22012-02-17 03:35:37 +00001543 // An array object is represented as either an Array APValue or as an
1544 // LValue which refers to a string literal.
1545 if (O->isLValue()) {
1546 assert(I == N - 1 && "extracting subobject of character?");
1547 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001548 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001549 Info, O->getLValueBase().get<const Expr*>(), Index));
1550 return true;
1551 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001552 O = &O->getArrayInitializedElt(Index);
1553 else
1554 O = &O->getArrayFiller();
1555 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001556 } else if (ObjType->isAnyComplexType()) {
1557 // Next subobject is a complex number.
1558 uint64_t Index = Sub.Entries[I].ArrayIndex;
1559 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001560 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001561 (unsigned)diag::note_constexpr_read_past_end :
1562 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1563 return false;
1564 }
1565 assert(I == N - 1 && "extracting subobject of scalar?");
1566 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001567 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001568 : O->getComplexIntReal());
1569 } else {
1570 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001571 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001572 : O->getComplexFloatReal());
1573 }
1574 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001575 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001576 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001577 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001578 << Field;
1579 Info.Note(Field->getLocation(), diag::note_declared_at);
1580 return false;
1581 }
1582
Richard Smith180f4792011-11-10 06:34:14 +00001583 // Next subobject is a class, struct or union field.
1584 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1585 if (RD->isUnion()) {
1586 const FieldDecl *UnionField = O->getUnionField();
1587 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001588 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001589 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001590 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001591 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001592 }
Richard Smith180f4792011-11-10 06:34:14 +00001593 O = &O->getUnionValue();
1594 } else
1595 O = &O->getStructField(Field->getFieldIndex());
1596 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001597
1598 if (ObjType.isVolatileQualified()) {
1599 if (Info.getLangOpts().CPlusPlus) {
1600 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001601 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001602 << 2 << Field;
1603 Info.Note(Field->getLocation(), diag::note_declared_at);
1604 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001605 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001606 }
1607 return false;
1608 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001609 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001610 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001611 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1612 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1613 O = &O->getStructBase(getBaseIndex(Derived, Base));
1614 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 }
Richard Smith180f4792011-11-10 06:34:14 +00001616
Richard Smithf48fdb02011-12-09 22:58:01 +00001617 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001618 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001619 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001620 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001621 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 }
1623
Richard Smith0069b842012-03-10 00:28:11 +00001624 // This may look super-stupid, but it serves an important purpose: if we just
1625 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1626 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1627 // object, which is destroyed by Tmp's destructor.
1628 APValue Tmp;
1629 O->swap(Tmp);
1630 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001631 return true;
1632}
1633
Richard Smithf15fda02012-02-02 01:16:57 +00001634/// Find the position where two subobject designators diverge, or equivalently
1635/// the length of the common initial subsequence.
1636static unsigned FindDesignatorMismatch(QualType ObjType,
1637 const SubobjectDesignator &A,
1638 const SubobjectDesignator &B,
1639 bool &WasArrayIndex) {
1640 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1641 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001642 if (!ObjType.isNull() &&
1643 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001644 // Next subobject is an array element.
1645 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1646 WasArrayIndex = true;
1647 return I;
1648 }
Richard Smith86024012012-02-18 22:04:06 +00001649 if (ObjType->isAnyComplexType())
1650 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1651 else
1652 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001653 } else {
1654 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1655 WasArrayIndex = false;
1656 return I;
1657 }
1658 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1659 // Next subobject is a field.
1660 ObjType = FD->getType();
1661 else
1662 // Next subobject is a base class.
1663 ObjType = QualType();
1664 }
1665 }
1666 WasArrayIndex = false;
1667 return I;
1668}
1669
1670/// Determine whether the given subobject designators refer to elements of the
1671/// same array object.
1672static bool AreElementsOfSameArray(QualType ObjType,
1673 const SubobjectDesignator &A,
1674 const SubobjectDesignator &B) {
1675 if (A.Entries.size() != B.Entries.size())
1676 return false;
1677
1678 bool IsArray = A.MostDerivedArraySize != 0;
1679 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1680 // A is a subobject of the array element.
1681 return false;
1682
1683 // If A (and B) designates an array element, the last entry will be the array
1684 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1685 // of length 1' case, and the entire path must match.
1686 bool WasArrayIndex;
1687 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1688 return CommonLength >= A.Entries.size() - IsArray;
1689}
1690
Richard Smith180f4792011-11-10 06:34:14 +00001691/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1692/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1693/// for looking up the glvalue referred to by an entity of reference type.
1694///
1695/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001696/// \param Conv - The expression for which we are performing the conversion.
1697/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001698/// \param Type - The type we expect this conversion to produce, before
1699/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001700/// \param LVal - The glvalue on which we are attempting to perform this action.
1701/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001702static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1703 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001704 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001705 if (LVal.Designator.Invalid)
1706 // A diagnostic will have already been produced.
1707 return false;
1708
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001709 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001710
Richard Smithf48fdb02011-12-09 22:58:01 +00001711 if (!LVal.Base) {
1712 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001713 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001714 return false;
1715 }
1716
Richard Smith83587db2012-02-15 02:18:13 +00001717 CallStackFrame *Frame = 0;
1718 if (LVal.CallIndex) {
1719 Frame = Info.getCallFrame(LVal.CallIndex);
1720 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001721 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001722 NoteLValueLocation(Info, LVal.Base);
1723 return false;
1724 }
1725 }
1726
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1728 // is not a constant expression (even if the object is non-volatile). We also
1729 // apply this rule to C++98, in order to conform to the expected 'volatile'
1730 // semantics.
1731 if (Type.isVolatileQualified()) {
1732 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001733 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001734 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001737 }
Richard Smithc49bd112011-10-28 17:51:58 +00001738
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001739 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001740 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1741 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001742 // expressions are constant expressions too. Inside constexpr functions,
1743 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001744 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001745 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001746 if (VD) {
1747 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1748 VD = VDef;
1749 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001750 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001751 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001752 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001753 }
1754
Richard Smith7098cbd2011-12-21 05:04:46 +00001755 // DR1313: If the object is volatile-qualified but the glvalue was not,
1756 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001757 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001758 if (VT.isVolatileQualified()) {
1759 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001760 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001761 Info.Note(VD->getLocation(), diag::note_declared_at);
1762 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001763 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001764 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 return false;
1766 }
1767
1768 if (!isa<ParmVarDecl>(VD)) {
1769 if (VD->isConstexpr()) {
1770 // OK, we can read this variable.
1771 } else if (VT->isIntegralOrEnumerationType()) {
1772 if (!VT.isConstQualified()) {
1773 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001774 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001775 Info.Note(VD->getLocation(), diag::note_declared_at);
1776 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001777 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001778 }
1779 return false;
1780 }
1781 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1782 // We support folding of const floating-point types, in order to make
1783 // static const data members of such types (supported as an extension)
1784 // more useful.
1785 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001786 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001787 Info.Note(VD->getLocation(), diag::note_declared_at);
1788 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001789 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001790 }
1791 } else {
1792 // FIXME: Allow folding of values of any literal type in all languages.
1793 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001794 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001795 Info.Note(VD->getLocation(), diag::note_declared_at);
1796 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001797 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001798 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001799 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001800 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001801 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001802
Richard Smithf48fdb02011-12-09 22:58:01 +00001803 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001804 return false;
1805
Richard Smith47a1eed2011-10-29 20:57:55 +00001806 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001807 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001808
1809 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1810 // conversion. This happens when the declaration and the lvalue should be
1811 // considered synonymous, for instance when initializing an array of char
1812 // from a string literal. Continue as if the initializer lvalue was the
1813 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 assert(RVal.getLValueOffset().isZero() &&
1815 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001816 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001817
1818 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1819 Frame = Info.getCallFrame(CallIndex);
1820 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001821 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001822 NoteLValueLocation(Info, RVal.getLValueBase());
1823 return false;
1824 }
1825 } else {
1826 Frame = 0;
1827 }
Richard Smithc49bd112011-10-28 17:51:58 +00001828 }
1829
Richard Smith7098cbd2011-12-21 05:04:46 +00001830 // Volatile temporary objects cannot be read in constant expressions.
1831 if (Base->getType().isVolatileQualified()) {
1832 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001833 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001834 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1835 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001836 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001837 }
1838 return false;
1839 }
1840
Richard Smithcc5d4f62011-11-07 09:22:26 +00001841 if (Frame) {
1842 // If this is a temporary expression with a nontrivial initializer, grab the
1843 // value from the relevant stack frame.
1844 RVal = Frame->Temporaries[Base];
1845 } else if (const CompoundLiteralExpr *CLE
1846 = dyn_cast<CompoundLiteralExpr>(Base)) {
1847 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1848 // initializer until now for such expressions. Such an expression can't be
1849 // an ICE in C, so this only matters for fold.
1850 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1851 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1852 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001853 } else if (isa<StringLiteral>(Base)) {
1854 // We represent a string literal array as an lvalue pointing at the
1855 // corresponding expression, rather than building an array of chars.
1856 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001857 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001858 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001859 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001860 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001861 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001862
Richard Smithf48fdb02011-12-09 22:58:01 +00001863 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1864 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001865}
1866
Richard Smith59efe262011-11-11 04:05:33 +00001867/// Build an lvalue for the object argument of a member function call.
1868static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1869 LValue &This) {
1870 if (Object->getType()->isPointerType())
1871 return EvaluatePointer(Object, This, Info);
1872
1873 if (Object->isGLValue())
1874 return EvaluateLValue(Object, This, Info);
1875
Richard Smithe24f5fc2011-11-17 22:56:20 +00001876 if (Object->getType()->isLiteralType())
1877 return EvaluateTemporary(Object, This, Info);
1878
1879 return false;
1880}
1881
1882/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1883/// lvalue referring to the result.
1884///
1885/// \param Info - Information about the ongoing evaluation.
1886/// \param BO - The member pointer access operation.
1887/// \param LV - Filled in with a reference to the resulting object.
1888/// \param IncludeMember - Specifies whether the member itself is included in
1889/// the resulting LValue subobject designator. This is not possible when
1890/// creating a bound member function.
1891/// \return The field or method declaration to which the member pointer refers,
1892/// or 0 if evaluation fails.
1893static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1894 const BinaryOperator *BO,
1895 LValue &LV,
1896 bool IncludeMember = true) {
1897 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1898
Richard Smith745f5142012-01-27 01:14:48 +00001899 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1900 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001901 return 0;
1902
1903 MemberPtr MemPtr;
1904 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1905 return 0;
1906
1907 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1908 // member value, the behavior is undefined.
1909 if (!MemPtr.getDecl())
1910 return 0;
1911
Richard Smith745f5142012-01-27 01:14:48 +00001912 if (!EvalObjOK)
1913 return 0;
1914
Richard Smithe24f5fc2011-11-17 22:56:20 +00001915 if (MemPtr.isDerivedMember()) {
1916 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001917 // The end of the derived-to-base path for the base object must match the
1918 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001919 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001920 LV.Designator.Entries.size())
1921 return 0;
1922 unsigned PathLengthToMember =
1923 LV.Designator.Entries.size() - MemPtr.Path.size();
1924 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1925 const CXXRecordDecl *LVDecl = getAsBaseClass(
1926 LV.Designator.Entries[PathLengthToMember + I]);
1927 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1928 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1929 return 0;
1930 }
1931
1932 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001933 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1934 PathLengthToMember))
1935 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001936 } else if (!MemPtr.Path.empty()) {
1937 // Extend the LValue path with the member pointer's path.
1938 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1939 MemPtr.Path.size() + IncludeMember);
1940
1941 // Walk down to the appropriate base class.
1942 QualType LVType = BO->getLHS()->getType();
1943 if (const PointerType *PT = LVType->getAs<PointerType>())
1944 LVType = PT->getPointeeType();
1945 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1946 assert(RD && "member pointer access on non-class-type expression");
1947 // The first class in the path is that of the lvalue.
1948 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1949 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001950 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001951 RD = Base;
1952 }
1953 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001954 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 }
1956
1957 // Add the member. Note that we cannot build bound member functions here.
1958 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001959 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1960 HandleLValueMember(Info, BO, LV, FD);
1961 else if (const IndirectFieldDecl *IFD =
1962 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1963 HandleLValueIndirectMember(Info, BO, LV, IFD);
1964 else
1965 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001966 }
1967
1968 return MemPtr.getDecl();
1969}
1970
1971/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1972/// the provided lvalue, which currently refers to the base object.
1973static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1974 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001976 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001977 return false;
1978
Richard Smithb4e85ed2012-01-06 16:39:00 +00001979 QualType TargetQT = E->getType();
1980 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1981 TargetQT = PT->getPointeeType();
1982
1983 // Check this cast lands within the final derived-to-base subobject path.
1984 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001985 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001986 << D.MostDerivedType << TargetQT;
1987 return false;
1988 }
1989
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 // Check the type of the final cast. We don't need to check the path,
1991 // since a cast can only be formed if the path is unique.
1992 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1994 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001995 if (NewEntriesSize == D.MostDerivedPathLength)
1996 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1997 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001998 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002000 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002001 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002004
2005 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002007}
2008
Mike Stumpc4c90452009-10-27 22:09:17 +00002009namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002010enum EvalStmtResult {
2011 /// Evaluation failed.
2012 ESR_Failed,
2013 /// Hit a 'return' statement.
2014 ESR_Returned,
2015 /// Evaluation succeeded.
2016 ESR_Succeeded
2017};
2018}
2019
2020// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002021static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002022 const Stmt *S) {
2023 switch (S->getStmtClass()) {
2024 default:
2025 return ESR_Failed;
2026
2027 case Stmt::NullStmtClass:
2028 case Stmt::DeclStmtClass:
2029 return ESR_Succeeded;
2030
Richard Smithc1c5f272011-12-13 06:39:58 +00002031 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002032 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002033 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002034 return ESR_Failed;
2035 return ESR_Returned;
2036 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002037
2038 case Stmt::CompoundStmtClass: {
2039 const CompoundStmt *CS = cast<CompoundStmt>(S);
2040 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2041 BE = CS->body_end(); BI != BE; ++BI) {
2042 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2043 if (ESR != ESR_Succeeded)
2044 return ESR;
2045 }
2046 return ESR_Succeeded;
2047 }
2048 }
2049}
2050
Richard Smith61802452011-12-22 02:22:31 +00002051/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2052/// default constructor. If so, we'll fold it whether or not it's marked as
2053/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2054/// so we need special handling.
2055static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002056 const CXXConstructorDecl *CD,
2057 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002058 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2059 return false;
2060
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002061 // Value-initialization does not call a trivial default constructor, so such a
2062 // call is a core constant expression whether or not the constructor is
2063 // constexpr.
2064 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002065 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002066 // FIXME: If DiagDecl is an implicitly-declared special member function,
2067 // we should be much more explicit about why it's not constexpr.
2068 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2069 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2070 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002071 } else {
2072 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2073 }
2074 }
2075 return true;
2076}
2077
Richard Smithc1c5f272011-12-13 06:39:58 +00002078/// CheckConstexprFunction - Check that a function can be called in a constant
2079/// expression.
2080static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2081 const FunctionDecl *Declaration,
2082 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002083 // Potential constant expressions can contain calls to declared, but not yet
2084 // defined, constexpr functions.
2085 if (Info.CheckingPotentialConstantExpression && !Definition &&
2086 Declaration->isConstexpr())
2087 return false;
2088
Richard Smithc1c5f272011-12-13 06:39:58 +00002089 // Can we evaluate this function call?
2090 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2091 return true;
2092
2093 if (Info.getLangOpts().CPlusPlus0x) {
2094 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002095 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2096 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002097 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2098 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2099 << DiagDecl;
2100 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2101 } else {
2102 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2103 }
2104 return false;
2105}
2106
Richard Smith180f4792011-11-10 06:34:14 +00002107namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002108typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002109}
2110
2111/// EvaluateArgs - Evaluate the arguments to a function call.
2112static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2113 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002114 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002115 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002116 I != E; ++I) {
2117 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2118 // If we're checking for a potential constant expression, evaluate all
2119 // initializers even if some of them fail.
2120 if (!Info.keepEvaluatingAfterFailure())
2121 return false;
2122 Success = false;
2123 }
2124 }
2125 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002126}
2127
Richard Smithd0dccea2011-10-28 22:34:42 +00002128/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002129static bool HandleFunctionCall(SourceLocation CallLoc,
2130 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002131 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002132 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002133 ArgVector ArgValues(Args.size());
2134 if (!EvaluateArgs(Args, ArgValues, Info))
2135 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002136
Richard Smith745f5142012-01-27 01:14:48 +00002137 if (!Info.CheckCallLimit(CallLoc))
2138 return false;
2139
2140 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002141 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2142}
2143
Richard Smith180f4792011-11-10 06:34:14 +00002144/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002145static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002146 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002147 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002148 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002149 ArgVector ArgValues(Args.size());
2150 if (!EvaluateArgs(Args, ArgValues, Info))
2151 return false;
2152
Richard Smith745f5142012-01-27 01:14:48 +00002153 if (!Info.CheckCallLimit(CallLoc))
2154 return false;
2155
Richard Smith86c3ae42012-02-13 03:54:03 +00002156 const CXXRecordDecl *RD = Definition->getParent();
2157 if (RD->getNumVBases()) {
2158 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2159 return false;
2160 }
2161
Richard Smith745f5142012-01-27 01:14:48 +00002162 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002163
2164 // If it's a delegating constructor, just delegate.
2165 if (Definition->isDelegatingConstructor()) {
2166 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002167 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002168 }
2169
Richard Smith610a60c2012-01-10 04:32:03 +00002170 // For a trivial copy or move constructor, perform an APValue copy. This is
2171 // essential for unions, where the operations performed by the constructor
2172 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002173 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002174 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2175 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002176 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002177 RHS.setFrom(Info.Ctx, ArgValues[0]);
2178 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2179 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002180 }
2181
2182 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002183 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002184 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2185 std::distance(RD->field_begin(), RD->field_end()));
2186
2187 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2188
Richard Smith745f5142012-01-27 01:14:48 +00002189 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002190 unsigned BasesSeen = 0;
2191#ifndef NDEBUG
2192 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2193#endif
2194 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2195 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002196 LValue Subobject = This;
2197 APValue *Value = &Result;
2198
2199 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002200 if ((*I)->isBaseInitializer()) {
2201 QualType BaseType((*I)->getBaseClass(), 0);
2202#ifndef NDEBUG
2203 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002204 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002205 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2206 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2207 "base class initializers not in expected order");
2208 ++BaseIt;
2209#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002210 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002211 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002212 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002213 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002214 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002215 if (RD->isUnion()) {
2216 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002217 Value = &Result.getUnionValue();
2218 } else {
2219 Value = &Result.getStructField(FD->getFieldIndex());
2220 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002221 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002222 // Walk the indirect field decl's chain to find the object to initialize,
2223 // and make sure we've initialized every step along it.
2224 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2225 CE = IFD->chain_end();
2226 C != CE; ++C) {
2227 FieldDecl *FD = cast<FieldDecl>(*C);
2228 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2229 // Switch the union field if it differs. This happens if we had
2230 // preceding zero-initialization, and we're now initializing a union
2231 // subobject other than the first.
2232 // FIXME: In this case, the values of the other subobjects are
2233 // specified, since zero-initialization sets all padding bits to zero.
2234 if (Value->isUninit() ||
2235 (Value->isUnion() && Value->getUnionField() != FD)) {
2236 if (CD->isUnion())
2237 *Value = APValue(FD);
2238 else
2239 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2240 std::distance(CD->field_begin(), CD->field_end()));
2241 }
Richard Smith745f5142012-01-27 01:14:48 +00002242 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 if (CD->isUnion())
2244 Value = &Value->getUnionValue();
2245 else
2246 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 }
Richard Smith180f4792011-11-10 06:34:14 +00002248 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002249 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002250 }
Richard Smith745f5142012-01-27 01:14:48 +00002251
Richard Smith83587db2012-02-15 02:18:13 +00002252 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2253 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002254 ? CCEK_Constant : CCEK_MemberInit)) {
2255 // If we're checking for a potential constant expression, evaluate all
2256 // initializers even if some of them fail.
2257 if (!Info.keepEvaluatingAfterFailure())
2258 return false;
2259 Success = false;
2260 }
Richard Smith180f4792011-11-10 06:34:14 +00002261 }
2262
Richard Smith745f5142012-01-27 01:14:48 +00002263 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002264}
2265
Richard Smithd0dccea2011-10-28 22:34:42 +00002266namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002267class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002268 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002269 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002270public:
2271
Richard Smith1e12c592011-10-16 21:26:27 +00002272 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002273
2274 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002275 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002276 return true;
2277 }
2278
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002279 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2280 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002281 return Visit(E->getResultExpr());
2282 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002284 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002285 return true;
2286 return false;
2287 }
John McCallf85e1932011-06-15 23:02:42 +00002288 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002289 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002290 return true;
2291 return false;
2292 }
John McCallf85e1932011-06-15 23:02:42 +00002293
Mike Stumpc4c90452009-10-27 22:09:17 +00002294 // We don't want to evaluate BlockExprs multiple times, as they generate
2295 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002296 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2297 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2298 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002299 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2301 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2302 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2303 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2304 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2305 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002306 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *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 VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002310 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2312 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2313 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2314 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002315 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002316 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2317 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2318 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2319 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2320 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002321 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002322 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002323 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002324 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002325 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002326
2327 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002329 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2330 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002332 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002333 return false;
2334 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002335
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002336 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002337};
2338
John McCall56ca35d2011-02-17 10:25:35 +00002339class OpaqueValueEvaluation {
2340 EvalInfo &info;
2341 OpaqueValueExpr *opaqueValue;
2342
2343public:
2344 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2345 Expr *value)
2346 : info(info), opaqueValue(opaqueValue) {
2347
2348 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002349 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002350 this->opaqueValue = 0;
2351 return;
2352 }
John McCall56ca35d2011-02-17 10:25:35 +00002353 }
2354
2355 bool hasError() const { return opaqueValue == 0; }
2356
2357 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002358 // FIXME: For a recursive constexpr call, an outer stack frame might have
2359 // been using this opaque value too, and will now have to re-evaluate the
2360 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2362 }
2363};
2364
Mike Stumpc4c90452009-10-27 22:09:17 +00002365} // end anonymous namespace
2366
Eli Friedman4efaa272008-11-12 09:44:48 +00002367//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002368// Generic Evaluation
2369//===----------------------------------------------------------------------===//
2370namespace {
2371
Richard Smithf48fdb02011-12-09 22:58:01 +00002372// FIXME: RetTy is always bool. Remove it.
2373template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002374class ExprEvaluatorBase
2375 : public ConstStmtVisitor<Derived, RetTy> {
2376private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002377 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002378 return static_cast<Derived*>(this)->Success(V, E);
2379 }
Richard Smith51201882011-12-30 21:15:51 +00002380 RetTy DerivedZeroInitialization(const Expr *E) {
2381 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002382 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002383
Richard Smith74e1ad92012-02-16 02:46:34 +00002384 // Check whether a conditional operator with a non-constant condition is a
2385 // potential constant expression. If neither arm is a potential constant
2386 // expression, then the conditional operator is not either.
2387 template<typename ConditionalOperator>
2388 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2389 assert(Info.CheckingPotentialConstantExpression);
2390
2391 // Speculatively evaluate both arms.
2392 {
2393 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2394 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2395
2396 StmtVisitorTy::Visit(E->getFalseExpr());
2397 if (Diag.empty())
2398 return;
2399
2400 Diag.clear();
2401 StmtVisitorTy::Visit(E->getTrueExpr());
2402 if (Diag.empty())
2403 return;
2404 }
2405
2406 Error(E, diag::note_constexpr_conditional_never_const);
2407 }
2408
2409
2410 template<typename ConditionalOperator>
2411 bool HandleConditionalOperator(const ConditionalOperator *E) {
2412 bool BoolResult;
2413 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2414 if (Info.CheckingPotentialConstantExpression)
2415 CheckPotentialConstantConditional(E);
2416 return false;
2417 }
2418
2419 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2420 return StmtVisitorTy::Visit(EvalExpr);
2421 }
2422
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002423protected:
2424 EvalInfo &Info;
2425 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2426 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2427
Richard Smithdd1f29b2011-12-12 09:28:41 +00002428 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002429 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002430 }
2431
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002432 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2433
2434public:
2435 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2436
2437 EvalInfo &getEvalInfo() { return Info; }
2438
Richard Smithf48fdb02011-12-09 22:58:01 +00002439 /// Report an evaluation error. This should only be called when an error is
2440 /// first discovered. When propagating an error, just return false.
2441 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002442 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002443 return false;
2444 }
2445 bool Error(const Expr *E) {
2446 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2447 }
2448
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002449 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002450 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002451 }
2452 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002453 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002454 }
2455
2456 RetTy VisitParenExpr(const ParenExpr *E)
2457 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2458 RetTy VisitUnaryExtension(const UnaryOperator *E)
2459 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2460 RetTy VisitUnaryPlus(const UnaryOperator *E)
2461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2462 RetTy VisitChooseExpr(const ChooseExpr *E)
2463 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2464 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2465 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002466 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2467 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002468 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2469 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002470 // We cannot create any objects for which cleanups are required, so there is
2471 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2472 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2473 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002474
Richard Smithc216a012011-12-12 12:46:16 +00002475 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2477 return static_cast<Derived*>(this)->VisitCastExpr(E);
2478 }
2479 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2480 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2481 return static_cast<Derived*>(this)->VisitCastExpr(E);
2482 }
2483
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2485 switch (E->getOpcode()) {
2486 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002487 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488
2489 case BO_Comma:
2490 VisitIgnoredValue(E->getLHS());
2491 return StmtVisitorTy::Visit(E->getRHS());
2492
2493 case BO_PtrMemD:
2494 case BO_PtrMemI: {
2495 LValue Obj;
2496 if (!HandleMemberPointerAccess(Info, E, Obj))
2497 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002498 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002499 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 return false;
2501 return DerivedSuccess(Result, E);
2502 }
2503 }
2504 }
2505
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002506 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002507 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2509 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002510 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002511
Richard Smith74e1ad92012-02-16 02:46:34 +00002512 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 }
2514
2515 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002516 bool IsBcpCall = false;
2517 // If the condition (ignoring parens) is a __builtin_constant_p call,
2518 // the result is a constant expression if it can be folded without
2519 // side-effects. This is an important GNU extension. See GCC PR38377
2520 // for discussion.
2521 if (const CallExpr *CallCE =
2522 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2523 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2524 IsBcpCall = true;
2525
2526 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2527 // constant expression; we can't check whether it's potentially foldable.
2528 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2529 return false;
2530
2531 FoldConstant Fold(Info);
2532
Richard Smith74e1ad92012-02-16 02:46:34 +00002533 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002534 return false;
2535
2536 if (IsBcpCall)
2537 Fold.Fold(Info);
2538
2539 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002540 }
2541
2542 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002543 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002544 if (!Value) {
2545 const Expr *Source = E->getSourceExpr();
2546 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002547 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002548 if (Source == E) { // sanity checking.
2549 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002551 }
2552 return StmtVisitorTy::Visit(Source);
2553 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002554 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002555 }
Richard Smithf10d9172011-10-11 21:43:33 +00002556
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002558 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002559 QualType CalleeType = Callee->getType();
2560
Richard Smithd0dccea2011-10-28 22:34:42 +00002561 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002562 LValue *This = 0, ThisVal;
2563 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002564 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002565
Richard Smith59efe262011-11-11 04:05:33 +00002566 // Extract function decl and 'this' pointer from the callee.
2567 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002569 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2570 // Explicit bound member calls, such as x.f() or p->g();
2571 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return false;
2573 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002575 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2577 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2579 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002581 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002582 return Error(Callee);
2583
2584 FD = dyn_cast<FunctionDecl>(Member);
2585 if (!FD)
2586 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002587 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002588 LValue Call;
2589 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002590 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002591
Richard Smithb4e85ed2012-01-06 16:39:00 +00002592 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002594 FD = dyn_cast_or_null<FunctionDecl>(
2595 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002596 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002598
2599 // Overloaded operator calls to member functions are represented as normal
2600 // calls with '*this' as the first argument.
2601 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2602 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002603 // FIXME: When selecting an implicit conversion for an overloaded
2604 // operator delete, we sometimes try to evaluate calls to conversion
2605 // operators without a 'this' parameter!
2606 if (Args.empty())
2607 return Error(E);
2608
Richard Smith59efe262011-11-11 04:05:33 +00002609 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2610 return false;
2611 This = &ThisVal;
2612 Args = Args.slice(1);
2613 }
2614
2615 // Don't call function pointers which have been cast to some other type.
2616 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002618 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002619 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002620
Richard Smithb04035a2012-02-01 02:39:43 +00002621 if (This && !This->checkSubobject(Info, E, CSK_This))
2622 return false;
2623
Richard Smith86c3ae42012-02-13 03:54:03 +00002624 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2625 // calls to such functions in constant expressions.
2626 if (This && !HasQualifier &&
2627 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2628 return Error(E, diag::note_constexpr_virtual_call);
2629
Richard Smithc1c5f272011-12-13 06:39:58 +00002630 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002631 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002632 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002633
Richard Smithc1c5f272011-12-13 06:39:58 +00002634 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002635 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2636 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002637 return false;
2638
Richard Smith83587db2012-02-15 02:18:13 +00002639 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002640 }
2641
Richard Smithc49bd112011-10-28 17:51:58 +00002642 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2643 return StmtVisitorTy::Visit(E->getInitializer());
2644 }
Richard Smithf10d9172011-10-11 21:43:33 +00002645 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002646 if (E->getNumInits() == 0)
2647 return DerivedZeroInitialization(E);
2648 if (E->getNumInits() == 1)
2649 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002650 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002651 }
2652 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002653 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002654 }
2655 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002656 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002657 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002658 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002659 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002660 }
Richard Smithf10d9172011-10-11 21:43:33 +00002661
Richard Smith180f4792011-11-10 06:34:14 +00002662 /// A member expression where the object is a prvalue is itself a prvalue.
2663 RetTy VisitMemberExpr(const MemberExpr *E) {
2664 assert(!E->isArrow() && "missing call to bound member function?");
2665
Richard Smith1aa0be82012-03-03 22:46:17 +00002666 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002667 if (!Evaluate(Val, Info, E->getBase()))
2668 return false;
2669
2670 QualType BaseTy = E->getBase()->getType();
2671
2672 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002673 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002674 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2675 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2676 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2677
Richard Smithb4e85ed2012-01-06 16:39:00 +00002678 SubobjectDesignator Designator(BaseTy);
2679 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002680
Richard Smithf48fdb02011-12-09 22:58:01 +00002681 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002682 DerivedSuccess(Val, E);
2683 }
2684
Richard Smithc49bd112011-10-28 17:51:58 +00002685 RetTy VisitCastExpr(const CastExpr *E) {
2686 switch (E->getCastKind()) {
2687 default:
2688 break;
2689
David Chisnall7a7ee302012-01-16 17:27:18 +00002690 case CK_AtomicToNonAtomic:
2691 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002692 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002693 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002694 return StmtVisitorTy::Visit(E->getSubExpr());
2695
2696 case CK_LValueToRValue: {
2697 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002698 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2699 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002700 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002701 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2702 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2703 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002704 return false;
2705 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002706 }
2707 }
2708
Richard Smithf48fdb02011-12-09 22:58:01 +00002709 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002710 }
2711
Richard Smith8327fad2011-10-24 18:44:57 +00002712 /// Visit a value which is evaluated, but whose value is ignored.
2713 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002714 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002715 if (!Evaluate(Scratch, Info, E))
2716 Info.EvalStatus.HasSideEffects = true;
2717 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002718};
2719
2720}
2721
2722//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002723// Common base class for lvalue and temporary evaluation.
2724//===----------------------------------------------------------------------===//
2725namespace {
2726template<class Derived>
2727class LValueExprEvaluatorBase
2728 : public ExprEvaluatorBase<Derived, bool> {
2729protected:
2730 LValue &Result;
2731 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2732 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2733
2734 bool Success(APValue::LValueBase B) {
2735 Result.set(B);
2736 return true;
2737 }
2738
2739public:
2740 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2741 ExprEvaluatorBaseTy(Info), Result(Result) {}
2742
Richard Smith1aa0be82012-03-03 22:46:17 +00002743 bool Success(const APValue &V, const Expr *E) {
2744 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002745 return true;
2746 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 bool VisitMemberExpr(const MemberExpr *E) {
2749 // Handle non-static data members.
2750 QualType BaseTy;
2751 if (E->isArrow()) {
2752 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2753 return false;
2754 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002755 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002756 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002757 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2758 return false;
2759 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002760 } else {
2761 if (!this->Visit(E->getBase()))
2762 return false;
2763 BaseTy = E->getBase()->getType();
2764 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002765
Richard Smithd9b02e72012-01-25 22:15:11 +00002766 const ValueDecl *MD = E->getMemberDecl();
2767 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2768 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2769 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2770 (void)BaseTy;
2771 HandleLValueMember(this->Info, E, Result, FD);
2772 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2773 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2774 } else
2775 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776
Richard Smithd9b02e72012-01-25 22:15:11 +00002777 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002778 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002779 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 RefValue))
2781 return false;
2782 return Success(RefValue, E);
2783 }
2784 return true;
2785 }
2786
2787 bool VisitBinaryOperator(const BinaryOperator *E) {
2788 switch (E->getOpcode()) {
2789 default:
2790 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2791
2792 case BO_PtrMemD:
2793 case BO_PtrMemI:
2794 return HandleMemberPointerAccess(this->Info, E, Result);
2795 }
2796 }
2797
2798 bool VisitCastExpr(const CastExpr *E) {
2799 switch (E->getCastKind()) {
2800 default:
2801 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2802
2803 case CK_DerivedToBase:
2804 case CK_UncheckedDerivedToBase: {
2805 if (!this->Visit(E->getSubExpr()))
2806 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807
2808 // Now figure out the necessary offset to add to the base LV to get from
2809 // the derived class to the base class.
2810 QualType Type = E->getSubExpr()->getType();
2811
2812 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2813 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002814 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002815 *PathI))
2816 return false;
2817 Type = (*PathI)->getType();
2818 }
2819
2820 return true;
2821 }
2822 }
2823 }
2824};
2825}
2826
2827//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002828// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002829//
2830// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2831// function designators (in C), decl references to void objects (in C), and
2832// temporaries (if building with -Wno-address-of-temporary).
2833//
2834// LValue evaluation produces values comprising a base expression of one of the
2835// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002836// - Declarations
2837// * VarDecl
2838// * FunctionDecl
2839// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002840// * CompoundLiteralExpr in C
2841// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002842// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002843// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002844// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002845// * ObjCEncodeExpr
2846// * AddrLabelExpr
2847// * BlockExpr
2848// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002849// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002850// * Any Expr, with a CallIndex indicating the function in which the temporary
2851// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002852// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002853//===----------------------------------------------------------------------===//
2854namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002855class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002856 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002857public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002858 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2859 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Richard Smithc49bd112011-10-28 17:51:58 +00002861 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2862
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002863 bool VisitDeclRefExpr(const DeclRefExpr *E);
2864 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002865 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002866 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2867 bool VisitMemberExpr(const MemberExpr *E);
2868 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2869 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002870 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002871 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2872 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002873 bool VisitUnaryReal(const UnaryOperator *E);
2874 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002875
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002876 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002877 switch (E->getCastKind()) {
2878 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002879 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002880
Eli Friedmandb924222011-10-11 00:13:24 +00002881 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002882 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002883 if (!Visit(E->getSubExpr()))
2884 return false;
2885 Result.Designator.setInvalid();
2886 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002887
Richard Smithe24f5fc2011-11-17 22:56:20 +00002888 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002889 if (!Visit(E->getSubExpr()))
2890 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002891 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002892 }
2893 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002894};
2895} // end anonymous namespace
2896
Richard Smithc49bd112011-10-28 17:51:58 +00002897/// Evaluate an expression as an lvalue. This can be legitimately called on
2898/// expressions which are not glvalues, in a few cases:
2899/// * function designators in C,
2900/// * "extern void" objects,
2901/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002902static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002903 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2904 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2905 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002906 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002907}
2908
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002909bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002910 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2911 return Success(FD);
2912 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002913 return VisitVarDecl(E, VD);
2914 return Error(E);
2915}
Richard Smith436c8892011-10-24 23:14:33 +00002916
Richard Smithc49bd112011-10-28 17:51:58 +00002917bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002918 if (!VD->getType()->isReferenceType()) {
2919 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002920 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002921 return true;
2922 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002923 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002924 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002925
Richard Smith1aa0be82012-03-03 22:46:17 +00002926 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002927 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2928 return false;
2929 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002930}
2931
Richard Smithbd552ef2011-10-31 05:52:43 +00002932bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2933 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002934 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002935 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002936 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2937
Richard Smith83587db2012-02-15 02:18:13 +00002938 Result.set(E, Info.CurrentCall->Index);
2939 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2940 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002941 }
2942
2943 // Materialization of an lvalue temporary occurs when we need to force a copy
2944 // (for instance, if it's a bitfield).
2945 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2946 if (!Visit(E->GetTemporaryExpr()))
2947 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002948 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002949 Info.CurrentCall->Temporaries[E]))
2950 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002951 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002952 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002953}
2954
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002955bool
2956LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002957 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2958 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2959 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002960 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002961}
2962
Richard Smith47d21452011-12-27 12:18:28 +00002963bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2964 if (E->isTypeOperand())
2965 return Success(E);
2966 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2967 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002968 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002969 << E->getExprOperand()->getType()
2970 << E->getExprOperand()->getSourceRange();
2971 return false;
2972 }
2973 return Success(E);
2974}
2975
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002976bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002977 // Handle static data members.
2978 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2979 VisitIgnoredValue(E->getBase());
2980 return VisitVarDecl(E, VD);
2981 }
2982
Richard Smithd0dccea2011-10-28 22:34:42 +00002983 // Handle static member functions.
2984 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2985 if (MD->isStatic()) {
2986 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002987 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002988 }
2989 }
2990
Richard Smith180f4792011-11-10 06:34:14 +00002991 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002992 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002993}
2994
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002995bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002996 // FIXME: Deal with vectors as array subscript bases.
2997 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002998 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002999
Anders Carlsson3068d112008-11-16 19:01:22 +00003000 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003001 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Anders Carlsson3068d112008-11-16 19:01:22 +00003003 APSInt Index;
3004 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003005 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003006 int64_t IndexValue
3007 = Index.isSigned() ? Index.getSExtValue()
3008 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003009
Richard Smithb4e85ed2012-01-06 16:39:00 +00003010 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003011}
Eli Friedman4efaa272008-11-12 09:44:48 +00003012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003013bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003014 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003015}
3016
Richard Smith86024012012-02-18 22:04:06 +00003017bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3018 if (!Visit(E->getSubExpr()))
3019 return false;
3020 // __real is a no-op on scalar lvalues.
3021 if (E->getSubExpr()->getType()->isAnyComplexType())
3022 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3023 return true;
3024}
3025
3026bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3027 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3028 "lvalue __imag__ on scalar?");
3029 if (!Visit(E->getSubExpr()))
3030 return false;
3031 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3032 return true;
3033}
3034
Eli Friedman4efaa272008-11-12 09:44:48 +00003035//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003036// Pointer Evaluation
3037//===----------------------------------------------------------------------===//
3038
Anders Carlssonc754aa62008-07-08 05:13:58 +00003039namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003040class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003041 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003042 LValue &Result;
3043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003045 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003046 return true;
3047 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003048public:
Mike Stump1eb44332009-09-09 15:08:12 +00003049
John McCallefdb83e2010-05-07 21:00:08 +00003050 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052
Richard Smith1aa0be82012-03-03 22:46:17 +00003053 bool Success(const APValue &V, const Expr *E) {
3054 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003055 return true;
3056 }
Richard Smith51201882011-12-30 21:15:51 +00003057 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003058 return Success((Expr*)0);
3059 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003060
John McCallefdb83e2010-05-07 21:00:08 +00003061 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003062 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003063 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003064 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003065 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003066 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3067 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003068 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003069 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003070 bool VisitCallExpr(const CallExpr *E);
3071 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003072 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003073 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003074 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003075 }
Richard Smith180f4792011-11-10 06:34:14 +00003076 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3077 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003078 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003079 Result = *Info.CurrentCall->This;
3080 return true;
3081 }
John McCall56ca35d2011-02-17 10:25:35 +00003082
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003083 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003084};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003085} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003086
John McCallefdb83e2010-05-07 21:00:08 +00003087static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003088 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003089 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003090}
3091
John McCallefdb83e2010-05-07 21:00:08 +00003092bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003093 if (E->getOpcode() != BO_Add &&
3094 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003095 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003096
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003097 const Expr *PExp = E->getLHS();
3098 const Expr *IExp = E->getRHS();
3099 if (IExp->getType()->isPointerType())
3100 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Richard Smith745f5142012-01-27 01:14:48 +00003102 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3103 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003104 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003105
John McCallefdb83e2010-05-07 21:00:08 +00003106 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003107 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003108 return false;
3109 int64_t AdditionalOffset
3110 = Offset.isSigned() ? Offset.getSExtValue()
3111 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003112 if (E->getOpcode() == BO_Sub)
3113 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003114
Richard Smith180f4792011-11-10 06:34:14 +00003115 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003116 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3117 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003118}
Eli Friedman4efaa272008-11-12 09:44:48 +00003119
John McCallefdb83e2010-05-07 21:00:08 +00003120bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3121 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003122}
Mike Stump1eb44332009-09-09 15:08:12 +00003123
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003124bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3125 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003126
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003127 switch (E->getCastKind()) {
3128 default:
3129 break;
3130
John McCall2de56d12010-08-25 11:45:40 +00003131 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003132 case CK_CPointerToObjCPointerCast:
3133 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003134 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003135 if (!Visit(SubExpr))
3136 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003137 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3138 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3139 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003140 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003141 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003142 if (SubExpr->getType()->isVoidPointerType())
3143 CCEDiag(E, diag::note_constexpr_invalid_cast)
3144 << 3 << SubExpr->getType();
3145 else
3146 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3147 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003148 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003149
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003150 case CK_DerivedToBase:
3151 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003152 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003153 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003154 if (!Result.Base && Result.Offset.isZero())
3155 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003156
Richard Smith180f4792011-11-10 06:34:14 +00003157 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003159 QualType Type =
3160 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003161
Richard Smith180f4792011-11-10 06:34:14 +00003162 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003163 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003164 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3165 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003167 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003168 }
3169
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003170 return true;
3171 }
3172
Richard Smithe24f5fc2011-11-17 22:56:20 +00003173 case CK_BaseToDerived:
3174 if (!Visit(E->getSubExpr()))
3175 return false;
3176 if (!Result.Base && Result.Offset.isZero())
3177 return true;
3178 return HandleBaseToDerivedCast(Info, E, Result);
3179
Richard Smith47a1eed2011-10-29 20:57:55 +00003180 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003181 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003182
John McCall2de56d12010-08-25 11:45:40 +00003183 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003184 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3185
Richard Smith1aa0be82012-03-03 22:46:17 +00003186 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003187 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003188 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003189
John McCallefdb83e2010-05-07 21:00:08 +00003190 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003191 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3192 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003193 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003194 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003195 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003196 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003197 return true;
3198 } else {
3199 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003200 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003201 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003202 }
3203 }
John McCall2de56d12010-08-25 11:45:40 +00003204 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003205 if (SubExpr->isGLValue()) {
3206 if (!EvaluateLValue(SubExpr, Result, Info))
3207 return false;
3208 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003209 Result.set(SubExpr, Info.CurrentCall->Index);
3210 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3211 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003212 return false;
3213 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003214 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003215 if (const ConstantArrayType *CAT
3216 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3217 Result.addArray(Info, E, CAT);
3218 else
3219 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003220 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003221
John McCall2de56d12010-08-25 11:45:40 +00003222 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003223 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003224 }
3225
Richard Smithc49bd112011-10-28 17:51:58 +00003226 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003227}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003229bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003230 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003231 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003232
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003233 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003234}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003235
3236//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003237// Member Pointer Evaluation
3238//===----------------------------------------------------------------------===//
3239
3240namespace {
3241class MemberPointerExprEvaluator
3242 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3243 MemberPtr &Result;
3244
3245 bool Success(const ValueDecl *D) {
3246 Result = MemberPtr(D);
3247 return true;
3248 }
3249public:
3250
3251 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3252 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3253
Richard Smith1aa0be82012-03-03 22:46:17 +00003254 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003255 Result.setFrom(V);
3256 return true;
3257 }
Richard Smith51201882011-12-30 21:15:51 +00003258 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003259 return Success((const ValueDecl*)0);
3260 }
3261
3262 bool VisitCastExpr(const CastExpr *E);
3263 bool VisitUnaryAddrOf(const UnaryOperator *E);
3264};
3265} // end anonymous namespace
3266
3267static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3268 EvalInfo &Info) {
3269 assert(E->isRValue() && E->getType()->isMemberPointerType());
3270 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3271}
3272
3273bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3274 switch (E->getCastKind()) {
3275 default:
3276 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3277
3278 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003279 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003280
3281 case CK_BaseToDerivedMemberPointer: {
3282 if (!Visit(E->getSubExpr()))
3283 return false;
3284 if (E->path_empty())
3285 return true;
3286 // Base-to-derived member pointer casts store the path in derived-to-base
3287 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3288 // the wrong end of the derived->base arc, so stagger the path by one class.
3289 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3290 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3291 PathI != PathE; ++PathI) {
3292 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3293 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3294 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003295 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003296 }
3297 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3298 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003299 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003300 return true;
3301 }
3302
3303 case CK_DerivedToBaseMemberPointer:
3304 if (!Visit(E->getSubExpr()))
3305 return false;
3306 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3307 PathE = E->path_end(); PathI != PathE; ++PathI) {
3308 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3309 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3310 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003311 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003312 }
3313 return true;
3314 }
3315}
3316
3317bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3318 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3319 // member can be formed.
3320 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3321}
3322
3323//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003324// Record Evaluation
3325//===----------------------------------------------------------------------===//
3326
3327namespace {
3328 class RecordExprEvaluator
3329 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3330 const LValue &This;
3331 APValue &Result;
3332 public:
3333
3334 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3335 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3336
Richard Smith1aa0be82012-03-03 22:46:17 +00003337 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003338 Result = V;
3339 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003340 }
Richard Smith51201882011-12-30 21:15:51 +00003341 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003342
Richard Smith59efe262011-11-11 04:05:33 +00003343 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003344 bool VisitInitListExpr(const InitListExpr *E);
3345 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3346 };
3347}
3348
Richard Smith51201882011-12-30 21:15:51 +00003349/// Perform zero-initialization on an object of non-union class type.
3350/// C++11 [dcl.init]p5:
3351/// To zero-initialize an object or reference of type T means:
3352/// [...]
3353/// -- if T is a (possibly cv-qualified) non-union class type,
3354/// each non-static data member and each base-class subobject is
3355/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003356static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3357 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003358 const LValue &This, APValue &Result) {
3359 assert(!RD->isUnion() && "Expected non-union class type");
3360 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3361 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3362 std::distance(RD->field_begin(), RD->field_end()));
3363
3364 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3365
3366 if (CD) {
3367 unsigned Index = 0;
3368 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003369 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003370 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3371 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003372 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3373 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003374 Result.getStructBase(Index)))
3375 return false;
3376 }
3377 }
3378
Richard Smithb4e85ed2012-01-06 16:39:00 +00003379 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3380 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003381 // -- if T is a reference type, no initialization is performed.
3382 if ((*I)->getType()->isReferenceType())
3383 continue;
3384
3385 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003386 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003387
3388 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003389 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003390 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3391 return false;
3392 }
3393
3394 return true;
3395}
3396
3397bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3398 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3399 if (RD->isUnion()) {
3400 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3401 // object's first non-static named data member is zero-initialized
3402 RecordDecl::field_iterator I = RD->field_begin();
3403 if (I == RD->field_end()) {
3404 Result = APValue((const FieldDecl*)0);
3405 return true;
3406 }
3407
3408 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003409 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003410 Result = APValue(*I);
3411 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003412 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003413 }
3414
Richard Smithce582fe2012-02-17 00:44:16 +00003415 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003416 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003417 return false;
3418 }
3419
Richard Smithb4e85ed2012-01-06 16:39:00 +00003420 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003421}
3422
Richard Smith59efe262011-11-11 04:05:33 +00003423bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3424 switch (E->getCastKind()) {
3425 default:
3426 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3427
3428 case CK_ConstructorConversion:
3429 return Visit(E->getSubExpr());
3430
3431 case CK_DerivedToBase:
3432 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003433 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003434 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003436 if (!DerivedObject.isStruct())
3437 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003438
3439 // Derived-to-base rvalue conversion: just slice off the derived part.
3440 APValue *Value = &DerivedObject;
3441 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3442 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3443 PathE = E->path_end(); PathI != PathE; ++PathI) {
3444 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3445 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3446 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3447 RD = Base;
3448 }
3449 Result = *Value;
3450 return true;
3451 }
3452 }
3453}
3454
Richard Smith180f4792011-11-10 06:34:14 +00003455bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003456 // Cannot constant-evaluate std::initializer_list inits.
3457 if (E->initializesStdInitializerList())
3458 return false;
3459
Richard Smith180f4792011-11-10 06:34:14 +00003460 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3461 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3462
3463 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003464 const FieldDecl *Field = E->getInitializedFieldInUnion();
3465 Result = APValue(Field);
3466 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003467 return true;
Richard Smithec789162012-01-12 18:54:33 +00003468
3469 // If the initializer list for a union does not contain any elements, the
3470 // first element of the union is value-initialized.
3471 ImplicitValueInitExpr VIE(Field->getType());
3472 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3473
Richard Smith180f4792011-11-10 06:34:14 +00003474 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003475 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003476 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003477 }
3478
3479 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3480 "initializer list for class with base classes");
3481 Result = APValue(APValue::UninitStruct(), 0,
3482 std::distance(RD->field_begin(), RD->field_end()));
3483 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003484 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003485 for (RecordDecl::field_iterator Field = RD->field_begin(),
3486 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3487 // Anonymous bit-fields are not considered members of the class for
3488 // purposes of aggregate initialization.
3489 if (Field->isUnnamedBitfield())
3490 continue;
3491
3492 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003493
Richard Smith745f5142012-01-27 01:14:48 +00003494 bool HaveInit = ElementNo < E->getNumInits();
3495
3496 // FIXME: Diagnostics here should point to the end of the initializer
3497 // list, not the start.
3498 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3499 *Field, &Layout);
3500
3501 // Perform an implicit value-initialization for members beyond the end of
3502 // the initializer list.
3503 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3504
Richard Smith83587db2012-02-15 02:18:13 +00003505 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003506 Result.getStructField((*Field)->getFieldIndex()),
3507 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3508 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003509 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003510 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003511 }
3512 }
3513
Richard Smith745f5142012-01-27 01:14:48 +00003514 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003515}
3516
3517bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3518 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003519 bool ZeroInit = E->requiresZeroInitialization();
3520 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003521 // If we've already performed zero-initialization, we're already done.
3522 if (!Result.isUninit())
3523 return true;
3524
Richard Smith51201882011-12-30 21:15:51 +00003525 if (ZeroInit)
3526 return ZeroInitialization(E);
3527
Richard Smith61802452011-12-22 02:22:31 +00003528 const CXXRecordDecl *RD = FD->getParent();
3529 if (RD->isUnion())
3530 Result = APValue((FieldDecl*)0);
3531 else
3532 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3533 std::distance(RD->field_begin(), RD->field_end()));
3534 return true;
3535 }
3536
Richard Smith180f4792011-11-10 06:34:14 +00003537 const FunctionDecl *Definition = 0;
3538 FD->getBody(Definition);
3539
Richard Smithc1c5f272011-12-13 06:39:58 +00003540 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3541 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003542
Richard Smith610a60c2012-01-10 04:32:03 +00003543 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003544 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003545 if (const MaterializeTemporaryExpr *ME
3546 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3547 return Visit(ME->GetTemporaryExpr());
3548
Richard Smith51201882011-12-30 21:15:51 +00003549 if (ZeroInit && !ZeroInitialization(E))
3550 return false;
3551
Richard Smith180f4792011-11-10 06:34:14 +00003552 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003553 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003554 cast<CXXConstructorDecl>(Definition), Info,
3555 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003556}
3557
3558static bool EvaluateRecord(const Expr *E, const LValue &This,
3559 APValue &Result, EvalInfo &Info) {
3560 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003561 "can't evaluate expression as a record rvalue");
3562 return RecordExprEvaluator(Info, This, Result).Visit(E);
3563}
3564
3565//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003566// Temporary Evaluation
3567//
3568// Temporaries are represented in the AST as rvalues, but generally behave like
3569// lvalues. The full-object of which the temporary is a subobject is implicitly
3570// materialized so that a reference can bind to it.
3571//===----------------------------------------------------------------------===//
3572namespace {
3573class TemporaryExprEvaluator
3574 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3575public:
3576 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3577 LValueExprEvaluatorBaseTy(Info, Result) {}
3578
3579 /// Visit an expression which constructs the value of this temporary.
3580 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003581 Result.set(E, Info.CurrentCall->Index);
3582 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003583 }
3584
3585 bool VisitCastExpr(const CastExpr *E) {
3586 switch (E->getCastKind()) {
3587 default:
3588 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3589
3590 case CK_ConstructorConversion:
3591 return VisitConstructExpr(E->getSubExpr());
3592 }
3593 }
3594 bool VisitInitListExpr(const InitListExpr *E) {
3595 return VisitConstructExpr(E);
3596 }
3597 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3598 return VisitConstructExpr(E);
3599 }
3600 bool VisitCallExpr(const CallExpr *E) {
3601 return VisitConstructExpr(E);
3602 }
3603};
3604} // end anonymous namespace
3605
3606/// Evaluate an expression of record type as a temporary.
3607static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003608 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003609 return TemporaryExprEvaluator(Info, Result).Visit(E);
3610}
3611
3612//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003613// Vector Evaluation
3614//===----------------------------------------------------------------------===//
3615
3616namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003617 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003618 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3619 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003620 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003621
Richard Smith07fc6572011-10-22 21:10:00 +00003622 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3623 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Richard Smith07fc6572011-10-22 21:10:00 +00003625 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3626 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3627 // FIXME: remove this APValue copy.
3628 Result = APValue(V.data(), V.size());
3629 return true;
3630 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003631 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003632 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003633 Result = V;
3634 return true;
3635 }
Richard Smith51201882011-12-30 21:15:51 +00003636 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Richard Smith07fc6572011-10-22 21:10:00 +00003638 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003639 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003640 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003641 bool VisitInitListExpr(const InitListExpr *E);
3642 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003643 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003644 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003645 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003646 };
3647} // end anonymous namespace
3648
3649static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003650 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003651 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003652}
3653
Richard Smith07fc6572011-10-22 21:10:00 +00003654bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3655 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003656 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003657
Richard Smithd62ca372011-12-06 22:44:34 +00003658 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003659 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003660
Eli Friedman46a52322011-03-25 00:43:55 +00003661 switch (E->getCastKind()) {
3662 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003663 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003664 if (SETy->isIntegerType()) {
3665 APSInt IntResult;
3666 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003667 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003668 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003669 } else if (SETy->isRealFloatingType()) {
3670 APFloat F(0.0);
3671 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003672 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003673 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003674 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003675 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003676 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003677
3678 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003679 SmallVector<APValue, 4> Elts(NElts, Val);
3680 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003681 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003682 case CK_BitCast: {
3683 // Evaluate the operand into an APInt we can extract from.
3684 llvm::APInt SValInt;
3685 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3686 return false;
3687 // Extract the elements
3688 QualType EltTy = VTy->getElementType();
3689 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3690 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3691 SmallVector<APValue, 4> Elts;
3692 if (EltTy->isRealFloatingType()) {
3693 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3694 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3695 unsigned FloatEltSize = EltSize;
3696 if (&Sem == &APFloat::x87DoubleExtended)
3697 FloatEltSize = 80;
3698 for (unsigned i = 0; i < NElts; i++) {
3699 llvm::APInt Elt;
3700 if (BigEndian)
3701 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3702 else
3703 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3704 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3705 }
3706 } else if (EltTy->isIntegerType()) {
3707 for (unsigned i = 0; i < NElts; i++) {
3708 llvm::APInt Elt;
3709 if (BigEndian)
3710 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3711 else
3712 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3713 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3714 }
3715 } else {
3716 return Error(E);
3717 }
3718 return Success(Elts, E);
3719 }
Eli Friedman46a52322011-03-25 00:43:55 +00003720 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003721 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003722 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003723}
3724
Richard Smith07fc6572011-10-22 21:10:00 +00003725bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003726VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003727 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003728 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003729 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Nate Begeman59b5da62009-01-18 03:20:47 +00003731 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003732 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003733
Eli Friedman3edd5a92012-01-03 23:24:20 +00003734 // The number of initializers can be less than the number of
3735 // vector elements. For OpenCL, this can be due to nested vector
3736 // initialization. For GCC compatibility, missing trailing elements
3737 // should be initialized with zeroes.
3738 unsigned CountInits = 0, CountElts = 0;
3739 while (CountElts < NumElements) {
3740 // Handle nested vector initialization.
3741 if (CountInits < NumInits
3742 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3743 APValue v;
3744 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3745 return Error(E);
3746 unsigned vlen = v.getVectorLength();
3747 for (unsigned j = 0; j < vlen; j++)
3748 Elements.push_back(v.getVectorElt(j));
3749 CountElts += vlen;
3750 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003751 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003752 if (CountInits < NumInits) {
3753 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003754 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003755 } else // trailing integer zero.
3756 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3757 Elements.push_back(APValue(sInt));
3758 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003759 } else {
3760 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003761 if (CountInits < NumInits) {
3762 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003763 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003764 } else // trailing float zero.
3765 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3766 Elements.push_back(APValue(f));
3767 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003768 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003769 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003770 }
Richard Smith07fc6572011-10-22 21:10:00 +00003771 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003772}
3773
Richard Smith07fc6572011-10-22 21:10:00 +00003774bool
Richard Smith51201882011-12-30 21:15:51 +00003775VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003776 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003777 QualType EltTy = VT->getElementType();
3778 APValue ZeroElement;
3779 if (EltTy->isIntegerType())
3780 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3781 else
3782 ZeroElement =
3783 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3784
Chris Lattner5f9e2722011-07-23 10:55:15 +00003785 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003786 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003787}
3788
Richard Smith07fc6572011-10-22 21:10:00 +00003789bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003790 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003791 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003792}
3793
Nate Begeman59b5da62009-01-18 03:20:47 +00003794//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003795// Array Evaluation
3796//===----------------------------------------------------------------------===//
3797
3798namespace {
3799 class ArrayExprEvaluator
3800 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003801 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003802 APValue &Result;
3803 public:
3804
Richard Smith180f4792011-11-10 06:34:14 +00003805 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3806 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003807
3808 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003809 assert((V.isArray() || V.isLValue()) &&
3810 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003811 Result = V;
3812 return true;
3813 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003814
Richard Smith51201882011-12-30 21:15:51 +00003815 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003816 const ConstantArrayType *CAT =
3817 Info.Ctx.getAsConstantArrayType(E->getType());
3818 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003819 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003820
3821 Result = APValue(APValue::UninitArray(), 0,
3822 CAT->getSize().getZExtValue());
3823 if (!Result.hasArrayFiller()) return true;
3824
Richard Smith51201882011-12-30 21:15:51 +00003825 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003826 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003827 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003828 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003829 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003830 }
3831
Richard Smithcc5d4f62011-11-07 09:22:26 +00003832 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003833 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003834 };
3835} // end anonymous namespace
3836
Richard Smith180f4792011-11-10 06:34:14 +00003837static bool EvaluateArray(const Expr *E, const LValue &This,
3838 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003839 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003840 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003841}
3842
3843bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3844 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3845 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003846 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003847
Richard Smith974c5f92011-12-22 01:07:19 +00003848 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3849 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003850 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003851 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3852 LValue LV;
3853 if (!EvaluateLValue(E->getInit(0), LV, Info))
3854 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003855 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003856 LV.moveInto(Val);
3857 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003858 }
3859
Richard Smith745f5142012-01-27 01:14:48 +00003860 bool Success = true;
3861
Richard Smithcc5d4f62011-11-07 09:22:26 +00003862 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3863 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003864 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003865 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003866 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003867 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003868 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003869 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3870 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003871 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3872 CAT->getElementType(), 1)) {
3873 if (!Info.keepEvaluatingAfterFailure())
3874 return false;
3875 Success = false;
3876 }
Richard Smith180f4792011-11-10 06:34:14 +00003877 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003878
Richard Smith745f5142012-01-27 01:14:48 +00003879 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003880 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003881 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3882 // but sometimes does:
3883 // struct S { constexpr S() : p(&p) {} void *p; };
3884 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003885 return EvaluateInPlace(Result.getArrayFiller(), Info,
3886 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003887}
3888
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3890 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3891 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003892 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003893
Richard Smithec789162012-01-12 18:54:33 +00003894 bool HadZeroInit = !Result.isUninit();
3895 if (!HadZeroInit)
3896 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003897 if (!Result.hasArrayFiller())
3898 return true;
3899
3900 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003901
Richard Smith51201882011-12-30 21:15:51 +00003902 bool ZeroInit = E->requiresZeroInitialization();
3903 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003904 if (HadZeroInit)
3905 return true;
3906
Richard Smith51201882011-12-30 21:15:51 +00003907 if (ZeroInit) {
3908 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003909 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003910 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003911 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003912 }
3913
Richard Smith61802452011-12-22 02:22:31 +00003914 const CXXRecordDecl *RD = FD->getParent();
3915 if (RD->isUnion())
3916 Result.getArrayFiller() = APValue((FieldDecl*)0);
3917 else
3918 Result.getArrayFiller() =
3919 APValue(APValue::UninitStruct(), RD->getNumBases(),
3920 std::distance(RD->field_begin(), RD->field_end()));
3921 return true;
3922 }
3923
Richard Smithe24f5fc2011-11-17 22:56:20 +00003924 const FunctionDecl *Definition = 0;
3925 FD->getBody(Definition);
3926
Richard Smithc1c5f272011-12-13 06:39:58 +00003927 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3928 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003929
3930 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3931 // but sometimes does:
3932 // struct S { constexpr S() : p(&p) {} void *p; };
3933 // S s[10];
3934 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003935 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003936
Richard Smithec789162012-01-12 18:54:33 +00003937 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003938 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003939 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003940 return false;
3941 }
3942
Richard Smithe24f5fc2011-11-17 22:56:20 +00003943 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003944 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003945 cast<CXXConstructorDecl>(Definition),
3946 Info, Result.getArrayFiller());
3947}
3948
Richard Smithcc5d4f62011-11-07 09:22:26 +00003949//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003950// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003951//
3952// As a GNU extension, we support casting pointers to sufficiently-wide integer
3953// types and back in constant folding. Integer values are thus represented
3954// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003955//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003956
3957namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003958class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003959 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003960 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003961public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003962 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003963 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003964
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003965 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003966 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003967 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003968 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003969 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003970 assert(SI.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(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003973 return true;
3974 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003975 bool Success(const llvm::APSInt &SI, const Expr *E) {
3976 return Success(SI, E, Result);
3977 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003978
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003979 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003980 assert(E->getType()->isIntegralOrEnumerationType() &&
3981 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003982 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003983 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003984 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003985 Result.getInt().setIsUnsigned(
3986 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003987 return true;
3988 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003989 bool Success(const llvm::APInt &I, const Expr *E) {
3990 return Success(I, E, Result);
3991 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003992
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003993 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003994 assert(E->getType()->isIntegralOrEnumerationType() &&
3995 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003996 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003997 return true;
3998 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003999 bool Success(uint64_t Value, const Expr *E) {
4000 return Success(Value, E, Result);
4001 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004002
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004003 bool Success(CharUnits Size, const Expr *E) {
4004 return Success(Size.getQuantity(), E);
4005 }
4006
Richard Smith1aa0be82012-03-03 22:46:17 +00004007 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004008 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004009 Result = V;
4010 return true;
4011 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004012 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Richard Smith51201882011-12-30 21:15:51 +00004015 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004016
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004017 //===--------------------------------------------------------------------===//
4018 // Visitor Methods
4019 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004020
Chris Lattner4c4867e2008-07-12 00:38:25 +00004021 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004022 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004023 }
4024 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004025 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004026 }
Eli Friedman04309752009-11-24 05:28:59 +00004027
4028 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4029 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004030 if (CheckReferencedDecl(E, E->getDecl()))
4031 return true;
4032
4033 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004034 }
4035 bool VisitMemberExpr(const MemberExpr *E) {
4036 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004037 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004038 return true;
4039 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004040
4041 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004042 }
4043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004044 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004045 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004046 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004047 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004049 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004050 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004051
Anders Carlsson3068d112008-11-16 19:01:22 +00004052 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004053 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004054 }
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004056 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4057 return Success(E->getValue(), E);
4058 }
4059
Richard Smithf10d9172011-10-11 21:43:33 +00004060 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004061 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004062 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004063 }
4064
Sebastian Redl64b45f72009-01-05 20:52:13 +00004065 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004066 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004067 }
4068
Francois Pichet6ad6f282010-12-07 00:08:36 +00004069 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4070 return Success(E->getValue(), E);
4071 }
4072
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004073 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4074 return Success(E->getValue(), E);
4075 }
4076
John Wiegley21ff2e52011-04-28 00:16:57 +00004077 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4078 return Success(E->getValue(), E);
4079 }
4080
John Wiegley55262202011-04-25 06:54:41 +00004081 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4082 return Success(E->getValue(), E);
4083 }
4084
Eli Friedman722c7172009-02-28 03:59:05 +00004085 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004086 bool VisitUnaryImag(const UnaryOperator *E);
4087
Sebastian Redl295995c2010-09-10 20:55:47 +00004088 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004089 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004090
Chris Lattnerfcee0012008-07-11 21:24:13 +00004091private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004092 CharUnits GetAlignOfExpr(const Expr *E);
4093 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004094 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004095 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004096 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004097};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004098} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004099
Richard Smithc49bd112011-10-28 17:51:58 +00004100/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4101/// produce either the integer value or a pointer.
4102///
4103/// GCC has a heinous extension which folds casts between pointer types and
4104/// pointer-sized integral types. We support this by allowing the evaluation of
4105/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4106/// Some simple arithmetic on such values is supported (they are treated much
4107/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004108static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004109 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004110 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004111 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004112}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004113
Richard Smithf48fdb02011-12-09 22:58:01 +00004114static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004115 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004116 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004117 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004118 if (!Val.isInt()) {
4119 // FIXME: It would be better to produce the diagnostic for casting
4120 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004121 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004122 return false;
4123 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004124 Result = Val.getInt();
4125 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004126}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004127
Richard Smithf48fdb02011-12-09 22:58:01 +00004128/// Check whether the given declaration can be directly converted to an integral
4129/// rvalue. If not, no diagnostic is produced; there are other things we can
4130/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004131bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004132 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004133 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004134 // Check for signedness/width mismatches between E type and ECD value.
4135 bool SameSign = (ECD->getInitVal().isSigned()
4136 == E->getType()->isSignedIntegerOrEnumerationType());
4137 bool SameWidth = (ECD->getInitVal().getBitWidth()
4138 == Info.Ctx.getIntWidth(E->getType()));
4139 if (SameSign && SameWidth)
4140 return Success(ECD->getInitVal(), E);
4141 else {
4142 // Get rid of mismatch (otherwise Success assertions will fail)
4143 // by computing a new value matching the type of E.
4144 llvm::APSInt Val = ECD->getInitVal();
4145 if (!SameSign)
4146 Val.setIsSigned(!ECD->getInitVal().isSigned());
4147 if (!SameWidth)
4148 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4149 return Success(Val, E);
4150 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004151 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004152 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004153}
4154
Chris Lattnera4d55d82008-10-06 06:40:35 +00004155/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4156/// as GCC.
4157static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4158 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004159 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004160 enum gcc_type_class {
4161 no_type_class = -1,
4162 void_type_class, integer_type_class, char_type_class,
4163 enumeral_type_class, boolean_type_class,
4164 pointer_type_class, reference_type_class, offset_type_class,
4165 real_type_class, complex_type_class,
4166 function_type_class, method_type_class,
4167 record_type_class, union_type_class,
4168 array_type_class, string_type_class,
4169 lang_type_class
4170 };
Mike Stump1eb44332009-09-09 15:08:12 +00004171
4172 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004173 // ideal, however it is what gcc does.
4174 if (E->getNumArgs() == 0)
4175 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004176
Chris Lattnera4d55d82008-10-06 06:40:35 +00004177 QualType ArgTy = E->getArg(0)->getType();
4178 if (ArgTy->isVoidType())
4179 return void_type_class;
4180 else if (ArgTy->isEnumeralType())
4181 return enumeral_type_class;
4182 else if (ArgTy->isBooleanType())
4183 return boolean_type_class;
4184 else if (ArgTy->isCharType())
4185 return string_type_class; // gcc doesn't appear to use char_type_class
4186 else if (ArgTy->isIntegerType())
4187 return integer_type_class;
4188 else if (ArgTy->isPointerType())
4189 return pointer_type_class;
4190 else if (ArgTy->isReferenceType())
4191 return reference_type_class;
4192 else if (ArgTy->isRealType())
4193 return real_type_class;
4194 else if (ArgTy->isComplexType())
4195 return complex_type_class;
4196 else if (ArgTy->isFunctionType())
4197 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004198 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004199 return record_type_class;
4200 else if (ArgTy->isUnionType())
4201 return union_type_class;
4202 else if (ArgTy->isArrayType())
4203 return array_type_class;
4204 else if (ArgTy->isUnionType())
4205 return union_type_class;
4206 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004207 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004208}
4209
Richard Smith80d4b552011-12-28 19:48:30 +00004210/// EvaluateBuiltinConstantPForLValue - Determine the result of
4211/// __builtin_constant_p when applied to the given lvalue.
4212///
4213/// An lvalue is only "constant" if it is a pointer or reference to the first
4214/// character of a string literal.
4215template<typename LValue>
4216static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004217 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004218 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4219}
4220
4221/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4222/// GCC as we can manage.
4223static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4224 QualType ArgType = Arg->getType();
4225
4226 // __builtin_constant_p always has one operand. The rules which gcc follows
4227 // are not precisely documented, but are as follows:
4228 //
4229 // - If the operand is of integral, floating, complex or enumeration type,
4230 // and can be folded to a known value of that type, it returns 1.
4231 // - If the operand and can be folded to a pointer to the first character
4232 // of a string literal (or such a pointer cast to an integral type), it
4233 // returns 1.
4234 //
4235 // Otherwise, it returns 0.
4236 //
4237 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4238 // its support for this does not currently work.
4239 if (ArgType->isIntegralOrEnumerationType()) {
4240 Expr::EvalResult Result;
4241 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4242 return false;
4243
4244 APValue &V = Result.Val;
4245 if (V.getKind() == APValue::Int)
4246 return true;
4247
4248 return EvaluateBuiltinConstantPForLValue(V);
4249 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4250 return Arg->isEvaluatable(Ctx);
4251 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4252 LValue LV;
4253 Expr::EvalStatus Status;
4254 EvalInfo Info(Ctx, Status);
4255 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4256 : EvaluatePointer(Arg, LV, Info)) &&
4257 !Status.HasSideEffects)
4258 return EvaluateBuiltinConstantPForLValue(LV);
4259 }
4260
4261 // Anything else isn't considered to be sufficiently constant.
4262 return false;
4263}
4264
John McCall42c8f872010-05-10 23:27:23 +00004265/// Retrieves the "underlying object type" of the given expression,
4266/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004267QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4268 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4269 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004270 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004271 } else if (const Expr *E = B.get<const Expr*>()) {
4272 if (isa<CompoundLiteralExpr>(E))
4273 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004274 }
4275
4276 return QualType();
4277}
4278
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004279bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004280 // TODO: Perhaps we should let LLVM lower this?
4281 LValue Base;
4282 if (!EvaluatePointer(E->getArg(0), Base, Info))
4283 return false;
4284
4285 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004286 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004287
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004288 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004289 if (T.isNull() ||
4290 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004291 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004292 T->isVariablyModifiedType() ||
4293 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004294 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004295
4296 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4297 CharUnits Offset = Base.getLValueOffset();
4298
4299 if (!Offset.isNegative() && Offset <= Size)
4300 Size -= Offset;
4301 else
4302 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004303 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004304}
4305
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004306bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004307 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004308 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004309 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004310
4311 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004312 if (TryEvaluateBuiltinObjectSize(E))
4313 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004314
Eric Christopherb2aaf512010-01-19 22:58:35 +00004315 // If evaluating the argument has side-effects we can't determine
4316 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004317 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004318 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004319 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004320 return Success(0, E);
4321 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004322
Richard Smithf48fdb02011-12-09 22:58:01 +00004323 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004324 }
4325
Chris Lattner019f4e82008-10-06 05:28:25 +00004326 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004327 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004328
Richard Smith80d4b552011-12-28 19:48:30 +00004329 case Builtin::BI__builtin_constant_p:
4330 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004331
Chris Lattner21fb98e2009-09-23 06:06:36 +00004332 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004333 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004334 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004335 return Success(Operand, E);
4336 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004337
4338 case Builtin::BI__builtin_expect:
4339 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004340
Douglas Gregor5726d402010-09-10 06:27:15 +00004341 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004342 // A call to strlen is not a constant expression.
4343 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004344 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004345 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4346 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004347 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004348 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004349 case Builtin::BI__builtin_strlen:
4350 // As an extension, we support strlen() and __builtin_strlen() as constant
4351 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004352 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004353 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4354 // The string literal may have embedded null characters. Find the first
4355 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004356 StringRef Str = S->getString();
4357 StringRef::size_type Pos = Str.find(0);
4358 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004359 Str = Str.substr(0, Pos);
4360
4361 return Success(Str.size(), E);
4362 }
4363
Richard Smithf48fdb02011-12-09 22:58:01 +00004364 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004365
4366 case Builtin::BI__atomic_is_lock_free: {
4367 APSInt SizeVal;
4368 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4369 return false;
4370
4371 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4372 // of two less than the maximum inline atomic width, we know it is
4373 // lock-free. If the size isn't a power of two, or greater than the
4374 // maximum alignment where we promote atomics, we know it is not lock-free
4375 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4376 // the answer can only be determined at runtime; for example, 16-byte
4377 // atomics have lock-free implementations on some, but not all,
4378 // x86-64 processors.
4379
4380 // Check power-of-two.
4381 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4382 if (!Size.isPowerOfTwo())
4383#if 0
4384 // FIXME: Suppress this folding until the ABI for the promotion width
4385 // settles.
4386 return Success(0, E);
4387#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004388 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004389#endif
4390
4391#if 0
4392 // Check against promotion width.
4393 // FIXME: Suppress this folding until the ABI for the promotion width
4394 // settles.
4395 unsigned PromoteWidthBits =
4396 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4397 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4398 return Success(0, E);
4399#endif
4400
4401 // Check against inlining width.
4402 unsigned InlineWidthBits =
4403 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4404 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4405 return Success(1, E);
4406
Richard Smithf48fdb02011-12-09 22:58:01 +00004407 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004408 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004409 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004410}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004411
Richard Smith625b8072011-10-31 01:37:14 +00004412static bool HasSameBase(const LValue &A, const LValue &B) {
4413 if (!A.getLValueBase())
4414 return !B.getLValueBase();
4415 if (!B.getLValueBase())
4416 return false;
4417
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004418 if (A.getLValueBase().getOpaqueValue() !=
4419 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004420 const Decl *ADecl = GetLValueBaseDecl(A);
4421 if (!ADecl)
4422 return false;
4423 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004424 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004425 return false;
4426 }
4427
4428 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004429 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004430}
4431
Richard Smith7b48a292012-02-01 05:53:12 +00004432/// Perform the given integer operation, which is known to need at most BitWidth
4433/// bits, and check for overflow in the original type (if that type was not an
4434/// unsigned type).
4435template<typename Operation>
4436static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4437 const APSInt &LHS, const APSInt &RHS,
4438 unsigned BitWidth, Operation Op) {
4439 if (LHS.isUnsigned())
4440 return Op(LHS, RHS);
4441
4442 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4443 APSInt Result = Value.trunc(LHS.getBitWidth());
4444 if (Result.extend(BitWidth) != Value)
4445 HandleOverflow(Info, E, Value, E->getType());
4446 return Result;
4447}
4448
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004449namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004450
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004451/// \brief Data recursive integer evaluator of certain binary operators.
4452///
4453/// We use a data recursive algorithm for binary operators so that we are able
4454/// to handle extreme cases of chained binary operators without causing stack
4455/// overflow.
4456class DataRecursiveIntBinOpEvaluator {
4457 struct EvalResult {
4458 APValue Val;
4459 bool Failed;
4460
4461 EvalResult() : Failed(false) { }
4462
4463 void swap(EvalResult &RHS) {
4464 Val.swap(RHS.Val);
4465 Failed = RHS.Failed;
4466 RHS.Failed = false;
4467 }
4468 };
4469
4470 struct Job {
4471 const Expr *E;
4472 EvalResult LHSResult; // meaningful only for binary operator expression.
4473 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4474
4475 Job() : StoredInfo(0) { }
4476 void startSpeculativeEval(EvalInfo &Info) {
4477 OldEvalStatus = Info.EvalStatus;
4478 Info.EvalStatus.Diag = 0;
4479 StoredInfo = &Info;
4480 }
4481 ~Job() {
4482 if (StoredInfo) {
4483 StoredInfo->EvalStatus = OldEvalStatus;
4484 }
4485 }
4486 private:
4487 EvalInfo *StoredInfo; // non-null if status changed.
4488 Expr::EvalStatus OldEvalStatus;
4489 };
4490
4491 SmallVector<Job, 16> Queue;
4492
4493 IntExprEvaluator &IntEval;
4494 EvalInfo &Info;
4495 APValue &FinalResult;
4496
4497public:
4498 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4499 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4500
4501 /// \brief True if \param E is a binary operator that we are going to handle
4502 /// data recursively.
4503 /// We handle binary operators that are comma, logical, or that have operands
4504 /// with integral or enumeration type.
4505 static bool shouldEnqueue(const BinaryOperator *E) {
4506 return E->getOpcode() == BO_Comma ||
4507 E->isLogicalOp() ||
4508 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4509 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004510 }
4511
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004512 bool Traverse(const BinaryOperator *E) {
4513 enqueue(E);
4514 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004515 while (!Queue.empty())
4516 process(PrevResult);
4517
4518 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004519
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004520 FinalResult.swap(PrevResult.Val);
4521 return true;
4522 }
4523
4524private:
4525 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4526 return IntEval.Success(Value, E, Result);
4527 }
4528 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4529 return IntEval.Success(Value, E, Result);
4530 }
4531 bool Error(const Expr *E) {
4532 return IntEval.Error(E);
4533 }
4534 bool Error(const Expr *E, diag::kind D) {
4535 return IntEval.Error(E, D);
4536 }
4537
4538 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4539 return Info.CCEDiag(E, D);
4540 }
4541
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004542 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4543 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004544 bool &SuppressRHSDiags);
4545
4546 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4547 const BinaryOperator *E, APValue &Result);
4548
4549 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4550 Result.Failed = !Evaluate(Result.Val, Info, E);
4551 if (Result.Failed)
4552 Result.Val = APValue();
4553 }
4554
Richard Trieub7783052012-03-21 23:30:30 +00004555 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004556
4557 void enqueue(const Expr *E) {
4558 E = E->IgnoreParens();
4559 Queue.resize(Queue.size()+1);
4560 Queue.back().E = E;
4561 Queue.back().Kind = Job::AnyExprKind;
4562 }
4563};
4564
4565}
4566
4567bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004568 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004569 bool &SuppressRHSDiags) {
4570 if (E->getOpcode() == BO_Comma) {
4571 // Ignore LHS but note if we could not evaluate it.
4572 if (LHSResult.Failed)
4573 Info.EvalStatus.HasSideEffects = true;
4574 return true;
4575 }
4576
4577 if (E->isLogicalOp()) {
4578 bool lhsResult;
4579 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004580 // We were able to evaluate the LHS, see if we can get away with not
4581 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004582 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004583 Success(lhsResult, E, LHSResult.Val);
4584 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004585 }
4586 } else {
4587 // Since we weren't able to evaluate the left hand side, it
4588 // must have had side effects.
4589 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004590
4591 // We can't evaluate the LHS; however, sometimes the result
4592 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4593 // Don't ignore RHS and suppress diagnostics from this arm.
4594 SuppressRHSDiags = true;
4595 }
4596
4597 return true;
4598 }
4599
4600 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4601 E->getRHS()->getType()->isIntegralOrEnumerationType());
4602
4603 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004604 return false; // Ignore RHS;
4605
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004606 return true;
4607}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004608
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004609bool DataRecursiveIntBinOpEvaluator::
4610 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4611 const BinaryOperator *E, APValue &Result) {
4612 if (E->getOpcode() == BO_Comma) {
4613 if (RHSResult.Failed)
4614 return false;
4615 Result = RHSResult.Val;
4616 return true;
4617 }
4618
4619 if (E->isLogicalOp()) {
4620 bool lhsResult, rhsResult;
4621 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4622 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4623
4624 if (LHSIsOK) {
4625 if (RHSIsOK) {
4626 if (E->getOpcode() == BO_LOr)
4627 return Success(lhsResult || rhsResult, E, Result);
4628 else
4629 return Success(lhsResult && rhsResult, E, Result);
4630 }
4631 } else {
4632 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004633 // We can't evaluate the LHS; however, sometimes the result
4634 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4635 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004636 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004637 }
4638 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004639
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004640 return false;
4641 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004642
4643 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4644 E->getRHS()->getType()->isIntegralOrEnumerationType());
4645
4646 if (LHSResult.Failed || RHSResult.Failed)
4647 return false;
4648
4649 const APValue &LHSVal = LHSResult.Val;
4650 const APValue &RHSVal = RHSResult.Val;
4651
4652 // Handle cases like (unsigned long)&a + 4.
4653 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4654 Result = LHSVal;
4655 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4656 RHSVal.getInt().getZExtValue());
4657 if (E->getOpcode() == BO_Add)
4658 Result.getLValueOffset() += AdditionalOffset;
4659 else
4660 Result.getLValueOffset() -= AdditionalOffset;
4661 return true;
4662 }
4663
4664 // Handle cases like 4 + (unsigned long)&a
4665 if (E->getOpcode() == BO_Add &&
4666 RHSVal.isLValue() && LHSVal.isInt()) {
4667 Result = RHSVal;
4668 Result.getLValueOffset() += CharUnits::fromQuantity(
4669 LHSVal.getInt().getZExtValue());
4670 return true;
4671 }
4672
4673 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4674 // Handle (intptr_t)&&A - (intptr_t)&&B.
4675 if (!LHSVal.getLValueOffset().isZero() ||
4676 !RHSVal.getLValueOffset().isZero())
4677 return false;
4678 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4679 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4680 if (!LHSExpr || !RHSExpr)
4681 return false;
4682 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4683 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4684 if (!LHSAddrExpr || !RHSAddrExpr)
4685 return false;
4686 // Make sure both labels come from the same function.
4687 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4688 RHSAddrExpr->getLabel()->getDeclContext())
4689 return false;
4690 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4691 return true;
4692 }
4693
4694 // All the following cases expect both operands to be an integer
4695 if (!LHSVal.isInt() || !RHSVal.isInt())
4696 return Error(E);
4697
4698 const APSInt &LHS = LHSVal.getInt();
4699 APSInt RHS = RHSVal.getInt();
4700
4701 switch (E->getOpcode()) {
4702 default:
4703 return Error(E);
4704 case BO_Mul:
4705 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4706 LHS.getBitWidth() * 2,
4707 std::multiplies<APSInt>()), E,
4708 Result);
4709 case BO_Add:
4710 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4711 LHS.getBitWidth() + 1,
4712 std::plus<APSInt>()), E, Result);
4713 case BO_Sub:
4714 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4715 LHS.getBitWidth() + 1,
4716 std::minus<APSInt>()), E, Result);
4717 case BO_And: return Success(LHS & RHS, E, Result);
4718 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4719 case BO_Or: return Success(LHS | RHS, E, Result);
4720 case BO_Div:
4721 case BO_Rem:
4722 if (RHS == 0)
4723 return Error(E, diag::note_expr_divide_by_zero);
4724 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4725 // not actually undefined behavior in C++11 due to a language defect.
4726 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4727 LHS.isSigned() && LHS.isMinSignedValue())
4728 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4729 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4730 Result);
4731 case BO_Shl: {
4732 // During constant-folding, a negative shift is an opposite shift. Such
4733 // a shift is not a constant expression.
4734 if (RHS.isSigned() && RHS.isNegative()) {
4735 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4736 RHS = -RHS;
4737 goto shift_right;
4738 }
4739
4740 shift_left:
4741 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4742 // the shifted type.
4743 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4744 if (SA != RHS) {
4745 CCEDiag(E, diag::note_constexpr_large_shift)
4746 << RHS << E->getType() << LHS.getBitWidth();
4747 } else if (LHS.isSigned()) {
4748 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4749 // operand, and must not overflow the corresponding unsigned type.
4750 if (LHS.isNegative())
4751 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4752 else if (LHS.countLeadingZeros() < SA)
4753 CCEDiag(E, diag::note_constexpr_lshift_discards);
4754 }
4755
4756 return Success(LHS << SA, E, Result);
4757 }
4758 case BO_Shr: {
4759 // During constant-folding, a negative shift is an opposite shift. Such a
4760 // shift is not a constant expression.
4761 if (RHS.isSigned() && RHS.isNegative()) {
4762 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4763 RHS = -RHS;
4764 goto shift_left;
4765 }
4766
4767 shift_right:
4768 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4769 // shifted type.
4770 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4771 if (SA != RHS)
4772 CCEDiag(E, diag::note_constexpr_large_shift)
4773 << RHS << E->getType() << LHS.getBitWidth();
4774
4775 return Success(LHS >> SA, E, Result);
4776 }
4777
4778 case BO_LT: return Success(LHS < RHS, E, Result);
4779 case BO_GT: return Success(LHS > RHS, E, Result);
4780 case BO_LE: return Success(LHS <= RHS, E, Result);
4781 case BO_GE: return Success(LHS >= RHS, E, Result);
4782 case BO_EQ: return Success(LHS == RHS, E, Result);
4783 case BO_NE: return Success(LHS != RHS, E, Result);
4784 }
4785}
4786
Richard Trieub7783052012-03-21 23:30:30 +00004787void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004788 Job &job = Queue.back();
4789
4790 switch (job.Kind) {
4791 case Job::AnyExprKind: {
4792 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4793 if (shouldEnqueue(Bop)) {
4794 job.Kind = Job::BinOpKind;
4795 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004796 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004797 }
4798 }
4799
4800 EvaluateExpr(job.E, Result);
4801 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004802 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004803 }
4804
4805 case Job::BinOpKind: {
4806 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004807 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004808 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004809 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004810 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004811 }
4812 if (SuppressRHSDiags)
4813 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004814 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004815 job.Kind = Job::BinOpVisitedLHSKind;
4816 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004817 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004818 }
4819
4820 case Job::BinOpVisitedLHSKind: {
4821 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4822 EvalResult RHS;
4823 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004824 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004825 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004826 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004827 }
4828 }
4829
4830 llvm_unreachable("Invalid Job::Kind!");
4831}
4832
4833bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4834 if (E->isAssignmentOp())
4835 return Error(E);
4836
4837 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4838 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004839
Anders Carlsson286f85e2008-11-16 07:17:21 +00004840 QualType LHSTy = E->getLHS()->getType();
4841 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004842
4843 if (LHSTy->isAnyComplexType()) {
4844 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004845 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004846
Richard Smith745f5142012-01-27 01:14:48 +00004847 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4848 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004849 return false;
4850
Richard Smith745f5142012-01-27 01:14:48 +00004851 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004852 return false;
4853
4854 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004855 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004856 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004857 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004858 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4859
John McCall2de56d12010-08-25 11:45:40 +00004860 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004861 return Success((CR_r == APFloat::cmpEqual &&
4862 CR_i == APFloat::cmpEqual), E);
4863 else {
John McCall2de56d12010-08-25 11:45:40 +00004864 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004865 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004866 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004867 CR_r == APFloat::cmpLessThan ||
4868 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004869 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004870 CR_i == APFloat::cmpLessThan ||
4871 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004872 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004873 } else {
John McCall2de56d12010-08-25 11:45:40 +00004874 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004875 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4876 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4877 else {
John McCall2de56d12010-08-25 11:45:40 +00004878 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004879 "Invalid compex comparison.");
4880 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4881 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4882 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004883 }
4884 }
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Anders Carlsson286f85e2008-11-16 07:17:21 +00004886 if (LHSTy->isRealFloatingType() &&
4887 RHSTy->isRealFloatingType()) {
4888 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004889
Richard Smith745f5142012-01-27 01:14:48 +00004890 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4891 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004892 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004893
Richard Smith745f5142012-01-27 01:14:48 +00004894 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004895 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004896
Anders Carlsson286f85e2008-11-16 07:17:21 +00004897 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004898
Anders Carlsson286f85e2008-11-16 07:17:21 +00004899 switch (E->getOpcode()) {
4900 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004901 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004902 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004903 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004904 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004905 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004906 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004907 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004908 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004909 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004910 E);
John McCall2de56d12010-08-25 11:45:40 +00004911 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004912 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004913 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004914 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004915 || CR == APFloat::cmpLessThan
4916 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004917 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004918 }
Mike Stump1eb44332009-09-09 15:08:12 +00004919
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004920 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004921 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004922 LValue LHSValue, RHSValue;
4923
4924 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4925 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004926 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004927
Richard Smith745f5142012-01-27 01:14:48 +00004928 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004929 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004930
Richard Smith625b8072011-10-31 01:37:14 +00004931 // Reject differing bases from the normal codepath; we special-case
4932 // comparisons to null.
4933 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004934 if (E->getOpcode() == BO_Sub) {
4935 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004936 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4937 return false;
4938 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4939 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4940 if (!LHSExpr || !RHSExpr)
4941 return false;
4942 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4943 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4944 if (!LHSAddrExpr || !RHSAddrExpr)
4945 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004946 // Make sure both labels come from the same function.
4947 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4948 RHSAddrExpr->getLabel()->getDeclContext())
4949 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004950 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004951 return true;
4952 }
Richard Smith9e36b532011-10-31 05:11:32 +00004953 // Inequalities and subtractions between unrelated pointers have
4954 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004955 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004956 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004957 // A constant address may compare equal to the address of a symbol.
4958 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004959 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004960 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4961 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004962 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004963 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004964 // distinct addresses. In clang, the result of such a comparison is
4965 // unspecified, so it is not a constant expression. However, we do know
4966 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004967 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4968 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004969 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004970 // We can't tell whether weak symbols will end up pointing to the same
4971 // object.
4972 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004973 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004974 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004975 // (Note that clang defaults to -fmerge-all-constants, which can
4976 // lead to inconsistent results for comparisons involving the address
4977 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004978 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004979 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004980
Richard Smith15efc4d2012-02-01 08:10:20 +00004981 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4982 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4983
Richard Smithf15fda02012-02-02 01:16:57 +00004984 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4985 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4986
John McCall2de56d12010-08-25 11:45:40 +00004987 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004988 // C++11 [expr.add]p6:
4989 // Unless both pointers point to elements of the same array object, or
4990 // one past the last element of the array object, the behavior is
4991 // undefined.
4992 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4993 !AreElementsOfSameArray(getType(LHSValue.Base),
4994 LHSDesignator, RHSDesignator))
4995 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4996
Chris Lattner4992bdd2010-04-20 17:13:14 +00004997 QualType Type = E->getLHS()->getType();
4998 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004999
Richard Smith180f4792011-11-10 06:34:14 +00005000 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005001 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005002 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005003
Richard Smith15efc4d2012-02-01 08:10:20 +00005004 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5005 // and produce incorrect results when it overflows. Such behavior
5006 // appears to be non-conforming, but is common, so perhaps we should
5007 // assume the standard intended for such cases to be undefined behavior
5008 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005009
Richard Smith15efc4d2012-02-01 08:10:20 +00005010 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5011 // overflow in the final conversion to ptrdiff_t.
5012 APSInt LHS(
5013 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5014 APSInt RHS(
5015 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5016 APSInt ElemSize(
5017 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5018 APSInt TrueResult = (LHS - RHS) / ElemSize;
5019 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5020
5021 if (Result.extend(65) != TrueResult)
5022 HandleOverflow(Info, E, TrueResult, E->getType());
5023 return Success(Result, E);
5024 }
Richard Smith82f28582012-01-31 06:41:30 +00005025
5026 // C++11 [expr.rel]p3:
5027 // Pointers to void (after pointer conversions) can be compared, with a
5028 // result defined as follows: If both pointers represent the same
5029 // address or are both the null pointer value, the result is true if the
5030 // operator is <= or >= and false otherwise; otherwise the result is
5031 // unspecified.
5032 // We interpret this as applying to pointers to *cv* void.
5033 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005034 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005035 CCEDiag(E, diag::note_constexpr_void_comparison);
5036
Richard Smithf15fda02012-02-02 01:16:57 +00005037 // C++11 [expr.rel]p2:
5038 // - If two pointers point to non-static data members of the same object,
5039 // or to subobjects or array elements fo such members, recursively, the
5040 // pointer to the later declared member compares greater provided the
5041 // two members have the same access control and provided their class is
5042 // not a union.
5043 // [...]
5044 // - Otherwise pointer comparisons are unspecified.
5045 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5046 E->isRelationalOp()) {
5047 bool WasArrayIndex;
5048 unsigned Mismatch =
5049 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5050 RHSDesignator, WasArrayIndex);
5051 // At the point where the designators diverge, the comparison has a
5052 // specified value if:
5053 // - we are comparing array indices
5054 // - we are comparing fields of a union, or fields with the same access
5055 // Otherwise, the result is unspecified and thus the comparison is not a
5056 // constant expression.
5057 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5058 Mismatch < RHSDesignator.Entries.size()) {
5059 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5060 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5061 if (!LF && !RF)
5062 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5063 else if (!LF)
5064 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5065 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5066 << RF->getParent() << RF;
5067 else if (!RF)
5068 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5069 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5070 << LF->getParent() << LF;
5071 else if (!LF->getParent()->isUnion() &&
5072 LF->getAccess() != RF->getAccess())
5073 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5074 << LF << LF->getAccess() << RF << RF->getAccess()
5075 << LF->getParent();
5076 }
5077 }
5078
Richard Smith625b8072011-10-31 01:37:14 +00005079 switch (E->getOpcode()) {
5080 default: llvm_unreachable("missing comparison operator");
5081 case BO_LT: return Success(LHSOffset < RHSOffset, E);
5082 case BO_GT: return Success(LHSOffset > RHSOffset, E);
5083 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
5084 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
5085 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
5086 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005087 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005088 }
5089 }
Richard Smithb02e4622012-02-01 01:42:44 +00005090
5091 if (LHSTy->isMemberPointerType()) {
5092 assert(E->isEqualityOp() && "unexpected member pointer operation");
5093 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5094
5095 MemberPtr LHSValue, RHSValue;
5096
5097 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5098 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5099 return false;
5100
5101 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5102 return false;
5103
5104 // C++11 [expr.eq]p2:
5105 // If both operands are null, they compare equal. Otherwise if only one is
5106 // null, they compare unequal.
5107 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5108 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5109 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5110 }
5111
5112 // Otherwise if either is a pointer to a virtual member function, the
5113 // result is unspecified.
5114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5115 if (MD->isVirtual())
5116 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5117 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5118 if (MD->isVirtual())
5119 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5120
5121 // Otherwise they compare equal if and only if they would refer to the
5122 // same member of the same most derived object or the same subobject if
5123 // they were dereferenced with a hypothetical object of the associated
5124 // class type.
5125 bool Equal = LHSValue == RHSValue;
5126 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5127 }
5128
Richard Smith26f2cac2012-02-14 22:35:28 +00005129 if (LHSTy->isNullPtrType()) {
5130 assert(E->isComparisonOp() && "unexpected nullptr operation");
5131 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5132 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5133 // are compared, the result is true of the operator is <=, >= or ==, and
5134 // false otherwise.
5135 BinaryOperator::Opcode Opcode = E->getOpcode();
5136 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5137 }
5138
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005139 assert((!LHSTy->isIntegralOrEnumerationType() ||
5140 !RHSTy->isIntegralOrEnumerationType()) &&
5141 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5142 // We can't continue from here for non-integral types.
5143 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005144}
5145
Ken Dyck8b752f12010-01-27 17:10:57 +00005146CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005147 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5148 // result shall be the alignment of the referenced type."
5149 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5150 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005151
5152 // __alignof is defined to return the preferred alignment.
5153 return Info.Ctx.toCharUnitsFromBits(
5154 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005155}
5156
Ken Dyck8b752f12010-01-27 17:10:57 +00005157CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005158 E = E->IgnoreParens();
5159
5160 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005161 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005162 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005163 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5164 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005165
Chris Lattneraf707ab2009-01-24 21:53:27 +00005166 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005167 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5168 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005169
Chris Lattnere9feb472009-01-24 21:09:06 +00005170 return GetAlignOfType(E->getType());
5171}
5172
5173
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005174/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5175/// a result as the expression's type.
5176bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5177 const UnaryExprOrTypeTraitExpr *E) {
5178 switch(E->getKind()) {
5179 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005180 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005181 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005182 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005183 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005184 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005185
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005186 case UETT_VecStep: {
5187 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005188
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005189 if (Ty->isVectorType()) {
5190 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005191
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005192 // The vec_step built-in functions that take a 3-component
5193 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5194 if (n == 3)
5195 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005196
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005197 return Success(n, E);
5198 } else
5199 return Success(1, E);
5200 }
5201
5202 case UETT_SizeOf: {
5203 QualType SrcTy = E->getTypeOfArgument();
5204 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5205 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005206 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5207 SrcTy = Ref->getPointeeType();
5208
Richard Smith180f4792011-11-10 06:34:14 +00005209 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005210 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005211 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005212 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005213 }
5214 }
5215
5216 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005217}
5218
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005219bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005220 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005221 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005222 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005223 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005224 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005225 for (unsigned i = 0; i != n; ++i) {
5226 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5227 switch (ON.getKind()) {
5228 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005229 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005230 APSInt IdxResult;
5231 if (!EvaluateInteger(Idx, IdxResult, Info))
5232 return false;
5233 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5234 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005235 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005236 CurrentType = AT->getElementType();
5237 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5238 Result += IdxResult.getSExtValue() * ElementSize;
5239 break;
5240 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005241
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005242 case OffsetOfExpr::OffsetOfNode::Field: {
5243 FieldDecl *MemberDecl = ON.getField();
5244 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005245 if (!RT)
5246 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005247 RecordDecl *RD = RT->getDecl();
5248 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005249 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005250 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005251 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005252 CurrentType = MemberDecl->getType().getNonReferenceType();
5253 break;
5254 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005255
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005256 case OffsetOfExpr::OffsetOfNode::Identifier:
5257 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005258
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005259 case OffsetOfExpr::OffsetOfNode::Base: {
5260 CXXBaseSpecifier *BaseSpec = ON.getBase();
5261 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005262 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005263
5264 // Find the layout of the class whose base we are looking into.
5265 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005266 if (!RT)
5267 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005268 RecordDecl *RD = RT->getDecl();
5269 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5270
5271 // Find the base class itself.
5272 CurrentType = BaseSpec->getType();
5273 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5274 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005275 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005276
5277 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005278 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005279 break;
5280 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005281 }
5282 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005283 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005284}
5285
Chris Lattnerb542afe2008-07-11 19:10:17 +00005286bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005287 switch (E->getOpcode()) {
5288 default:
5289 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5290 // See C99 6.6p3.
5291 return Error(E);
5292 case UO_Extension:
5293 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5294 // If so, we could clear the diagnostic ID.
5295 return Visit(E->getSubExpr());
5296 case UO_Plus:
5297 // The result is just the value.
5298 return Visit(E->getSubExpr());
5299 case UO_Minus: {
5300 if (!Visit(E->getSubExpr()))
5301 return false;
5302 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005303 const APSInt &Value = Result.getInt();
5304 if (Value.isSigned() && Value.isMinSignedValue())
5305 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5306 E->getType());
5307 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005308 }
5309 case UO_Not: {
5310 if (!Visit(E->getSubExpr()))
5311 return false;
5312 if (!Result.isInt()) return Error(E);
5313 return Success(~Result.getInt(), E);
5314 }
5315 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005316 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005317 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005318 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005319 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005320 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005321 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005322}
Mike Stump1eb44332009-09-09 15:08:12 +00005323
Chris Lattner732b2232008-07-12 01:15:53 +00005324/// HandleCast - This is used to evaluate implicit or explicit casts where the
5325/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005326bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5327 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005328 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005329 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005330
Eli Friedman46a52322011-03-25 00:43:55 +00005331 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005332 case CK_BaseToDerived:
5333 case CK_DerivedToBase:
5334 case CK_UncheckedDerivedToBase:
5335 case CK_Dynamic:
5336 case CK_ToUnion:
5337 case CK_ArrayToPointerDecay:
5338 case CK_FunctionToPointerDecay:
5339 case CK_NullToPointer:
5340 case CK_NullToMemberPointer:
5341 case CK_BaseToDerivedMemberPointer:
5342 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005343 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005344 case CK_ConstructorConversion:
5345 case CK_IntegralToPointer:
5346 case CK_ToVoid:
5347 case CK_VectorSplat:
5348 case CK_IntegralToFloating:
5349 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005350 case CK_CPointerToObjCPointerCast:
5351 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005352 case CK_AnyPointerToBlockPointerCast:
5353 case CK_ObjCObjectLValueCast:
5354 case CK_FloatingRealToComplex:
5355 case CK_FloatingComplexToReal:
5356 case CK_FloatingComplexCast:
5357 case CK_FloatingComplexToIntegralComplex:
5358 case CK_IntegralRealToComplex:
5359 case CK_IntegralComplexCast:
5360 case CK_IntegralComplexToFloatingComplex:
5361 llvm_unreachable("invalid cast kind for integral value");
5362
Eli Friedmane50c2972011-03-25 19:07:11 +00005363 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005364 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005365 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005366 case CK_ARCProduceObject:
5367 case CK_ARCConsumeObject:
5368 case CK_ARCReclaimReturnedObject:
5369 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005370 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005371 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005372
Richard Smith7d580a42012-01-17 21:17:26 +00005373 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005374 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005375 case CK_AtomicToNonAtomic:
5376 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005377 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005378 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005379
5380 case CK_MemberPointerToBoolean:
5381 case CK_PointerToBoolean:
5382 case CK_IntegralToBoolean:
5383 case CK_FloatingToBoolean:
5384 case CK_FloatingComplexToBoolean:
5385 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005386 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005387 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005388 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005389 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005390 }
5391
Eli Friedman46a52322011-03-25 00:43:55 +00005392 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005393 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005394 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005395
Eli Friedmanbe265702009-02-20 01:15:07 +00005396 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005397 // Allow casts of address-of-label differences if they are no-ops
5398 // or narrowing. (The narrowing case isn't actually guaranteed to
5399 // be constant-evaluatable except in some narrow cases which are hard
5400 // to detect here. We let it through on the assumption the user knows
5401 // what they are doing.)
5402 if (Result.isAddrLabelDiff())
5403 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005404 // Only allow casts of lvalues if they are lossless.
5405 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5406 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005407
Richard Smithf72fccf2012-01-30 22:27:01 +00005408 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5409 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005410 }
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Eli Friedman46a52322011-03-25 00:43:55 +00005412 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005413 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5414
John McCallefdb83e2010-05-07 21:00:08 +00005415 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005416 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005417 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005418
Daniel Dunbardd211642009-02-19 22:24:01 +00005419 if (LV.getLValueBase()) {
5420 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005421 // FIXME: Allow a larger integer size than the pointer size, and allow
5422 // narrowing back down to pointer width in subsequent integral casts.
5423 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005424 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005425 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005426
Richard Smithb755a9d2011-11-16 07:18:12 +00005427 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005428 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005429 return true;
5430 }
5431
Ken Dycka7305832010-01-15 12:37:54 +00005432 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5433 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005434 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005435 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005436
Eli Friedman46a52322011-03-25 00:43:55 +00005437 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005438 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005439 if (!EvaluateComplex(SubExpr, C, Info))
5440 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005441 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005442 }
Eli Friedman2217c872009-02-22 11:46:18 +00005443
Eli Friedman46a52322011-03-25 00:43:55 +00005444 case CK_FloatingToIntegral: {
5445 APFloat F(0.0);
5446 if (!EvaluateFloat(SubExpr, F, Info))
5447 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005448
Richard Smithc1c5f272011-12-13 06:39:58 +00005449 APSInt Value;
5450 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5451 return false;
5452 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005453 }
5454 }
Mike Stump1eb44332009-09-09 15:08:12 +00005455
Eli Friedman46a52322011-03-25 00:43:55 +00005456 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005457}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005458
Eli Friedman722c7172009-02-28 03:59:05 +00005459bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5460 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005461 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005462 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5463 return false;
5464 if (!LV.isComplexInt())
5465 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005466 return Success(LV.getComplexIntReal(), E);
5467 }
5468
5469 return Visit(E->getSubExpr());
5470}
5471
Eli Friedman664a1042009-02-27 04:45:43 +00005472bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005473 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005474 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005475 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5476 return false;
5477 if (!LV.isComplexInt())
5478 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005479 return Success(LV.getComplexIntImag(), E);
5480 }
5481
Richard Smith8327fad2011-10-24 18:44:57 +00005482 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005483 return Success(0, E);
5484}
5485
Douglas Gregoree8aff02011-01-04 17:33:58 +00005486bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5487 return Success(E->getPackLength(), E);
5488}
5489
Sebastian Redl295995c2010-09-10 20:55:47 +00005490bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5491 return Success(E->getValue(), E);
5492}
5493
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005494//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005495// Float Evaluation
5496//===----------------------------------------------------------------------===//
5497
5498namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005499class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005500 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005501 APFloat &Result;
5502public:
5503 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005504 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005505
Richard Smith1aa0be82012-03-03 22:46:17 +00005506 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005507 Result = V.getFloat();
5508 return true;
5509 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005510
Richard Smith51201882011-12-30 21:15:51 +00005511 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005512 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5513 return true;
5514 }
5515
Chris Lattner019f4e82008-10-06 05:28:25 +00005516 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005518 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005519 bool VisitBinaryOperator(const BinaryOperator *E);
5520 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005521 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005522
John McCallabd3a852010-05-07 22:08:54 +00005523 bool VisitUnaryReal(const UnaryOperator *E);
5524 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005525
Richard Smith51201882011-12-30 21:15:51 +00005526 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005527};
5528} // end anonymous namespace
5529
5530static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005531 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005532 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533}
5534
Jay Foad4ba2a172011-01-12 09:06:06 +00005535static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005536 QualType ResultTy,
5537 const Expr *Arg,
5538 bool SNaN,
5539 llvm::APFloat &Result) {
5540 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5541 if (!S) return false;
5542
5543 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5544
5545 llvm::APInt fill;
5546
5547 // Treat empty strings as if they were zero.
5548 if (S->getString().empty())
5549 fill = llvm::APInt(32, 0);
5550 else if (S->getString().getAsInteger(0, fill))
5551 return false;
5552
5553 if (SNaN)
5554 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5555 else
5556 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5557 return true;
5558}
5559
Chris Lattner019f4e82008-10-06 05:28:25 +00005560bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005561 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005562 default:
5563 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5564
Chris Lattner019f4e82008-10-06 05:28:25 +00005565 case Builtin::BI__builtin_huge_val:
5566 case Builtin::BI__builtin_huge_valf:
5567 case Builtin::BI__builtin_huge_vall:
5568 case Builtin::BI__builtin_inf:
5569 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005570 case Builtin::BI__builtin_infl: {
5571 const llvm::fltSemantics &Sem =
5572 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005573 Result = llvm::APFloat::getInf(Sem);
5574 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005575 }
Mike Stump1eb44332009-09-09 15:08:12 +00005576
John McCalldb7b72a2010-02-28 13:00:19 +00005577 case Builtin::BI__builtin_nans:
5578 case Builtin::BI__builtin_nansf:
5579 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005580 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5581 true, Result))
5582 return Error(E);
5583 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005584
Chris Lattner9e621712008-10-06 06:31:58 +00005585 case Builtin::BI__builtin_nan:
5586 case Builtin::BI__builtin_nanf:
5587 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005588 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005589 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005590 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5591 false, Result))
5592 return Error(E);
5593 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005594
5595 case Builtin::BI__builtin_fabs:
5596 case Builtin::BI__builtin_fabsf:
5597 case Builtin::BI__builtin_fabsl:
5598 if (!EvaluateFloat(E->getArg(0), Result, Info))
5599 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005600
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005601 if (Result.isNegative())
5602 Result.changeSign();
5603 return true;
5604
Mike Stump1eb44332009-09-09 15:08:12 +00005605 case Builtin::BI__builtin_copysign:
5606 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005607 case Builtin::BI__builtin_copysignl: {
5608 APFloat RHS(0.);
5609 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5610 !EvaluateFloat(E->getArg(1), RHS, Info))
5611 return false;
5612 Result.copySign(RHS);
5613 return true;
5614 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005615 }
5616}
5617
John McCallabd3a852010-05-07 22:08:54 +00005618bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005619 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5620 ComplexValue CV;
5621 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5622 return false;
5623 Result = CV.FloatReal;
5624 return true;
5625 }
5626
5627 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005628}
5629
5630bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005631 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5632 ComplexValue CV;
5633 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5634 return false;
5635 Result = CV.FloatImag;
5636 return true;
5637 }
5638
Richard Smith8327fad2011-10-24 18:44:57 +00005639 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005640 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5641 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005642 return true;
5643}
5644
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005645bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005646 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005647 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005648 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005649 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005650 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005651 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5652 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005653 Result.changeSign();
5654 return true;
5655 }
5656}
Chris Lattner019f4e82008-10-06 05:28:25 +00005657
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005658bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005659 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5660 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005661
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005662 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005663 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5664 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005665 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005666 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005667 return false;
5668
5669 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005670 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005671 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005672 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005673 break;
John McCall2de56d12010-08-25 11:45:40 +00005674 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005675 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005676 break;
John McCall2de56d12010-08-25 11:45:40 +00005677 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005678 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005679 break;
John McCall2de56d12010-08-25 11:45:40 +00005680 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005682 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005683 }
Richard Smith7b48a292012-02-01 05:53:12 +00005684
5685 if (Result.isInfinity() || Result.isNaN())
5686 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5687 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005688}
5689
5690bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5691 Result = E->getValue();
5692 return true;
5693}
5694
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005695bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5696 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Eli Friedman2a523ee2011-03-25 00:54:52 +00005698 switch (E->getCastKind()) {
5699 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005700 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005701
5702 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005703 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005704 return EvaluateInteger(SubExpr, IntResult, Info) &&
5705 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5706 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005707 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005708
5709 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005710 if (!Visit(SubExpr))
5711 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005712 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5713 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005714 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005715
Eli Friedman2a523ee2011-03-25 00:54:52 +00005716 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005717 ComplexValue V;
5718 if (!EvaluateComplex(SubExpr, V, Info))
5719 return false;
5720 Result = V.getComplexFloatReal();
5721 return true;
5722 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005723 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005724}
5725
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005726//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005727// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005728//===----------------------------------------------------------------------===//
5729
5730namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005731class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005732 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005733 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005734
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005735public:
John McCallf4cf1a12010-05-07 17:22:02 +00005736 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005737 : ExprEvaluatorBaseTy(info), Result(Result) {}
5738
Richard Smith1aa0be82012-03-03 22:46:17 +00005739 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005740 Result.setFrom(V);
5741 return true;
5742 }
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Eli Friedman7ead5c72012-01-10 04:58:17 +00005744 bool ZeroInitialization(const Expr *E);
5745
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005746 //===--------------------------------------------------------------------===//
5747 // Visitor Methods
5748 //===--------------------------------------------------------------------===//
5749
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005750 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005751 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005752 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005753 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005754 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005755};
5756} // end anonymous namespace
5757
John McCallf4cf1a12010-05-07 17:22:02 +00005758static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5759 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005760 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005761 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005762}
5763
Eli Friedman7ead5c72012-01-10 04:58:17 +00005764bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005765 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005766 if (ElemTy->isRealFloatingType()) {
5767 Result.makeComplexFloat();
5768 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5769 Result.FloatReal = Zero;
5770 Result.FloatImag = Zero;
5771 } else {
5772 Result.makeComplexInt();
5773 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5774 Result.IntReal = Zero;
5775 Result.IntImag = Zero;
5776 }
5777 return true;
5778}
5779
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005780bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5781 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005782
5783 if (SubExpr->getType()->isRealFloatingType()) {
5784 Result.makeComplexFloat();
5785 APFloat &Imag = Result.FloatImag;
5786 if (!EvaluateFloat(SubExpr, Imag, Info))
5787 return false;
5788
5789 Result.FloatReal = APFloat(Imag.getSemantics());
5790 return true;
5791 } else {
5792 assert(SubExpr->getType()->isIntegerType() &&
5793 "Unexpected imaginary literal.");
5794
5795 Result.makeComplexInt();
5796 APSInt &Imag = Result.IntImag;
5797 if (!EvaluateInteger(SubExpr, Imag, Info))
5798 return false;
5799
5800 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5801 return true;
5802 }
5803}
5804
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005805bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005806
John McCall8786da72010-12-14 17:51:41 +00005807 switch (E->getCastKind()) {
5808 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005809 case CK_BaseToDerived:
5810 case CK_DerivedToBase:
5811 case CK_UncheckedDerivedToBase:
5812 case CK_Dynamic:
5813 case CK_ToUnion:
5814 case CK_ArrayToPointerDecay:
5815 case CK_FunctionToPointerDecay:
5816 case CK_NullToPointer:
5817 case CK_NullToMemberPointer:
5818 case CK_BaseToDerivedMemberPointer:
5819 case CK_DerivedToBaseMemberPointer:
5820 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005821 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005822 case CK_ConstructorConversion:
5823 case CK_IntegralToPointer:
5824 case CK_PointerToIntegral:
5825 case CK_PointerToBoolean:
5826 case CK_ToVoid:
5827 case CK_VectorSplat:
5828 case CK_IntegralCast:
5829 case CK_IntegralToBoolean:
5830 case CK_IntegralToFloating:
5831 case CK_FloatingToIntegral:
5832 case CK_FloatingToBoolean:
5833 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005834 case CK_CPointerToObjCPointerCast:
5835 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005836 case CK_AnyPointerToBlockPointerCast:
5837 case CK_ObjCObjectLValueCast:
5838 case CK_FloatingComplexToReal:
5839 case CK_FloatingComplexToBoolean:
5840 case CK_IntegralComplexToReal:
5841 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005842 case CK_ARCProduceObject:
5843 case CK_ARCConsumeObject:
5844 case CK_ARCReclaimReturnedObject:
5845 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005846 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005847 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005848
John McCall8786da72010-12-14 17:51:41 +00005849 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005850 case CK_AtomicToNonAtomic:
5851 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005852 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005853 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005854
5855 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005856 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005857 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005858 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005859
5860 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005861 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005862 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005863 return false;
5864
John McCall8786da72010-12-14 17:51:41 +00005865 Result.makeComplexFloat();
5866 Result.FloatImag = APFloat(Real.getSemantics());
5867 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005868 }
5869
John McCall8786da72010-12-14 17:51:41 +00005870 case CK_FloatingComplexCast: {
5871 if (!Visit(E->getSubExpr()))
5872 return false;
5873
5874 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5875 QualType From
5876 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5877
Richard Smithc1c5f272011-12-13 06:39:58 +00005878 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5879 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005880 }
5881
5882 case CK_FloatingComplexToIntegralComplex: {
5883 if (!Visit(E->getSubExpr()))
5884 return false;
5885
5886 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5887 QualType From
5888 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5889 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005890 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5891 To, Result.IntReal) &&
5892 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5893 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005894 }
5895
5896 case CK_IntegralRealToComplex: {
5897 APSInt &Real = Result.IntReal;
5898 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5899 return false;
5900
5901 Result.makeComplexInt();
5902 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5903 return true;
5904 }
5905
5906 case CK_IntegralComplexCast: {
5907 if (!Visit(E->getSubExpr()))
5908 return false;
5909
5910 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5911 QualType From
5912 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5913
Richard Smithf72fccf2012-01-30 22:27:01 +00005914 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5915 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005916 return true;
5917 }
5918
5919 case CK_IntegralComplexToFloatingComplex: {
5920 if (!Visit(E->getSubExpr()))
5921 return false;
5922
5923 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5924 QualType From
5925 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5926 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005927 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5928 To, Result.FloatReal) &&
5929 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5930 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005931 }
5932 }
5933
5934 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005935}
5936
John McCallf4cf1a12010-05-07 17:22:02 +00005937bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005938 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005939 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5940
Richard Smith745f5142012-01-27 01:14:48 +00005941 bool LHSOK = Visit(E->getLHS());
5942 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005943 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005944
John McCallf4cf1a12010-05-07 17:22:02 +00005945 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005946 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005947 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005948
Daniel Dunbar3f279872009-01-29 01:32:56 +00005949 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5950 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005951 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005952 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005953 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005954 if (Result.isComplexFloat()) {
5955 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5956 APFloat::rmNearestTiesToEven);
5957 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5958 APFloat::rmNearestTiesToEven);
5959 } else {
5960 Result.getComplexIntReal() += RHS.getComplexIntReal();
5961 Result.getComplexIntImag() += RHS.getComplexIntImag();
5962 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005963 break;
John McCall2de56d12010-08-25 11:45:40 +00005964 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005965 if (Result.isComplexFloat()) {
5966 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5967 APFloat::rmNearestTiesToEven);
5968 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5969 APFloat::rmNearestTiesToEven);
5970 } else {
5971 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5972 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5973 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005974 break;
John McCall2de56d12010-08-25 11:45:40 +00005975 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005976 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005977 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005978 APFloat &LHS_r = LHS.getComplexFloatReal();
5979 APFloat &LHS_i = LHS.getComplexFloatImag();
5980 APFloat &RHS_r = RHS.getComplexFloatReal();
5981 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005982
Daniel Dunbar3f279872009-01-29 01:32:56 +00005983 APFloat Tmp = LHS_r;
5984 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5985 Result.getComplexFloatReal() = Tmp;
5986 Tmp = LHS_i;
5987 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5988 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5989
5990 Tmp = LHS_r;
5991 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5992 Result.getComplexFloatImag() = Tmp;
5993 Tmp = LHS_i;
5994 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5995 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5996 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005997 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005998 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005999 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6000 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006001 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006002 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6003 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6004 }
6005 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006006 case BO_Div:
6007 if (Result.isComplexFloat()) {
6008 ComplexValue LHS = Result;
6009 APFloat &LHS_r = LHS.getComplexFloatReal();
6010 APFloat &LHS_i = LHS.getComplexFloatImag();
6011 APFloat &RHS_r = RHS.getComplexFloatReal();
6012 APFloat &RHS_i = RHS.getComplexFloatImag();
6013 APFloat &Res_r = Result.getComplexFloatReal();
6014 APFloat &Res_i = Result.getComplexFloatImag();
6015
6016 APFloat Den = RHS_r;
6017 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6018 APFloat Tmp = RHS_i;
6019 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6020 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6021
6022 Res_r = LHS_r;
6023 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6024 Tmp = LHS_i;
6025 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6026 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6027 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6028
6029 Res_i = LHS_i;
6030 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6031 Tmp = LHS_r;
6032 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6033 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6034 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6035 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006036 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6037 return Error(E, diag::note_expr_divide_by_zero);
6038
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006039 ComplexValue LHS = Result;
6040 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6041 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6042 Result.getComplexIntReal() =
6043 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6044 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6045 Result.getComplexIntImag() =
6046 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6047 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6048 }
6049 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006050 }
6051
John McCallf4cf1a12010-05-07 17:22:02 +00006052 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006053}
6054
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006055bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6056 // Get the operand value into 'Result'.
6057 if (!Visit(E->getSubExpr()))
6058 return false;
6059
6060 switch (E->getOpcode()) {
6061 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006062 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006063 case UO_Extension:
6064 return true;
6065 case UO_Plus:
6066 // The result is always just the subexpr.
6067 return true;
6068 case UO_Minus:
6069 if (Result.isComplexFloat()) {
6070 Result.getComplexFloatReal().changeSign();
6071 Result.getComplexFloatImag().changeSign();
6072 }
6073 else {
6074 Result.getComplexIntReal() = -Result.getComplexIntReal();
6075 Result.getComplexIntImag() = -Result.getComplexIntImag();
6076 }
6077 return true;
6078 case UO_Not:
6079 if (Result.isComplexFloat())
6080 Result.getComplexFloatImag().changeSign();
6081 else
6082 Result.getComplexIntImag() = -Result.getComplexIntImag();
6083 return true;
6084 }
6085}
6086
Eli Friedman7ead5c72012-01-10 04:58:17 +00006087bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6088 if (E->getNumInits() == 2) {
6089 if (E->getType()->isComplexType()) {
6090 Result.makeComplexFloat();
6091 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6092 return false;
6093 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6094 return false;
6095 } else {
6096 Result.makeComplexInt();
6097 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6098 return false;
6099 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6100 return false;
6101 }
6102 return true;
6103 }
6104 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6105}
6106
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006107//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006108// Void expression evaluation, primarily for a cast to void on the LHS of a
6109// comma operator
6110//===----------------------------------------------------------------------===//
6111
6112namespace {
6113class VoidExprEvaluator
6114 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6115public:
6116 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6117
Richard Smith1aa0be82012-03-03 22:46:17 +00006118 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006119
6120 bool VisitCastExpr(const CastExpr *E) {
6121 switch (E->getCastKind()) {
6122 default:
6123 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6124 case CK_ToVoid:
6125 VisitIgnoredValue(E->getSubExpr());
6126 return true;
6127 }
6128 }
6129};
6130} // end anonymous namespace
6131
6132static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6133 assert(E->isRValue() && E->getType()->isVoidType());
6134 return VoidExprEvaluator(Info).Visit(E);
6135}
6136
6137//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006138// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006139//===----------------------------------------------------------------------===//
6140
Richard Smith1aa0be82012-03-03 22:46:17 +00006141static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006142 // In C, function designators are not lvalues, but we evaluate them as if they
6143 // are.
6144 if (E->isGLValue() || E->getType()->isFunctionType()) {
6145 LValue LV;
6146 if (!EvaluateLValue(E, LV, Info))
6147 return false;
6148 LV.moveInto(Result);
6149 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006150 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006151 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006152 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006153 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006154 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006155 } else if (E->getType()->hasPointerRepresentation()) {
6156 LValue LV;
6157 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006158 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006159 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006160 } else if (E->getType()->isRealFloatingType()) {
6161 llvm::APFloat F(0.0);
6162 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006163 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006164 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006165 } else if (E->getType()->isAnyComplexType()) {
6166 ComplexValue C;
6167 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006168 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006169 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006170 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006171 MemberPtr P;
6172 if (!EvaluateMemberPointer(E, P, Info))
6173 return false;
6174 P.moveInto(Result);
6175 return true;
Richard Smith51201882011-12-30 21:15:51 +00006176 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006177 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006178 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006179 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006180 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006181 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006182 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006183 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006184 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006185 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6186 return false;
6187 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006188 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006189 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006190 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006191 << E->getType();
6192 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006193 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006194 if (!EvaluateVoid(E, Info))
6195 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006196 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006197 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006198 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006199 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006200 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006201 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006202 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006203
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006204 return true;
6205}
6206
Richard Smith83587db2012-02-15 02:18:13 +00006207/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6208/// cases, the in-place evaluation is essential, since later initializers for
6209/// an object can indirectly refer to subobjects which were initialized earlier.
6210static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6211 const Expr *E, CheckConstantExpressionKind CCEK,
6212 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006213 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006214 return false;
6215
6216 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006217 // Evaluate arrays and record types in-place, so that later initializers can
6218 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006219 if (E->getType()->isArrayType())
6220 return EvaluateArray(E, This, Result, Info);
6221 else if (E->getType()->isRecordType())
6222 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006223 }
6224
6225 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006226 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006227}
6228
Richard Smithf48fdb02011-12-09 22:58:01 +00006229/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6230/// lvalue-to-rvalue cast if it is an lvalue.
6231static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006232 if (!CheckLiteralType(Info, E))
6233 return false;
6234
Richard Smith1aa0be82012-03-03 22:46:17 +00006235 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006236 return false;
6237
6238 if (E->isGLValue()) {
6239 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006240 LV.setFrom(Info.Ctx, Result);
6241 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006242 return false;
6243 }
6244
Richard Smith1aa0be82012-03-03 22:46:17 +00006245 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006246 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006247}
Richard Smithc49bd112011-10-28 17:51:58 +00006248
Richard Smith51f47082011-10-29 00:50:52 +00006249/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006250/// any crazy technique (that has nothing to do with language standards) that
6251/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006252/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6253/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006254bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006255 // Fast-path evaluations of integer literals, since we sometimes see files
6256 // containing vast quantities of these.
6257 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6258 Result.Val = APValue(APSInt(L->getValue(),
6259 L->getType()->isUnsignedIntegerType()));
6260 return true;
6261 }
6262
Richard Smith2d6a5672012-01-14 04:30:29 +00006263 // FIXME: Evaluating values of large array and record types can cause
6264 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006265 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006266 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006267 return false;
6268
Richard Smithf48fdb02011-12-09 22:58:01 +00006269 EvalInfo Info(Ctx, Result);
6270 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006271}
6272
Jay Foad4ba2a172011-01-12 09:06:06 +00006273bool Expr::EvaluateAsBooleanCondition(bool &Result,
6274 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006275 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006276 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006277 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006278}
6279
Richard Smith80d4b552011-12-28 19:48:30 +00006280bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6281 SideEffectsKind AllowSideEffects) const {
6282 if (!getType()->isIntegralOrEnumerationType())
6283 return false;
6284
Richard Smithc49bd112011-10-28 17:51:58 +00006285 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006286 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6287 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006288 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006289
Richard Smithc49bd112011-10-28 17:51:58 +00006290 Result = ExprResult.Val.getInt();
6291 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006292}
6293
Jay Foad4ba2a172011-01-12 09:06:06 +00006294bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006295 EvalInfo Info(Ctx, Result);
6296
John McCallefdb83e2010-05-07 21:00:08 +00006297 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006298 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6299 !CheckLValueConstantExpression(Info, getExprLoc(),
6300 Ctx.getLValueReferenceType(getType()), LV))
6301 return false;
6302
Richard Smith1aa0be82012-03-03 22:46:17 +00006303 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006304 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006305}
6306
Richard Smith099e7f62011-12-19 06:19:21 +00006307bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6308 const VarDecl *VD,
6309 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006310 // FIXME: Evaluating initializers for large array and record types can cause
6311 // performance problems. Only do so in C++11 for now.
6312 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006313 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006314 return false;
6315
Richard Smith099e7f62011-12-19 06:19:21 +00006316 Expr::EvalStatus EStatus;
6317 EStatus.Diag = &Notes;
6318
6319 EvalInfo InitInfo(Ctx, EStatus);
6320 InitInfo.setEvaluatingDecl(VD, Value);
6321
6322 LValue LVal;
6323 LVal.set(VD);
6324
Richard Smith51201882011-12-30 21:15:51 +00006325 // C++11 [basic.start.init]p2:
6326 // Variables with static storage duration or thread storage duration shall be
6327 // zero-initialized before any other initialization takes place.
6328 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006329 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006330 !VD->getType()->isReferenceType()) {
6331 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006332 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6333 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006334 return false;
6335 }
6336
Richard Smith83587db2012-02-15 02:18:13 +00006337 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6338 /*AllowNonLiteralTypes=*/true) ||
6339 EStatus.HasSideEffects)
6340 return false;
6341
6342 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6343 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006344}
6345
Richard Smith51f47082011-10-29 00:50:52 +00006346/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6347/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006348bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006349 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006350 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006351}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006352
Jay Foad4ba2a172011-01-12 09:06:06 +00006353bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006354 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006355}
6356
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006357APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006358 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006359 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006360 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006361 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006362 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006363
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006364 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006365}
John McCalld905f5a2010-05-07 05:32:02 +00006366
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006367 bool Expr::EvalResult::isGlobalLValue() const {
6368 assert(Val.isLValue());
6369 return IsGlobalLValue(Val.getLValueBase());
6370 }
6371
6372
John McCalld905f5a2010-05-07 05:32:02 +00006373/// isIntegerConstantExpr - this recursive routine will test if an expression is
6374/// an integer constant expression.
6375
6376/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6377/// comma, etc
6378///
6379/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6380/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6381/// cast+dereference.
6382
6383// CheckICE - This function does the fundamental ICE checking: the returned
6384// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6385// Note that to reduce code duplication, this helper does no evaluation
6386// itself; the caller checks whether the expression is evaluatable, and
6387// in the rare cases where CheckICE actually cares about the evaluated
6388// value, it calls into Evalute.
6389//
6390// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006391// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006392// 1: This expression is not an ICE, but if it isn't evaluated, it's
6393// a legal subexpression for an ICE. This return value is used to handle
6394// the comma operator in C99 mode.
6395// 2: This expression is not an ICE, and is not a legal subexpression for one.
6396
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006397namespace {
6398
John McCalld905f5a2010-05-07 05:32:02 +00006399struct ICEDiag {
6400 unsigned Val;
6401 SourceLocation Loc;
6402
6403 public:
6404 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6405 ICEDiag() : Val(0) {}
6406};
6407
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006408}
6409
6410static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006411
6412static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6413 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006414 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006415 !EVResult.Val.isInt()) {
6416 return ICEDiag(2, E->getLocStart());
6417 }
6418 return NoDiag();
6419}
6420
6421static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6422 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006423 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006424 return ICEDiag(2, E->getLocStart());
6425 }
6426
6427 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006428#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006429#define STMT(Node, Base) case Expr::Node##Class:
6430#define EXPR(Node, Base)
6431#include "clang/AST/StmtNodes.inc"
6432 case Expr::PredefinedExprClass:
6433 case Expr::FloatingLiteralClass:
6434 case Expr::ImaginaryLiteralClass:
6435 case Expr::StringLiteralClass:
6436 case Expr::ArraySubscriptExprClass:
6437 case Expr::MemberExprClass:
6438 case Expr::CompoundAssignOperatorClass:
6439 case Expr::CompoundLiteralExprClass:
6440 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006441 case Expr::DesignatedInitExprClass:
6442 case Expr::ImplicitValueInitExprClass:
6443 case Expr::ParenListExprClass:
6444 case Expr::VAArgExprClass:
6445 case Expr::AddrLabelExprClass:
6446 case Expr::StmtExprClass:
6447 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006448 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006449 case Expr::CXXDynamicCastExprClass:
6450 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006451 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006452 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006453 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006454 case Expr::CXXThisExprClass:
6455 case Expr::CXXThrowExprClass:
6456 case Expr::CXXNewExprClass:
6457 case Expr::CXXDeleteExprClass:
6458 case Expr::CXXPseudoDestructorExprClass:
6459 case Expr::UnresolvedLookupExprClass:
6460 case Expr::DependentScopeDeclRefExprClass:
6461 case Expr::CXXConstructExprClass:
6462 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006463 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006464 case Expr::CXXTemporaryObjectExprClass:
6465 case Expr::CXXUnresolvedConstructExprClass:
6466 case Expr::CXXDependentScopeMemberExprClass:
6467 case Expr::UnresolvedMemberExprClass:
6468 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006469 case Expr::ObjCNumericLiteralClass:
6470 case Expr::ObjCArrayLiteralClass:
6471 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006472 case Expr::ObjCEncodeExprClass:
6473 case Expr::ObjCMessageExprClass:
6474 case Expr::ObjCSelectorExprClass:
6475 case Expr::ObjCProtocolExprClass:
6476 case Expr::ObjCIvarRefExprClass:
6477 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006478 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006479 case Expr::ObjCIsaExprClass:
6480 case Expr::ShuffleVectorExprClass:
6481 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006482 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006483 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006484 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006485 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006486 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006487 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006488 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006489 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006490 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006491 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006492 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006493 return ICEDiag(2, E->getLocStart());
6494
Douglas Gregoree8aff02011-01-04 17:33:58 +00006495 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006496 case Expr::GNUNullExprClass:
6497 // GCC considers the GNU __null value to be an integral constant expression.
6498 return NoDiag();
6499
John McCall91a57552011-07-15 05:09:51 +00006500 case Expr::SubstNonTypeTemplateParmExprClass:
6501 return
6502 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6503
John McCalld905f5a2010-05-07 05:32:02 +00006504 case Expr::ParenExprClass:
6505 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006506 case Expr::GenericSelectionExprClass:
6507 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006508 case Expr::IntegerLiteralClass:
6509 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006510 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006512 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006513 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006514 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006515 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006516 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006517 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006518 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006519 return NoDiag();
6520 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006521 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006522 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6523 // constant expressions, but they can never be ICEs because an ICE cannot
6524 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006525 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006526 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006527 return CheckEvalInICE(E, Ctx);
6528 return ICEDiag(2, E->getLocStart());
6529 }
Richard Smith359c89d2012-02-24 22:12:32 +00006530 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006531 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6532 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006533 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006534 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006535 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006536 // Parameter variables are never constants. Without this check,
6537 // getAnyInitializer() can find a default argument, which leads
6538 // to chaos.
6539 if (isa<ParmVarDecl>(D))
6540 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6541
6542 // C++ 7.1.5.1p2
6543 // A variable of non-volatile const-qualified integral or enumeration
6544 // type initialized by an ICE can be used in ICEs.
6545 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006546 if (!Dcl->getType()->isIntegralOrEnumerationType())
6547 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6548
Richard Smith099e7f62011-12-19 06:19:21 +00006549 const VarDecl *VD;
6550 // Look for a declaration of this variable that has an initializer, and
6551 // check whether it is an ICE.
6552 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6553 return NoDiag();
6554 else
6555 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006556 }
6557 }
6558 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006559 }
John McCalld905f5a2010-05-07 05:32:02 +00006560 case Expr::UnaryOperatorClass: {
6561 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6562 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006563 case UO_PostInc:
6564 case UO_PostDec:
6565 case UO_PreInc:
6566 case UO_PreDec:
6567 case UO_AddrOf:
6568 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006569 // C99 6.6/3 allows increment and decrement within unevaluated
6570 // subexpressions of constant expressions, but they can never be ICEs
6571 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006572 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006573 case UO_Extension:
6574 case UO_LNot:
6575 case UO_Plus:
6576 case UO_Minus:
6577 case UO_Not:
6578 case UO_Real:
6579 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006580 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006581 }
6582
6583 // OffsetOf falls through here.
6584 }
6585 case Expr::OffsetOfExprClass: {
6586 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006587 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006588 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006589 // compliance: we should warn earlier for offsetof expressions with
6590 // array subscripts that aren't ICEs, and if the array subscripts
6591 // are ICEs, the value of the offsetof must be an integer constant.
6592 return CheckEvalInICE(E, Ctx);
6593 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006594 case Expr::UnaryExprOrTypeTraitExprClass: {
6595 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6596 if ((Exp->getKind() == UETT_SizeOf) &&
6597 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006598 return ICEDiag(2, E->getLocStart());
6599 return NoDiag();
6600 }
6601 case Expr::BinaryOperatorClass: {
6602 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6603 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006604 case BO_PtrMemD:
6605 case BO_PtrMemI:
6606 case BO_Assign:
6607 case BO_MulAssign:
6608 case BO_DivAssign:
6609 case BO_RemAssign:
6610 case BO_AddAssign:
6611 case BO_SubAssign:
6612 case BO_ShlAssign:
6613 case BO_ShrAssign:
6614 case BO_AndAssign:
6615 case BO_XorAssign:
6616 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006617 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6618 // constant expressions, but they can never be ICEs because an ICE cannot
6619 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006620 return ICEDiag(2, E->getLocStart());
6621
John McCall2de56d12010-08-25 11:45:40 +00006622 case BO_Mul:
6623 case BO_Div:
6624 case BO_Rem:
6625 case BO_Add:
6626 case BO_Sub:
6627 case BO_Shl:
6628 case BO_Shr:
6629 case BO_LT:
6630 case BO_GT:
6631 case BO_LE:
6632 case BO_GE:
6633 case BO_EQ:
6634 case BO_NE:
6635 case BO_And:
6636 case BO_Xor:
6637 case BO_Or:
6638 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006639 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6640 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006641 if (Exp->getOpcode() == BO_Div ||
6642 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006643 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006644 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006645 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006646 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006647 if (REval == 0)
6648 return ICEDiag(1, E->getLocStart());
6649 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006650 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006651 if (LEval.isMinSignedValue())
6652 return ICEDiag(1, E->getLocStart());
6653 }
6654 }
6655 }
John McCall2de56d12010-08-25 11:45:40 +00006656 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006657 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006658 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6659 // if it isn't evaluated.
6660 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6661 return ICEDiag(1, E->getLocStart());
6662 } else {
6663 // In both C89 and C++, commas in ICEs are illegal.
6664 return ICEDiag(2, E->getLocStart());
6665 }
6666 }
6667 if (LHSResult.Val >= RHSResult.Val)
6668 return LHSResult;
6669 return RHSResult;
6670 }
John McCall2de56d12010-08-25 11:45:40 +00006671 case BO_LAnd:
6672 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006673 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6674 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6675 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6676 // Rare case where the RHS has a comma "side-effect"; we need
6677 // to actually check the condition to see whether the side
6678 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006679 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006680 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006681 return RHSResult;
6682 return NoDiag();
6683 }
6684
6685 if (LHSResult.Val >= RHSResult.Val)
6686 return LHSResult;
6687 return RHSResult;
6688 }
6689 }
6690 }
6691 case Expr::ImplicitCastExprClass:
6692 case Expr::CStyleCastExprClass:
6693 case Expr::CXXFunctionalCastExprClass:
6694 case Expr::CXXStaticCastExprClass:
6695 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006696 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006697 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006698 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006699 if (isa<ExplicitCastExpr>(E)) {
6700 if (const FloatingLiteral *FL
6701 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6702 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6703 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6704 APSInt IgnoredVal(DestWidth, !DestSigned);
6705 bool Ignored;
6706 // If the value does not fit in the destination type, the behavior is
6707 // undefined, so we are not required to treat it as a constant
6708 // expression.
6709 if (FL->getValue().convertToInteger(IgnoredVal,
6710 llvm::APFloat::rmTowardZero,
6711 &Ignored) & APFloat::opInvalidOp)
6712 return ICEDiag(2, E->getLocStart());
6713 return NoDiag();
6714 }
6715 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006716 switch (cast<CastExpr>(E)->getCastKind()) {
6717 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006718 case CK_AtomicToNonAtomic:
6719 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006720 case CK_NoOp:
6721 case CK_IntegralToBoolean:
6722 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006723 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006724 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006725 return ICEDiag(2, E->getLocStart());
6726 }
John McCalld905f5a2010-05-07 05:32:02 +00006727 }
John McCall56ca35d2011-02-17 10:25:35 +00006728 case Expr::BinaryConditionalOperatorClass: {
6729 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6730 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6731 if (CommonResult.Val == 2) return CommonResult;
6732 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6733 if (FalseResult.Val == 2) return FalseResult;
6734 if (CommonResult.Val == 1) return CommonResult;
6735 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006736 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006737 return FalseResult;
6738 }
John McCalld905f5a2010-05-07 05:32:02 +00006739 case Expr::ConditionalOperatorClass: {
6740 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6741 // If the condition (ignoring parens) is a __builtin_constant_p call,
6742 // then only the true side is actually considered in an integer constant
6743 // expression, and it is fully evaluated. This is an important GNU
6744 // extension. See GCC PR38377 for discussion.
6745 if (const CallExpr *CallCE
6746 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006747 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6748 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006749 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006750 if (CondResult.Val == 2)
6751 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006752
Richard Smithf48fdb02011-12-09 22:58:01 +00006753 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6754 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006755
John McCalld905f5a2010-05-07 05:32:02 +00006756 if (TrueResult.Val == 2)
6757 return TrueResult;
6758 if (FalseResult.Val == 2)
6759 return FalseResult;
6760 if (CondResult.Val == 1)
6761 return CondResult;
6762 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6763 return NoDiag();
6764 // Rare case where the diagnostics depend on which side is evaluated
6765 // Note that if we get here, CondResult is 0, and at least one of
6766 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006767 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006768 return FalseResult;
6769 }
6770 return TrueResult;
6771 }
6772 case Expr::CXXDefaultArgExprClass:
6773 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6774 case Expr::ChooseExprClass: {
6775 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6776 }
6777 }
6778
David Blaikie30263482012-01-20 21:50:17 +00006779 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006780}
6781
Richard Smithf48fdb02011-12-09 22:58:01 +00006782/// Evaluate an expression as a C++11 integral constant expression.
6783static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6784 const Expr *E,
6785 llvm::APSInt *Value,
6786 SourceLocation *Loc) {
6787 if (!E->getType()->isIntegralOrEnumerationType()) {
6788 if (Loc) *Loc = E->getExprLoc();
6789 return false;
6790 }
6791
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006792 APValue Result;
6793 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006794 return false;
6795
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006796 assert(Result.isInt() && "pointer cast to int is not an ICE");
6797 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006798 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006799}
6800
Richard Smithdd1f29b2011-12-12 09:28:41 +00006801bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006802 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006803 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6804
John McCalld905f5a2010-05-07 05:32:02 +00006805 ICEDiag d = CheckICE(this, Ctx);
6806 if (d.Val != 0) {
6807 if (Loc) *Loc = d.Loc;
6808 return false;
6809 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006810 return true;
6811}
6812
6813bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6814 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006815 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006816 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6817
6818 if (!isIntegerConstantExpr(Ctx, Loc))
6819 return false;
6820 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006821 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006822 return true;
6823}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006824
Richard Smith70488e22012-02-14 21:38:30 +00006825bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6826 return CheckICE(this, Ctx).Val == 0;
6827}
6828
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006829bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6830 SourceLocation *Loc) const {
6831 // We support this checking in C++98 mode in order to diagnose compatibility
6832 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006833 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006834
Richard Smith70488e22012-02-14 21:38:30 +00006835 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006836 Expr::EvalStatus Status;
6837 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6838 Status.Diag = &Diags;
6839 EvalInfo Info(Ctx, Status);
6840
6841 APValue Scratch;
6842 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6843
6844 if (!Diags.empty()) {
6845 IsConstExpr = false;
6846 if (Loc) *Loc = Diags[0].first;
6847 } else if (!IsConstExpr) {
6848 // FIXME: This shouldn't happen.
6849 if (Loc) *Loc = getExprLoc();
6850 }
6851
6852 return IsConstExpr;
6853}
Richard Smith745f5142012-01-27 01:14:48 +00006854
6855bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6856 llvm::SmallVectorImpl<
6857 PartialDiagnosticAt> &Diags) {
6858 // FIXME: It would be useful to check constexpr function templates, but at the
6859 // moment the constant expression evaluator cannot cope with the non-rigorous
6860 // ASTs which we build for dependent expressions.
6861 if (FD->isDependentContext())
6862 return true;
6863
6864 Expr::EvalStatus Status;
6865 Status.Diag = &Diags;
6866
6867 EvalInfo Info(FD->getASTContext(), Status);
6868 Info.CheckingPotentialConstantExpression = true;
6869
6870 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6871 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6872
6873 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6874 // is a temporary being used as the 'this' pointer.
6875 LValue This;
6876 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006877 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006878
Richard Smith745f5142012-01-27 01:14:48 +00006879 ArrayRef<const Expr*> Args;
6880
6881 SourceLocation Loc = FD->getLocation();
6882
Richard Smith1aa0be82012-03-03 22:46:17 +00006883 APValue Scratch;
6884 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006885 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006886 else
Richard Smith745f5142012-01-27 01:14:48 +00006887 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6888 Args, FD->getBody(), Info, Scratch);
6889
6890 return Diags.empty();
6891}