blob: 98fc0e5cf3c44274f976ecb057f386f3ebd82cfd [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 Smithfe587202012-04-15 02:50:59 +00001494/// Extract the value of a character from a string literal. CharType is used to
1495/// determine the expected signedness of the result -- a string literal used to
1496/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1497/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001498static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001499 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001500 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1501 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1502 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001503 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001504
1505 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001506 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001507 if (Index < S->getLength())
1508 Value = S->getCodeUnit(Index);
1509 return Value;
1510}
1511
Richard Smithcc5d4f62011-11-07 09:22:26 +00001512/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001513static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001514 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001515 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001516 if (Sub.Invalid)
1517 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001518 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001519 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001520 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001521 (unsigned)diag::note_constexpr_read_past_end :
1522 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001523 return false;
1524 }
Richard Smithf64699e2011-11-11 08:28:03 +00001525 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001527 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1528 // This object might be initialized later.
1529 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530
Richard Smith0069b842012-03-10 00:28:11 +00001531 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001532 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001533 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001535 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001537 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001538 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001539 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001540 // Note, it should not be possible to form a pointer with a valid
1541 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001542 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001543 (unsigned)diag::note_constexpr_read_past_end :
1544 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001546 }
Richard Smithf3908f22012-02-17 03:35:37 +00001547 // An array object is represented as either an Array APValue or as an
1548 // LValue which refers to a string literal.
1549 if (O->isLValue()) {
1550 assert(I == N - 1 && "extracting subobject of character?");
1551 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001552 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001553 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001554 return true;
1555 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001556 O = &O->getArrayInitializedElt(Index);
1557 else
1558 O = &O->getArrayFiller();
1559 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001560 } else if (ObjType->isAnyComplexType()) {
1561 // Next subobject is a complex number.
1562 uint64_t Index = Sub.Entries[I].ArrayIndex;
1563 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001564 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001565 (unsigned)diag::note_constexpr_read_past_end :
1566 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1567 return false;
1568 }
1569 assert(I == N - 1 && "extracting subobject of scalar?");
1570 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001571 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001572 : O->getComplexIntReal());
1573 } else {
1574 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001575 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001576 : O->getComplexFloatReal());
1577 }
1578 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001579 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001580 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001581 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001582 << Field;
1583 Info.Note(Field->getLocation(), diag::note_declared_at);
1584 return false;
1585 }
1586
Richard Smith180f4792011-11-10 06:34:14 +00001587 // Next subobject is a class, struct or union field.
1588 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1589 if (RD->isUnion()) {
1590 const FieldDecl *UnionField = O->getUnionField();
1591 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001592 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001593 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001594 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001595 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001596 }
Richard Smith180f4792011-11-10 06:34:14 +00001597 O = &O->getUnionValue();
1598 } else
1599 O = &O->getStructField(Field->getFieldIndex());
1600 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001601
1602 if (ObjType.isVolatileQualified()) {
1603 if (Info.getLangOpts().CPlusPlus) {
1604 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001605 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001606 << 2 << Field;
1607 Info.Note(Field->getLocation(), diag::note_declared_at);
1608 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001609 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001610 }
1611 return false;
1612 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001613 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001614 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001615 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1616 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1617 O = &O->getStructBase(getBaseIndex(Derived, Base));
1618 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001619 }
Richard Smith180f4792011-11-10 06:34:14 +00001620
Richard Smithf48fdb02011-12-09 22:58:01 +00001621 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001622 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001623 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001624 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001625 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001626 }
1627
Richard Smith0069b842012-03-10 00:28:11 +00001628 // This may look super-stupid, but it serves an important purpose: if we just
1629 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1630 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1631 // object, which is destroyed by Tmp's destructor.
1632 APValue Tmp;
1633 O->swap(Tmp);
1634 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001635 return true;
1636}
1637
Richard Smithf15fda02012-02-02 01:16:57 +00001638/// Find the position where two subobject designators diverge, or equivalently
1639/// the length of the common initial subsequence.
1640static unsigned FindDesignatorMismatch(QualType ObjType,
1641 const SubobjectDesignator &A,
1642 const SubobjectDesignator &B,
1643 bool &WasArrayIndex) {
1644 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1645 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001646 if (!ObjType.isNull() &&
1647 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001648 // Next subobject is an array element.
1649 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1650 WasArrayIndex = true;
1651 return I;
1652 }
Richard Smith86024012012-02-18 22:04:06 +00001653 if (ObjType->isAnyComplexType())
1654 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1655 else
1656 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001657 } else {
1658 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1659 WasArrayIndex = false;
1660 return I;
1661 }
1662 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1663 // Next subobject is a field.
1664 ObjType = FD->getType();
1665 else
1666 // Next subobject is a base class.
1667 ObjType = QualType();
1668 }
1669 }
1670 WasArrayIndex = false;
1671 return I;
1672}
1673
1674/// Determine whether the given subobject designators refer to elements of the
1675/// same array object.
1676static bool AreElementsOfSameArray(QualType ObjType,
1677 const SubobjectDesignator &A,
1678 const SubobjectDesignator &B) {
1679 if (A.Entries.size() != B.Entries.size())
1680 return false;
1681
1682 bool IsArray = A.MostDerivedArraySize != 0;
1683 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1684 // A is a subobject of the array element.
1685 return false;
1686
1687 // If A (and B) designates an array element, the last entry will be the array
1688 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1689 // of length 1' case, and the entire path must match.
1690 bool WasArrayIndex;
1691 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1692 return CommonLength >= A.Entries.size() - IsArray;
1693}
1694
Richard Smith180f4792011-11-10 06:34:14 +00001695/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1696/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1697/// for looking up the glvalue referred to by an entity of reference type.
1698///
1699/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001700/// \param Conv - The expression for which we are performing the conversion.
1701/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001702/// \param Type - The type we expect this conversion to produce, before
1703/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001704/// \param LVal - The glvalue on which we are attempting to perform this action.
1705/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001706static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1707 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001708 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001709 if (LVal.Designator.Invalid)
1710 // A diagnostic will have already been produced.
1711 return false;
1712
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001713 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001714
Richard Smithf48fdb02011-12-09 22:58:01 +00001715 if (!LVal.Base) {
1716 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001717 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001718 return false;
1719 }
1720
Richard Smith83587db2012-02-15 02:18:13 +00001721 CallStackFrame *Frame = 0;
1722 if (LVal.CallIndex) {
1723 Frame = Info.getCallFrame(LVal.CallIndex);
1724 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001725 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001726 NoteLValueLocation(Info, LVal.Base);
1727 return false;
1728 }
1729 }
1730
Richard Smith7098cbd2011-12-21 05:04:46 +00001731 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1732 // is not a constant expression (even if the object is non-volatile). We also
1733 // apply this rule to C++98, in order to conform to the expected 'volatile'
1734 // semantics.
1735 if (Type.isVolatileQualified()) {
1736 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001737 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001738 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001739 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001740 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001741 }
Richard Smithc49bd112011-10-28 17:51:58 +00001742
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001743 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001744 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1745 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001746 // expressions are constant expressions too. Inside constexpr functions,
1747 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001748 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001749 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001750 if (VD) {
1751 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1752 VD = VDef;
1753 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001754 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001755 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001756 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001757 }
1758
Richard Smith7098cbd2011-12-21 05:04:46 +00001759 // DR1313: If the object is volatile-qualified but the glvalue was not,
1760 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001761 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001762 if (VT.isVolatileQualified()) {
1763 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001764 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 Info.Note(VD->getLocation(), diag::note_declared_at);
1766 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001767 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001768 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001769 return false;
1770 }
1771
1772 if (!isa<ParmVarDecl>(VD)) {
1773 if (VD->isConstexpr()) {
1774 // OK, we can read this variable.
1775 } else if (VT->isIntegralOrEnumerationType()) {
1776 if (!VT.isConstQualified()) {
1777 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001778 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001779 Info.Note(VD->getLocation(), diag::note_declared_at);
1780 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001781 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001782 }
1783 return false;
1784 }
1785 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1786 // We support folding of const floating-point types, in order to make
1787 // static const data members of such types (supported as an extension)
1788 // more useful.
1789 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001790 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001791 Info.Note(VD->getLocation(), diag::note_declared_at);
1792 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001793 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001794 }
1795 } else {
1796 // FIXME: Allow folding of values of any literal type in all languages.
1797 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001798 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001799 Info.Note(VD->getLocation(), diag::note_declared_at);
1800 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001801 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001802 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001803 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001804 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001805 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001806
Richard Smithf48fdb02011-12-09 22:58:01 +00001807 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001808 return false;
1809
Richard Smith47a1eed2011-10-29 20:57:55 +00001810 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001811 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001812
1813 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1814 // conversion. This happens when the declaration and the lvalue should be
1815 // considered synonymous, for instance when initializing an array of char
1816 // from a string literal. Continue as if the initializer lvalue was the
1817 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001818 assert(RVal.getLValueOffset().isZero() &&
1819 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001820 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001821
1822 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1823 Frame = Info.getCallFrame(CallIndex);
1824 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001825 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001826 NoteLValueLocation(Info, RVal.getLValueBase());
1827 return false;
1828 }
1829 } else {
1830 Frame = 0;
1831 }
Richard Smithc49bd112011-10-28 17:51:58 +00001832 }
1833
Richard Smith7098cbd2011-12-21 05:04:46 +00001834 // Volatile temporary objects cannot be read in constant expressions.
1835 if (Base->getType().isVolatileQualified()) {
1836 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001837 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001838 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1839 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001840 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001841 }
1842 return false;
1843 }
1844
Richard Smithcc5d4f62011-11-07 09:22:26 +00001845 if (Frame) {
1846 // If this is a temporary expression with a nontrivial initializer, grab the
1847 // value from the relevant stack frame.
1848 RVal = Frame->Temporaries[Base];
1849 } else if (const CompoundLiteralExpr *CLE
1850 = dyn_cast<CompoundLiteralExpr>(Base)) {
1851 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1852 // initializer until now for such expressions. Such an expression can't be
1853 // an ICE in C, so this only matters for fold.
1854 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1855 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1856 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001857 } else if (isa<StringLiteral>(Base)) {
1858 // We represent a string literal array as an lvalue pointing at the
1859 // corresponding expression, rather than building an array of chars.
1860 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001861 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001862 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001863 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001864 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001865 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001866
Richard Smithf48fdb02011-12-09 22:58:01 +00001867 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1868 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001869}
1870
Richard Smith59efe262011-11-11 04:05:33 +00001871/// Build an lvalue for the object argument of a member function call.
1872static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1873 LValue &This) {
1874 if (Object->getType()->isPointerType())
1875 return EvaluatePointer(Object, This, Info);
1876
1877 if (Object->isGLValue())
1878 return EvaluateLValue(Object, This, Info);
1879
Richard Smithe24f5fc2011-11-17 22:56:20 +00001880 if (Object->getType()->isLiteralType())
1881 return EvaluateTemporary(Object, This, Info);
1882
1883 return false;
1884}
1885
1886/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1887/// lvalue referring to the result.
1888///
1889/// \param Info - Information about the ongoing evaluation.
1890/// \param BO - The member pointer access operation.
1891/// \param LV - Filled in with a reference to the resulting object.
1892/// \param IncludeMember - Specifies whether the member itself is included in
1893/// the resulting LValue subobject designator. This is not possible when
1894/// creating a bound member function.
1895/// \return The field or method declaration to which the member pointer refers,
1896/// or 0 if evaluation fails.
1897static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1898 const BinaryOperator *BO,
1899 LValue &LV,
1900 bool IncludeMember = true) {
1901 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1902
Richard Smith745f5142012-01-27 01:14:48 +00001903 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1904 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001905 return 0;
1906
1907 MemberPtr MemPtr;
1908 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1909 return 0;
1910
1911 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1912 // member value, the behavior is undefined.
1913 if (!MemPtr.getDecl())
1914 return 0;
1915
Richard Smith745f5142012-01-27 01:14:48 +00001916 if (!EvalObjOK)
1917 return 0;
1918
Richard Smithe24f5fc2011-11-17 22:56:20 +00001919 if (MemPtr.isDerivedMember()) {
1920 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001921 // The end of the derived-to-base path for the base object must match the
1922 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001923 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001924 LV.Designator.Entries.size())
1925 return 0;
1926 unsigned PathLengthToMember =
1927 LV.Designator.Entries.size() - MemPtr.Path.size();
1928 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1929 const CXXRecordDecl *LVDecl = getAsBaseClass(
1930 LV.Designator.Entries[PathLengthToMember + I]);
1931 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1932 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1933 return 0;
1934 }
1935
1936 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001937 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1938 PathLengthToMember))
1939 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001940 } else if (!MemPtr.Path.empty()) {
1941 // Extend the LValue path with the member pointer's path.
1942 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1943 MemPtr.Path.size() + IncludeMember);
1944
1945 // Walk down to the appropriate base class.
1946 QualType LVType = BO->getLHS()->getType();
1947 if (const PointerType *PT = LVType->getAs<PointerType>())
1948 LVType = PT->getPointeeType();
1949 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1950 assert(RD && "member pointer access on non-class-type expression");
1951 // The first class in the path is that of the lvalue.
1952 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1953 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001954 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001955 RD = Base;
1956 }
1957 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001958 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001959 }
1960
1961 // Add the member. Note that we cannot build bound member functions here.
1962 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001963 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1964 HandleLValueMember(Info, BO, LV, FD);
1965 else if (const IndirectFieldDecl *IFD =
1966 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1967 HandleLValueIndirectMember(Info, BO, LV, IFD);
1968 else
1969 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001970 }
1971
1972 return MemPtr.getDecl();
1973}
1974
1975/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1976/// the provided lvalue, which currently refers to the base object.
1977static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1978 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001979 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001980 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001981 return false;
1982
Richard Smithb4e85ed2012-01-06 16:39:00 +00001983 QualType TargetQT = E->getType();
1984 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1985 TargetQT = PT->getPointeeType();
1986
1987 // Check this cast lands within the final derived-to-base subobject path.
1988 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001989 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001990 << D.MostDerivedType << TargetQT;
1991 return false;
1992 }
1993
Richard Smithe24f5fc2011-11-17 22:56:20 +00001994 // Check the type of the final cast. We don't need to check the path,
1995 // since a cast can only be formed if the path is unique.
1996 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001997 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1998 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 if (NewEntriesSize == D.MostDerivedPathLength)
2000 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2001 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002004 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002005 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002006 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002007 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008
2009 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002011}
2012
Mike Stumpc4c90452009-10-27 22:09:17 +00002013namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002014enum EvalStmtResult {
2015 /// Evaluation failed.
2016 ESR_Failed,
2017 /// Hit a 'return' statement.
2018 ESR_Returned,
2019 /// Evaluation succeeded.
2020 ESR_Succeeded
2021};
2022}
2023
2024// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002025static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002026 const Stmt *S) {
2027 switch (S->getStmtClass()) {
2028 default:
2029 return ESR_Failed;
2030
2031 case Stmt::NullStmtClass:
2032 case Stmt::DeclStmtClass:
2033 return ESR_Succeeded;
2034
Richard Smithc1c5f272011-12-13 06:39:58 +00002035 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002036 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002037 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002038 return ESR_Failed;
2039 return ESR_Returned;
2040 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002041
2042 case Stmt::CompoundStmtClass: {
2043 const CompoundStmt *CS = cast<CompoundStmt>(S);
2044 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2045 BE = CS->body_end(); BI != BE; ++BI) {
2046 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2047 if (ESR != ESR_Succeeded)
2048 return ESR;
2049 }
2050 return ESR_Succeeded;
2051 }
2052 }
2053}
2054
Richard Smith61802452011-12-22 02:22:31 +00002055/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2056/// default constructor. If so, we'll fold it whether or not it's marked as
2057/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2058/// so we need special handling.
2059static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002060 const CXXConstructorDecl *CD,
2061 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002062 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2063 return false;
2064
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002065 // Value-initialization does not call a trivial default constructor, so such a
2066 // call is a core constant expression whether or not the constructor is
2067 // constexpr.
2068 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002069 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002070 // FIXME: If DiagDecl is an implicitly-declared special member function,
2071 // we should be much more explicit about why it's not constexpr.
2072 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2073 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2074 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002075 } else {
2076 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2077 }
2078 }
2079 return true;
2080}
2081
Richard Smithc1c5f272011-12-13 06:39:58 +00002082/// CheckConstexprFunction - Check that a function can be called in a constant
2083/// expression.
2084static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2085 const FunctionDecl *Declaration,
2086 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002087 // Potential constant expressions can contain calls to declared, but not yet
2088 // defined, constexpr functions.
2089 if (Info.CheckingPotentialConstantExpression && !Definition &&
2090 Declaration->isConstexpr())
2091 return false;
2092
Richard Smithc1c5f272011-12-13 06:39:58 +00002093 // Can we evaluate this function call?
2094 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2095 return true;
2096
2097 if (Info.getLangOpts().CPlusPlus0x) {
2098 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002099 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2100 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002101 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2102 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2103 << DiagDecl;
2104 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2105 } else {
2106 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2107 }
2108 return false;
2109}
2110
Richard Smith180f4792011-11-10 06:34:14 +00002111namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002112typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002113}
2114
2115/// EvaluateArgs - Evaluate the arguments to a function call.
2116static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2117 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002118 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002119 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002120 I != E; ++I) {
2121 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2122 // If we're checking for a potential constant expression, evaluate all
2123 // initializers even if some of them fail.
2124 if (!Info.keepEvaluatingAfterFailure())
2125 return false;
2126 Success = false;
2127 }
2128 }
2129 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002130}
2131
Richard Smithd0dccea2011-10-28 22:34:42 +00002132/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002133static bool HandleFunctionCall(SourceLocation CallLoc,
2134 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002135 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002136 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002137 ArgVector ArgValues(Args.size());
2138 if (!EvaluateArgs(Args, ArgValues, Info))
2139 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002140
Richard Smith745f5142012-01-27 01:14:48 +00002141 if (!Info.CheckCallLimit(CallLoc))
2142 return false;
2143
2144 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002145 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2146}
2147
Richard Smith180f4792011-11-10 06:34:14 +00002148/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002149static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002150 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002151 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002152 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002153 ArgVector ArgValues(Args.size());
2154 if (!EvaluateArgs(Args, ArgValues, Info))
2155 return false;
2156
Richard Smith745f5142012-01-27 01:14:48 +00002157 if (!Info.CheckCallLimit(CallLoc))
2158 return false;
2159
Richard Smith86c3ae42012-02-13 03:54:03 +00002160 const CXXRecordDecl *RD = Definition->getParent();
2161 if (RD->getNumVBases()) {
2162 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2163 return false;
2164 }
2165
Richard Smith745f5142012-01-27 01:14:48 +00002166 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002167
2168 // If it's a delegating constructor, just delegate.
2169 if (Definition->isDelegatingConstructor()) {
2170 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002171 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002172 }
2173
Richard Smith610a60c2012-01-10 04:32:03 +00002174 // For a trivial copy or move constructor, perform an APValue copy. This is
2175 // essential for unions, where the operations performed by the constructor
2176 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002177 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002178 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2179 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002180 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002181 RHS.setFrom(Info.Ctx, ArgValues[0]);
2182 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2183 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002184 }
2185
2186 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002187 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002188 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2189 std::distance(RD->field_begin(), RD->field_end()));
2190
2191 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2192
Richard Smith745f5142012-01-27 01:14:48 +00002193 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002194 unsigned BasesSeen = 0;
2195#ifndef NDEBUG
2196 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2197#endif
2198 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2199 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002200 LValue Subobject = This;
2201 APValue *Value = &Result;
2202
2203 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002204 if ((*I)->isBaseInitializer()) {
2205 QualType BaseType((*I)->getBaseClass(), 0);
2206#ifndef NDEBUG
2207 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002208 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002209 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2210 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2211 "base class initializers not in expected order");
2212 ++BaseIt;
2213#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002214 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002215 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002216 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002217 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002218 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002219 if (RD->isUnion()) {
2220 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002221 Value = &Result.getUnionValue();
2222 } else {
2223 Value = &Result.getStructField(FD->getFieldIndex());
2224 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002225 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002226 // Walk the indirect field decl's chain to find the object to initialize,
2227 // and make sure we've initialized every step along it.
2228 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2229 CE = IFD->chain_end();
2230 C != CE; ++C) {
2231 FieldDecl *FD = cast<FieldDecl>(*C);
2232 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2233 // Switch the union field if it differs. This happens if we had
2234 // preceding zero-initialization, and we're now initializing a union
2235 // subobject other than the first.
2236 // FIXME: In this case, the values of the other subobjects are
2237 // specified, since zero-initialization sets all padding bits to zero.
2238 if (Value->isUninit() ||
2239 (Value->isUnion() && Value->getUnionField() != FD)) {
2240 if (CD->isUnion())
2241 *Value = APValue(FD);
2242 else
2243 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2244 std::distance(CD->field_begin(), CD->field_end()));
2245 }
Richard Smith745f5142012-01-27 01:14:48 +00002246 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 if (CD->isUnion())
2248 Value = &Value->getUnionValue();
2249 else
2250 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002251 }
Richard Smith180f4792011-11-10 06:34:14 +00002252 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002253 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002254 }
Richard Smith745f5142012-01-27 01:14:48 +00002255
Richard Smith83587db2012-02-15 02:18:13 +00002256 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2257 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002258 ? CCEK_Constant : CCEK_MemberInit)) {
2259 // If we're checking for a potential constant expression, evaluate all
2260 // initializers even if some of them fail.
2261 if (!Info.keepEvaluatingAfterFailure())
2262 return false;
2263 Success = false;
2264 }
Richard Smith180f4792011-11-10 06:34:14 +00002265 }
2266
Richard Smith745f5142012-01-27 01:14:48 +00002267 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002268}
2269
Richard Smithd0dccea2011-10-28 22:34:42 +00002270namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002271class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002272 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002273 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002274public:
2275
Richard Smith1e12c592011-10-16 21:26:27 +00002276 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002277
2278 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002279 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002280 return true;
2281 }
2282
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2284 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002285 return Visit(E->getResultExpr());
2286 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002288 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002289 return true;
2290 return false;
2291 }
John McCallf85e1932011-06-15 23:02:42 +00002292 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002293 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002294 return true;
2295 return false;
2296 }
John McCallf85e1932011-06-15 23:02:42 +00002297
Mike Stumpc4c90452009-10-27 22:09:17 +00002298 // We don't want to evaluate BlockExprs multiple times, as they generate
2299 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002300 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2301 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2302 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002303 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2305 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2306 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2307 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2308 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2309 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002310 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002312 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002314 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002315 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2316 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2317 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2318 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002319 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002320 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2321 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2322 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2323 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2324 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002325 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002326 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002327 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002328 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002330
2331 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002332 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002333 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2334 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002336 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002337 return false;
2338 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002339
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002341};
2342
John McCall56ca35d2011-02-17 10:25:35 +00002343class OpaqueValueEvaluation {
2344 EvalInfo &info;
2345 OpaqueValueExpr *opaqueValue;
2346
2347public:
2348 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2349 Expr *value)
2350 : info(info), opaqueValue(opaqueValue) {
2351
2352 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002353 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002354 this->opaqueValue = 0;
2355 return;
2356 }
John McCall56ca35d2011-02-17 10:25:35 +00002357 }
2358
2359 bool hasError() const { return opaqueValue == 0; }
2360
2361 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002362 // FIXME: For a recursive constexpr call, an outer stack frame might have
2363 // been using this opaque value too, and will now have to re-evaluate the
2364 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002365 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2366 }
2367};
2368
Mike Stumpc4c90452009-10-27 22:09:17 +00002369} // end anonymous namespace
2370
Eli Friedman4efaa272008-11-12 09:44:48 +00002371//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372// Generic Evaluation
2373//===----------------------------------------------------------------------===//
2374namespace {
2375
Richard Smithf48fdb02011-12-09 22:58:01 +00002376// FIXME: RetTy is always bool. Remove it.
2377template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002378class ExprEvaluatorBase
2379 : public ConstStmtVisitor<Derived, RetTy> {
2380private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002381 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002382 return static_cast<Derived*>(this)->Success(V, E);
2383 }
Richard Smith51201882011-12-30 21:15:51 +00002384 RetTy DerivedZeroInitialization(const Expr *E) {
2385 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002386 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002387
Richard Smith74e1ad92012-02-16 02:46:34 +00002388 // Check whether a conditional operator with a non-constant condition is a
2389 // potential constant expression. If neither arm is a potential constant
2390 // expression, then the conditional operator is not either.
2391 template<typename ConditionalOperator>
2392 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2393 assert(Info.CheckingPotentialConstantExpression);
2394
2395 // Speculatively evaluate both arms.
2396 {
2397 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2398 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2399
2400 StmtVisitorTy::Visit(E->getFalseExpr());
2401 if (Diag.empty())
2402 return;
2403
2404 Diag.clear();
2405 StmtVisitorTy::Visit(E->getTrueExpr());
2406 if (Diag.empty())
2407 return;
2408 }
2409
2410 Error(E, diag::note_constexpr_conditional_never_const);
2411 }
2412
2413
2414 template<typename ConditionalOperator>
2415 bool HandleConditionalOperator(const ConditionalOperator *E) {
2416 bool BoolResult;
2417 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2418 if (Info.CheckingPotentialConstantExpression)
2419 CheckPotentialConstantConditional(E);
2420 return false;
2421 }
2422
2423 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2424 return StmtVisitorTy::Visit(EvalExpr);
2425 }
2426
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002427protected:
2428 EvalInfo &Info;
2429 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2430 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2431
Richard Smithdd1f29b2011-12-12 09:28:41 +00002432 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002433 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002434 }
2435
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002436 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2437
2438public:
2439 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2440
2441 EvalInfo &getEvalInfo() { return Info; }
2442
Richard Smithf48fdb02011-12-09 22:58:01 +00002443 /// Report an evaluation error. This should only be called when an error is
2444 /// first discovered. When propagating an error, just return false.
2445 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002446 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002447 return false;
2448 }
2449 bool Error(const Expr *E) {
2450 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2451 }
2452
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002453 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002454 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002455 }
2456 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002457 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002458 }
2459
2460 RetTy VisitParenExpr(const ParenExpr *E)
2461 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2462 RetTy VisitUnaryExtension(const UnaryOperator *E)
2463 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2464 RetTy VisitUnaryPlus(const UnaryOperator *E)
2465 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2466 RetTy VisitChooseExpr(const ChooseExpr *E)
2467 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2468 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2469 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002470 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2471 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002472 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2473 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002474 // We cannot create any objects for which cleanups are required, so there is
2475 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2476 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2477 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002478
Richard Smithc216a012011-12-12 12:46:16 +00002479 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2480 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2481 return static_cast<Derived*>(this)->VisitCastExpr(E);
2482 }
2483 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2484 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2485 return static_cast<Derived*>(this)->VisitCastExpr(E);
2486 }
2487
Richard Smithe24f5fc2011-11-17 22:56:20 +00002488 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2489 switch (E->getOpcode()) {
2490 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002491 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002492
2493 case BO_Comma:
2494 VisitIgnoredValue(E->getLHS());
2495 return StmtVisitorTy::Visit(E->getRHS());
2496
2497 case BO_PtrMemD:
2498 case BO_PtrMemI: {
2499 LValue Obj;
2500 if (!HandleMemberPointerAccess(Info, E, Obj))
2501 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002502 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002503 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002504 return false;
2505 return DerivedSuccess(Result, E);
2506 }
2507 }
2508 }
2509
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002510 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002511 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002512 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2513 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002514 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002515
Richard Smith74e1ad92012-02-16 02:46:34 +00002516 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002517 }
2518
2519 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002520 bool IsBcpCall = false;
2521 // If the condition (ignoring parens) is a __builtin_constant_p call,
2522 // the result is a constant expression if it can be folded without
2523 // side-effects. This is an important GNU extension. See GCC PR38377
2524 // for discussion.
2525 if (const CallExpr *CallCE =
2526 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2527 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2528 IsBcpCall = true;
2529
2530 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2531 // constant expression; we can't check whether it's potentially foldable.
2532 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2533 return false;
2534
2535 FoldConstant Fold(Info);
2536
Richard Smith74e1ad92012-02-16 02:46:34 +00002537 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002538 return false;
2539
2540 if (IsBcpCall)
2541 Fold.Fold(Info);
2542
2543 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002544 }
2545
2546 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002547 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002548 if (!Value) {
2549 const Expr *Source = E->getSourceExpr();
2550 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002551 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002552 if (Source == E) { // sanity checking.
2553 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002554 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002555 }
2556 return StmtVisitorTy::Visit(Source);
2557 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002558 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002559 }
Richard Smithf10d9172011-10-11 21:43:33 +00002560
Richard Smithd0dccea2011-10-28 22:34:42 +00002561 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002562 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002563 QualType CalleeType = Callee->getType();
2564
Richard Smithd0dccea2011-10-28 22:34:42 +00002565 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002566 LValue *This = 0, ThisVal;
2567 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002568 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002569
Richard Smith59efe262011-11-11 04:05:33 +00002570 // Extract function decl and 'this' pointer from the callee.
2571 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002573 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2574 // Explicit bound member calls, such as x.f() or p->g();
2575 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 return false;
2577 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002578 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002579 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2581 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002582 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2583 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002584 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002585 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002586 return Error(Callee);
2587
2588 FD = dyn_cast<FunctionDecl>(Member);
2589 if (!FD)
2590 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002591 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002592 LValue Call;
2593 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002594 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002595
Richard Smithb4e85ed2012-01-06 16:39:00 +00002596 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002598 FD = dyn_cast_or_null<FunctionDecl>(
2599 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002600 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002601 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002602
2603 // Overloaded operator calls to member functions are represented as normal
2604 // calls with '*this' as the first argument.
2605 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2606 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002607 // FIXME: When selecting an implicit conversion for an overloaded
2608 // operator delete, we sometimes try to evaluate calls to conversion
2609 // operators without a 'this' parameter!
2610 if (Args.empty())
2611 return Error(E);
2612
Richard Smith59efe262011-11-11 04:05:33 +00002613 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2614 return false;
2615 This = &ThisVal;
2616 Args = Args.slice(1);
2617 }
2618
2619 // Don't call function pointers which have been cast to some other type.
2620 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002622 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002623 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002624
Richard Smithb04035a2012-02-01 02:39:43 +00002625 if (This && !This->checkSubobject(Info, E, CSK_This))
2626 return false;
2627
Richard Smith86c3ae42012-02-13 03:54:03 +00002628 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2629 // calls to such functions in constant expressions.
2630 if (This && !HasQualifier &&
2631 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2632 return Error(E, diag::note_constexpr_virtual_call);
2633
Richard Smithc1c5f272011-12-13 06:39:58 +00002634 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002635 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002636 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002637
Richard Smithc1c5f272011-12-13 06:39:58 +00002638 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002639 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2640 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002641 return false;
2642
Richard Smith83587db2012-02-15 02:18:13 +00002643 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002644 }
2645
Richard Smithc49bd112011-10-28 17:51:58 +00002646 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2647 return StmtVisitorTy::Visit(E->getInitializer());
2648 }
Richard Smithf10d9172011-10-11 21:43:33 +00002649 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002650 if (E->getNumInits() == 0)
2651 return DerivedZeroInitialization(E);
2652 if (E->getNumInits() == 1)
2653 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002654 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002655 }
2656 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002657 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002658 }
2659 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002660 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002661 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002662 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002663 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002664 }
Richard Smithf10d9172011-10-11 21:43:33 +00002665
Richard Smith180f4792011-11-10 06:34:14 +00002666 /// A member expression where the object is a prvalue is itself a prvalue.
2667 RetTy VisitMemberExpr(const MemberExpr *E) {
2668 assert(!E->isArrow() && "missing call to bound member function?");
2669
Richard Smith1aa0be82012-03-03 22:46:17 +00002670 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002671 if (!Evaluate(Val, Info, E->getBase()))
2672 return false;
2673
2674 QualType BaseTy = E->getBase()->getType();
2675
2676 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002677 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002678 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2679 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2680 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2681
Richard Smithb4e85ed2012-01-06 16:39:00 +00002682 SubobjectDesignator Designator(BaseTy);
2683 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002684
Richard Smithf48fdb02011-12-09 22:58:01 +00002685 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002686 DerivedSuccess(Val, E);
2687 }
2688
Richard Smithc49bd112011-10-28 17:51:58 +00002689 RetTy VisitCastExpr(const CastExpr *E) {
2690 switch (E->getCastKind()) {
2691 default:
2692 break;
2693
David Chisnall7a7ee302012-01-16 17:27:18 +00002694 case CK_AtomicToNonAtomic:
2695 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002696 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002697 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002698 return StmtVisitorTy::Visit(E->getSubExpr());
2699
2700 case CK_LValueToRValue: {
2701 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002702 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2703 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002704 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002705 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2706 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2707 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002708 return false;
2709 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002710 }
2711 }
2712
Richard Smithf48fdb02011-12-09 22:58:01 +00002713 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002714 }
2715
Richard Smith8327fad2011-10-24 18:44:57 +00002716 /// Visit a value which is evaluated, but whose value is ignored.
2717 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002718 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002719 if (!Evaluate(Scratch, Info, E))
2720 Info.EvalStatus.HasSideEffects = true;
2721 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002722};
2723
2724}
2725
2726//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002727// Common base class for lvalue and temporary evaluation.
2728//===----------------------------------------------------------------------===//
2729namespace {
2730template<class Derived>
2731class LValueExprEvaluatorBase
2732 : public ExprEvaluatorBase<Derived, bool> {
2733protected:
2734 LValue &Result;
2735 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2736 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2737
2738 bool Success(APValue::LValueBase B) {
2739 Result.set(B);
2740 return true;
2741 }
2742
2743public:
2744 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2745 ExprEvaluatorBaseTy(Info), Result(Result) {}
2746
Richard Smith1aa0be82012-03-03 22:46:17 +00002747 bool Success(const APValue &V, const Expr *E) {
2748 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002749 return true;
2750 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002751
Richard Smithe24f5fc2011-11-17 22:56:20 +00002752 bool VisitMemberExpr(const MemberExpr *E) {
2753 // Handle non-static data members.
2754 QualType BaseTy;
2755 if (E->isArrow()) {
2756 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2757 return false;
2758 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002759 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002760 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002761 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2762 return false;
2763 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002764 } else {
2765 if (!this->Visit(E->getBase()))
2766 return false;
2767 BaseTy = E->getBase()->getType();
2768 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002769
Richard Smithd9b02e72012-01-25 22:15:11 +00002770 const ValueDecl *MD = E->getMemberDecl();
2771 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2772 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2773 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2774 (void)BaseTy;
2775 HandleLValueMember(this->Info, E, Result, FD);
2776 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2777 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2778 } else
2779 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780
Richard Smithd9b02e72012-01-25 22:15:11 +00002781 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002782 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002783 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002784 RefValue))
2785 return false;
2786 return Success(RefValue, E);
2787 }
2788 return true;
2789 }
2790
2791 bool VisitBinaryOperator(const BinaryOperator *E) {
2792 switch (E->getOpcode()) {
2793 default:
2794 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2795
2796 case BO_PtrMemD:
2797 case BO_PtrMemI:
2798 return HandleMemberPointerAccess(this->Info, E, Result);
2799 }
2800 }
2801
2802 bool VisitCastExpr(const CastExpr *E) {
2803 switch (E->getCastKind()) {
2804 default:
2805 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2806
2807 case CK_DerivedToBase:
2808 case CK_UncheckedDerivedToBase: {
2809 if (!this->Visit(E->getSubExpr()))
2810 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002811
2812 // Now figure out the necessary offset to add to the base LV to get from
2813 // the derived class to the base class.
2814 QualType Type = E->getSubExpr()->getType();
2815
2816 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2817 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002818 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002819 *PathI))
2820 return false;
2821 Type = (*PathI)->getType();
2822 }
2823
2824 return true;
2825 }
2826 }
2827 }
2828};
2829}
2830
2831//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002832// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002833//
2834// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2835// function designators (in C), decl references to void objects (in C), and
2836// temporaries (if building with -Wno-address-of-temporary).
2837//
2838// LValue evaluation produces values comprising a base expression of one of the
2839// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002840// - Declarations
2841// * VarDecl
2842// * FunctionDecl
2843// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002844// * CompoundLiteralExpr in C
2845// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002846// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002847// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002848// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002849// * ObjCEncodeExpr
2850// * AddrLabelExpr
2851// * BlockExpr
2852// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002853// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002854// * Any Expr, with a CallIndex indicating the function in which the temporary
2855// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002856// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002857//===----------------------------------------------------------------------===//
2858namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002859class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002860 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002861public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002862 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2863 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Richard Smithc49bd112011-10-28 17:51:58 +00002865 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2866
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002867 bool VisitDeclRefExpr(const DeclRefExpr *E);
2868 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002869 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002870 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2871 bool VisitMemberExpr(const MemberExpr *E);
2872 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2873 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002874 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002875 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2876 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002877 bool VisitUnaryReal(const UnaryOperator *E);
2878 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002879
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002880 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002881 switch (E->getCastKind()) {
2882 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002883 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002884
Eli Friedmandb924222011-10-11 00:13:24 +00002885 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002886 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002887 if (!Visit(E->getSubExpr()))
2888 return false;
2889 Result.Designator.setInvalid();
2890 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002891
Richard Smithe24f5fc2011-11-17 22:56:20 +00002892 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002893 if (!Visit(E->getSubExpr()))
2894 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002895 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002896 }
2897 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002898};
2899} // end anonymous namespace
2900
Richard Smithc49bd112011-10-28 17:51:58 +00002901/// Evaluate an expression as an lvalue. This can be legitimately called on
2902/// expressions which are not glvalues, in a few cases:
2903/// * function designators in C,
2904/// * "extern void" objects,
2905/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002906static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002907 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2908 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2909 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002910 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002911}
2912
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002913bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002914 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2915 return Success(FD);
2916 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002917 return VisitVarDecl(E, VD);
2918 return Error(E);
2919}
Richard Smith436c8892011-10-24 23:14:33 +00002920
Richard Smithc49bd112011-10-28 17:51:58 +00002921bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002922 if (!VD->getType()->isReferenceType()) {
2923 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002924 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002925 return true;
2926 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002927 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002928 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002929
Richard Smith1aa0be82012-03-03 22:46:17 +00002930 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002931 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2932 return false;
2933 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002934}
2935
Richard Smithbd552ef2011-10-31 05:52:43 +00002936bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2937 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002938 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002939 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002940 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2941
Richard Smith83587db2012-02-15 02:18:13 +00002942 Result.set(E, Info.CurrentCall->Index);
2943 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2944 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002945 }
2946
2947 // Materialization of an lvalue temporary occurs when we need to force a copy
2948 // (for instance, if it's a bitfield).
2949 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2950 if (!Visit(E->GetTemporaryExpr()))
2951 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002952 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002953 Info.CurrentCall->Temporaries[E]))
2954 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002955 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002956 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002957}
2958
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002959bool
2960LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002961 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2962 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2963 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002964 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002965}
2966
Richard Smith47d21452011-12-27 12:18:28 +00002967bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2968 if (E->isTypeOperand())
2969 return Success(E);
2970 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2971 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002972 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002973 << E->getExprOperand()->getType()
2974 << E->getExprOperand()->getSourceRange();
2975 return false;
2976 }
2977 return Success(E);
2978}
2979
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002980bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002981 // Handle static data members.
2982 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2983 VisitIgnoredValue(E->getBase());
2984 return VisitVarDecl(E, VD);
2985 }
2986
Richard Smithd0dccea2011-10-28 22:34:42 +00002987 // Handle static member functions.
2988 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2989 if (MD->isStatic()) {
2990 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002991 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002992 }
2993 }
2994
Richard Smith180f4792011-11-10 06:34:14 +00002995 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002996 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002997}
2998
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002999bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003000 // FIXME: Deal with vectors as array subscript bases.
3001 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003002 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003003
Anders Carlsson3068d112008-11-16 19:01:22 +00003004 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003005 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003006
Anders Carlsson3068d112008-11-16 19:01:22 +00003007 APSInt Index;
3008 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003009 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003010 int64_t IndexValue
3011 = Index.isSigned() ? Index.getSExtValue()
3012 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003013
Richard Smithb4e85ed2012-01-06 16:39:00 +00003014 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003015}
Eli Friedman4efaa272008-11-12 09:44:48 +00003016
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003017bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003018 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003019}
3020
Richard Smith86024012012-02-18 22:04:06 +00003021bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3022 if (!Visit(E->getSubExpr()))
3023 return false;
3024 // __real is a no-op on scalar lvalues.
3025 if (E->getSubExpr()->getType()->isAnyComplexType())
3026 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3027 return true;
3028}
3029
3030bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3031 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3032 "lvalue __imag__ on scalar?");
3033 if (!Visit(E->getSubExpr()))
3034 return false;
3035 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3036 return true;
3037}
3038
Eli Friedman4efaa272008-11-12 09:44:48 +00003039//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003040// Pointer Evaluation
3041//===----------------------------------------------------------------------===//
3042
Anders Carlssonc754aa62008-07-08 05:13:58 +00003043namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003044class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003045 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003046 LValue &Result;
3047
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003048 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003049 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003050 return true;
3051 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003052public:
Mike Stump1eb44332009-09-09 15:08:12 +00003053
John McCallefdb83e2010-05-07 21:00:08 +00003054 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003055 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003056
Richard Smith1aa0be82012-03-03 22:46:17 +00003057 bool Success(const APValue &V, const Expr *E) {
3058 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059 return true;
3060 }
Richard Smith51201882011-12-30 21:15:51 +00003061 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003062 return Success((Expr*)0);
3063 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003064
John McCallefdb83e2010-05-07 21:00:08 +00003065 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003066 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003067 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003068 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003069 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003070 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3071 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003072 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003073 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003074 bool VisitCallExpr(const CallExpr *E);
3075 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003076 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003077 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003078 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003079 }
Richard Smith180f4792011-11-10 06:34:14 +00003080 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3081 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003082 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003083 Result = *Info.CurrentCall->This;
3084 return true;
3085 }
John McCall56ca35d2011-02-17 10:25:35 +00003086
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003087 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003088};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003089} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003090
John McCallefdb83e2010-05-07 21:00:08 +00003091static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003092 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003093 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003094}
3095
John McCallefdb83e2010-05-07 21:00:08 +00003096bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003097 if (E->getOpcode() != BO_Add &&
3098 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003099 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003100
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003101 const Expr *PExp = E->getLHS();
3102 const Expr *IExp = E->getRHS();
3103 if (IExp->getType()->isPointerType())
3104 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Richard Smith745f5142012-01-27 01:14:48 +00003106 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3107 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003108 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003109
John McCallefdb83e2010-05-07 21:00:08 +00003110 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003111 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003112 return false;
3113 int64_t AdditionalOffset
3114 = Offset.isSigned() ? Offset.getSExtValue()
3115 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003116 if (E->getOpcode() == BO_Sub)
3117 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003118
Richard Smith180f4792011-11-10 06:34:14 +00003119 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003120 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3121 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003122}
Eli Friedman4efaa272008-11-12 09:44:48 +00003123
John McCallefdb83e2010-05-07 21:00:08 +00003124bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3125 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003126}
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003128bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3129 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003130
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003131 switch (E->getCastKind()) {
3132 default:
3133 break;
3134
John McCall2de56d12010-08-25 11:45:40 +00003135 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003136 case CK_CPointerToObjCPointerCast:
3137 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003138 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003139 if (!Visit(SubExpr))
3140 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003141 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3142 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3143 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003144 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003145 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003146 if (SubExpr->getType()->isVoidPointerType())
3147 CCEDiag(E, diag::note_constexpr_invalid_cast)
3148 << 3 << SubExpr->getType();
3149 else
3150 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3151 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003152 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003153
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003154 case CK_DerivedToBase:
3155 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003156 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003157 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003158 if (!Result.Base && Result.Offset.isZero())
3159 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003160
Richard Smith180f4792011-11-10 06:34:14 +00003161 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003162 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003163 QualType Type =
3164 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003165
Richard Smith180f4792011-11-10 06:34:14 +00003166 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003167 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003168 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3169 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003170 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003171 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003172 }
3173
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003174 return true;
3175 }
3176
Richard Smithe24f5fc2011-11-17 22:56:20 +00003177 case CK_BaseToDerived:
3178 if (!Visit(E->getSubExpr()))
3179 return false;
3180 if (!Result.Base && Result.Offset.isZero())
3181 return true;
3182 return HandleBaseToDerivedCast(Info, E, Result);
3183
Richard Smith47a1eed2011-10-29 20:57:55 +00003184 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003185 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003186 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003187
John McCall2de56d12010-08-25 11:45:40 +00003188 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003189 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3190
Richard Smith1aa0be82012-03-03 22:46:17 +00003191 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003192 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003193 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003194
John McCallefdb83e2010-05-07 21:00:08 +00003195 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003196 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3197 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003198 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003199 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003200 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003201 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003202 return true;
3203 } else {
3204 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003205 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003206 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003207 }
3208 }
John McCall2de56d12010-08-25 11:45:40 +00003209 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003210 if (SubExpr->isGLValue()) {
3211 if (!EvaluateLValue(SubExpr, Result, Info))
3212 return false;
3213 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003214 Result.set(SubExpr, Info.CurrentCall->Index);
3215 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3216 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003217 return false;
3218 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003219 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003220 if (const ConstantArrayType *CAT
3221 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3222 Result.addArray(Info, E, CAT);
3223 else
3224 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003225 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003226
John McCall2de56d12010-08-25 11:45:40 +00003227 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003228 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003229 }
3230
Richard Smithc49bd112011-10-28 17:51:58 +00003231 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003232}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003233
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003234bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003235 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003236 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003237
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003238 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003239}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003240
3241//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003242// Member Pointer Evaluation
3243//===----------------------------------------------------------------------===//
3244
3245namespace {
3246class MemberPointerExprEvaluator
3247 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3248 MemberPtr &Result;
3249
3250 bool Success(const ValueDecl *D) {
3251 Result = MemberPtr(D);
3252 return true;
3253 }
3254public:
3255
3256 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3257 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3258
Richard Smith1aa0be82012-03-03 22:46:17 +00003259 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003260 Result.setFrom(V);
3261 return true;
3262 }
Richard Smith51201882011-12-30 21:15:51 +00003263 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003264 return Success((const ValueDecl*)0);
3265 }
3266
3267 bool VisitCastExpr(const CastExpr *E);
3268 bool VisitUnaryAddrOf(const UnaryOperator *E);
3269};
3270} // end anonymous namespace
3271
3272static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3273 EvalInfo &Info) {
3274 assert(E->isRValue() && E->getType()->isMemberPointerType());
3275 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3276}
3277
3278bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3279 switch (E->getCastKind()) {
3280 default:
3281 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3282
3283 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003284 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003285 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003286
3287 case CK_BaseToDerivedMemberPointer: {
3288 if (!Visit(E->getSubExpr()))
3289 return false;
3290 if (E->path_empty())
3291 return true;
3292 // Base-to-derived member pointer casts store the path in derived-to-base
3293 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3294 // the wrong end of the derived->base arc, so stagger the path by one class.
3295 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3296 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3297 PathI != PathE; ++PathI) {
3298 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3299 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3300 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003301 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003302 }
3303 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3304 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003305 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003306 return true;
3307 }
3308
3309 case CK_DerivedToBaseMemberPointer:
3310 if (!Visit(E->getSubExpr()))
3311 return false;
3312 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3313 PathE = E->path_end(); PathI != PathE; ++PathI) {
3314 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3315 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3316 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003317 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003318 }
3319 return true;
3320 }
3321}
3322
3323bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3324 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3325 // member can be formed.
3326 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3327}
3328
3329//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003330// Record Evaluation
3331//===----------------------------------------------------------------------===//
3332
3333namespace {
3334 class RecordExprEvaluator
3335 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3336 const LValue &This;
3337 APValue &Result;
3338 public:
3339
3340 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3341 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3342
Richard Smith1aa0be82012-03-03 22:46:17 +00003343 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003344 Result = V;
3345 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003346 }
Richard Smith51201882011-12-30 21:15:51 +00003347 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003348
Richard Smith59efe262011-11-11 04:05:33 +00003349 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003350 bool VisitInitListExpr(const InitListExpr *E);
3351 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3352 };
3353}
3354
Richard Smith51201882011-12-30 21:15:51 +00003355/// Perform zero-initialization on an object of non-union class type.
3356/// C++11 [dcl.init]p5:
3357/// To zero-initialize an object or reference of type T means:
3358/// [...]
3359/// -- if T is a (possibly cv-qualified) non-union class type,
3360/// each non-static data member and each base-class subobject is
3361/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003362static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3363 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003364 const LValue &This, APValue &Result) {
3365 assert(!RD->isUnion() && "Expected non-union class type");
3366 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3367 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3368 std::distance(RD->field_begin(), RD->field_end()));
3369
3370 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3371
3372 if (CD) {
3373 unsigned Index = 0;
3374 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003375 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003376 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3377 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003378 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3379 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003380 Result.getStructBase(Index)))
3381 return false;
3382 }
3383 }
3384
Richard Smithb4e85ed2012-01-06 16:39:00 +00003385 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3386 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003387 // -- if T is a reference type, no initialization is performed.
3388 if ((*I)->getType()->isReferenceType())
3389 continue;
3390
3391 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003392 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003393
3394 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003395 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003396 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3397 return false;
3398 }
3399
3400 return true;
3401}
3402
3403bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3404 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3405 if (RD->isUnion()) {
3406 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3407 // object's first non-static named data member is zero-initialized
3408 RecordDecl::field_iterator I = RD->field_begin();
3409 if (I == RD->field_end()) {
3410 Result = APValue((const FieldDecl*)0);
3411 return true;
3412 }
3413
3414 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003415 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003416 Result = APValue(*I);
3417 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003418 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003419 }
3420
Richard Smithce582fe2012-02-17 00:44:16 +00003421 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003422 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003423 return false;
3424 }
3425
Richard Smithb4e85ed2012-01-06 16:39:00 +00003426 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003427}
3428
Richard Smith59efe262011-11-11 04:05:33 +00003429bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3430 switch (E->getCastKind()) {
3431 default:
3432 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3433
3434 case CK_ConstructorConversion:
3435 return Visit(E->getSubExpr());
3436
3437 case CK_DerivedToBase:
3438 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003439 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003440 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003441 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003442 if (!DerivedObject.isStruct())
3443 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003444
3445 // Derived-to-base rvalue conversion: just slice off the derived part.
3446 APValue *Value = &DerivedObject;
3447 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3448 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3449 PathE = E->path_end(); PathI != PathE; ++PathI) {
3450 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3451 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3452 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3453 RD = Base;
3454 }
3455 Result = *Value;
3456 return true;
3457 }
3458 }
3459}
3460
Richard Smith180f4792011-11-10 06:34:14 +00003461bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003462 // Cannot constant-evaluate std::initializer_list inits.
3463 if (E->initializesStdInitializerList())
3464 return false;
3465
Richard Smith180f4792011-11-10 06:34:14 +00003466 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3467 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3468
3469 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003470 const FieldDecl *Field = E->getInitializedFieldInUnion();
3471 Result = APValue(Field);
3472 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003473 return true;
Richard Smithec789162012-01-12 18:54:33 +00003474
3475 // If the initializer list for a union does not contain any elements, the
3476 // first element of the union is value-initialized.
3477 ImplicitValueInitExpr VIE(Field->getType());
3478 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3479
Richard Smith180f4792011-11-10 06:34:14 +00003480 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003481 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003482 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003483 }
3484
3485 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3486 "initializer list for class with base classes");
3487 Result = APValue(APValue::UninitStruct(), 0,
3488 std::distance(RD->field_begin(), RD->field_end()));
3489 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003490 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003491 for (RecordDecl::field_iterator Field = RD->field_begin(),
3492 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3493 // Anonymous bit-fields are not considered members of the class for
3494 // purposes of aggregate initialization.
3495 if (Field->isUnnamedBitfield())
3496 continue;
3497
3498 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003499
Richard Smith745f5142012-01-27 01:14:48 +00003500 bool HaveInit = ElementNo < E->getNumInits();
3501
3502 // FIXME: Diagnostics here should point to the end of the initializer
3503 // list, not the start.
3504 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3505 *Field, &Layout);
3506
3507 // Perform an implicit value-initialization for members beyond the end of
3508 // the initializer list.
3509 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3510
Richard Smith83587db2012-02-15 02:18:13 +00003511 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003512 Result.getStructField((*Field)->getFieldIndex()),
3513 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3514 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003515 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003516 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003517 }
3518 }
3519
Richard Smith745f5142012-01-27 01:14:48 +00003520 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003521}
3522
3523bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3524 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003525 bool ZeroInit = E->requiresZeroInitialization();
3526 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003527 // If we've already performed zero-initialization, we're already done.
3528 if (!Result.isUninit())
3529 return true;
3530
Richard Smith51201882011-12-30 21:15:51 +00003531 if (ZeroInit)
3532 return ZeroInitialization(E);
3533
Richard Smith61802452011-12-22 02:22:31 +00003534 const CXXRecordDecl *RD = FD->getParent();
3535 if (RD->isUnion())
3536 Result = APValue((FieldDecl*)0);
3537 else
3538 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3539 std::distance(RD->field_begin(), RD->field_end()));
3540 return true;
3541 }
3542
Richard Smith180f4792011-11-10 06:34:14 +00003543 const FunctionDecl *Definition = 0;
3544 FD->getBody(Definition);
3545
Richard Smithc1c5f272011-12-13 06:39:58 +00003546 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3547 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003548
Richard Smith610a60c2012-01-10 04:32:03 +00003549 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003550 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003551 if (const MaterializeTemporaryExpr *ME
3552 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3553 return Visit(ME->GetTemporaryExpr());
3554
Richard Smith51201882011-12-30 21:15:51 +00003555 if (ZeroInit && !ZeroInitialization(E))
3556 return false;
3557
Richard Smith180f4792011-11-10 06:34:14 +00003558 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003559 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003560 cast<CXXConstructorDecl>(Definition), Info,
3561 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003562}
3563
3564static bool EvaluateRecord(const Expr *E, const LValue &This,
3565 APValue &Result, EvalInfo &Info) {
3566 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003567 "can't evaluate expression as a record rvalue");
3568 return RecordExprEvaluator(Info, This, Result).Visit(E);
3569}
3570
3571//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003572// Temporary Evaluation
3573//
3574// Temporaries are represented in the AST as rvalues, but generally behave like
3575// lvalues. The full-object of which the temporary is a subobject is implicitly
3576// materialized so that a reference can bind to it.
3577//===----------------------------------------------------------------------===//
3578namespace {
3579class TemporaryExprEvaluator
3580 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3581public:
3582 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3583 LValueExprEvaluatorBaseTy(Info, Result) {}
3584
3585 /// Visit an expression which constructs the value of this temporary.
3586 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003587 Result.set(E, Info.CurrentCall->Index);
3588 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003589 }
3590
3591 bool VisitCastExpr(const CastExpr *E) {
3592 switch (E->getCastKind()) {
3593 default:
3594 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3595
3596 case CK_ConstructorConversion:
3597 return VisitConstructExpr(E->getSubExpr());
3598 }
3599 }
3600 bool VisitInitListExpr(const InitListExpr *E) {
3601 return VisitConstructExpr(E);
3602 }
3603 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3604 return VisitConstructExpr(E);
3605 }
3606 bool VisitCallExpr(const CallExpr *E) {
3607 return VisitConstructExpr(E);
3608 }
3609};
3610} // end anonymous namespace
3611
3612/// Evaluate an expression of record type as a temporary.
3613static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003614 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003615 return TemporaryExprEvaluator(Info, Result).Visit(E);
3616}
3617
3618//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003619// Vector Evaluation
3620//===----------------------------------------------------------------------===//
3621
3622namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003623 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003624 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3625 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003626 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Richard Smith07fc6572011-10-22 21:10:00 +00003628 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3629 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Richard Smith07fc6572011-10-22 21:10:00 +00003631 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3632 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3633 // FIXME: remove this APValue copy.
3634 Result = APValue(V.data(), V.size());
3635 return true;
3636 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003637 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003638 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003639 Result = V;
3640 return true;
3641 }
Richard Smith51201882011-12-30 21:15:51 +00003642 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Richard Smith07fc6572011-10-22 21:10:00 +00003644 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003645 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003646 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003647 bool VisitInitListExpr(const InitListExpr *E);
3648 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003649 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003650 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003651 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003652 };
3653} // end anonymous namespace
3654
3655static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003656 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003657 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003658}
3659
Richard Smith07fc6572011-10-22 21:10:00 +00003660bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3661 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003662 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Richard Smithd62ca372011-12-06 22:44:34 +00003664 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003665 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003666
Eli Friedman46a52322011-03-25 00:43:55 +00003667 switch (E->getCastKind()) {
3668 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003669 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003670 if (SETy->isIntegerType()) {
3671 APSInt IntResult;
3672 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003673 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003674 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003675 } else if (SETy->isRealFloatingType()) {
3676 APFloat F(0.0);
3677 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003678 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003679 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003680 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003681 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003682 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003683
3684 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003685 SmallVector<APValue, 4> Elts(NElts, Val);
3686 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003687 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003688 case CK_BitCast: {
3689 // Evaluate the operand into an APInt we can extract from.
3690 llvm::APInt SValInt;
3691 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3692 return false;
3693 // Extract the elements
3694 QualType EltTy = VTy->getElementType();
3695 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3696 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3697 SmallVector<APValue, 4> Elts;
3698 if (EltTy->isRealFloatingType()) {
3699 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3700 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3701 unsigned FloatEltSize = EltSize;
3702 if (&Sem == &APFloat::x87DoubleExtended)
3703 FloatEltSize = 80;
3704 for (unsigned i = 0; i < NElts; i++) {
3705 llvm::APInt Elt;
3706 if (BigEndian)
3707 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3708 else
3709 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3710 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3711 }
3712 } else if (EltTy->isIntegerType()) {
3713 for (unsigned i = 0; i < NElts; i++) {
3714 llvm::APInt Elt;
3715 if (BigEndian)
3716 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3717 else
3718 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3719 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3720 }
3721 } else {
3722 return Error(E);
3723 }
3724 return Success(Elts, E);
3725 }
Eli Friedman46a52322011-03-25 00:43:55 +00003726 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003727 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003728 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003729}
3730
Richard Smith07fc6572011-10-22 21:10:00 +00003731bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003732VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003733 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003734 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003735 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Nate Begeman59b5da62009-01-18 03:20:47 +00003737 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003738 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003739
Eli Friedman3edd5a92012-01-03 23:24:20 +00003740 // The number of initializers can be less than the number of
3741 // vector elements. For OpenCL, this can be due to nested vector
3742 // initialization. For GCC compatibility, missing trailing elements
3743 // should be initialized with zeroes.
3744 unsigned CountInits = 0, CountElts = 0;
3745 while (CountElts < NumElements) {
3746 // Handle nested vector initialization.
3747 if (CountInits < NumInits
3748 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3749 APValue v;
3750 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3751 return Error(E);
3752 unsigned vlen = v.getVectorLength();
3753 for (unsigned j = 0; j < vlen; j++)
3754 Elements.push_back(v.getVectorElt(j));
3755 CountElts += vlen;
3756 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003757 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003758 if (CountInits < NumInits) {
3759 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003760 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003761 } else // trailing integer zero.
3762 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3763 Elements.push_back(APValue(sInt));
3764 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003765 } else {
3766 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003767 if (CountInits < NumInits) {
3768 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003769 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003770 } else // trailing float zero.
3771 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3772 Elements.push_back(APValue(f));
3773 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003774 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003775 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003776 }
Richard Smith07fc6572011-10-22 21:10:00 +00003777 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003778}
3779
Richard Smith07fc6572011-10-22 21:10:00 +00003780bool
Richard Smith51201882011-12-30 21:15:51 +00003781VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003782 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003783 QualType EltTy = VT->getElementType();
3784 APValue ZeroElement;
3785 if (EltTy->isIntegerType())
3786 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3787 else
3788 ZeroElement =
3789 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3790
Chris Lattner5f9e2722011-07-23 10:55:15 +00003791 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003792 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003793}
3794
Richard Smith07fc6572011-10-22 21:10:00 +00003795bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003796 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003797 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003798}
3799
Nate Begeman59b5da62009-01-18 03:20:47 +00003800//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003801// Array Evaluation
3802//===----------------------------------------------------------------------===//
3803
3804namespace {
3805 class ArrayExprEvaluator
3806 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003807 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003808 APValue &Result;
3809 public:
3810
Richard Smith180f4792011-11-10 06:34:14 +00003811 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3812 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003813
3814 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003815 assert((V.isArray() || V.isLValue()) &&
3816 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003817 Result = V;
3818 return true;
3819 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003820
Richard Smith51201882011-12-30 21:15:51 +00003821 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003822 const ConstantArrayType *CAT =
3823 Info.Ctx.getAsConstantArrayType(E->getType());
3824 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003825 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003826
3827 Result = APValue(APValue::UninitArray(), 0,
3828 CAT->getSize().getZExtValue());
3829 if (!Result.hasArrayFiller()) return true;
3830
Richard Smith51201882011-12-30 21:15:51 +00003831 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003832 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003833 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003834 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003835 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003836 }
3837
Richard Smithcc5d4f62011-11-07 09:22:26 +00003838 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003839 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003840 };
3841} // end anonymous namespace
3842
Richard Smith180f4792011-11-10 06:34:14 +00003843static bool EvaluateArray(const Expr *E, const LValue &This,
3844 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003845 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003846 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003847}
3848
3849bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3850 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3851 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003852 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003853
Richard Smith974c5f92011-12-22 01:07:19 +00003854 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3855 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003856 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003857 LValue LV;
3858 if (!EvaluateLValue(E->getInit(0), LV, Info))
3859 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003860 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003861 LV.moveInto(Val);
3862 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003863 }
3864
Richard Smith745f5142012-01-27 01:14:48 +00003865 bool Success = true;
3866
Richard Smithcc5d4f62011-11-07 09:22:26 +00003867 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3868 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003869 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003870 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003871 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003872 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003873 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003874 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3875 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003876 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3877 CAT->getElementType(), 1)) {
3878 if (!Info.keepEvaluatingAfterFailure())
3879 return false;
3880 Success = false;
3881 }
Richard Smith180f4792011-11-10 06:34:14 +00003882 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003883
Richard Smith745f5142012-01-27 01:14:48 +00003884 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003885 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003886 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3887 // but sometimes does:
3888 // struct S { constexpr S() : p(&p) {} void *p; };
3889 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003890 return EvaluateInPlace(Result.getArrayFiller(), Info,
3891 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003892}
3893
Richard Smithe24f5fc2011-11-17 22:56:20 +00003894bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3895 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3896 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003897 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003898
Richard Smithec789162012-01-12 18:54:33 +00003899 bool HadZeroInit = !Result.isUninit();
3900 if (!HadZeroInit)
3901 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003902 if (!Result.hasArrayFiller())
3903 return true;
3904
3905 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003906
Richard Smith51201882011-12-30 21:15:51 +00003907 bool ZeroInit = E->requiresZeroInitialization();
3908 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003909 if (HadZeroInit)
3910 return true;
3911
Richard Smith51201882011-12-30 21:15:51 +00003912 if (ZeroInit) {
3913 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003914 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003915 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003916 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003917 }
3918
Richard Smith61802452011-12-22 02:22:31 +00003919 const CXXRecordDecl *RD = FD->getParent();
3920 if (RD->isUnion())
3921 Result.getArrayFiller() = APValue((FieldDecl*)0);
3922 else
3923 Result.getArrayFiller() =
3924 APValue(APValue::UninitStruct(), RD->getNumBases(),
3925 std::distance(RD->field_begin(), RD->field_end()));
3926 return true;
3927 }
3928
Richard Smithe24f5fc2011-11-17 22:56:20 +00003929 const FunctionDecl *Definition = 0;
3930 FD->getBody(Definition);
3931
Richard Smithc1c5f272011-12-13 06:39:58 +00003932 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3933 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003934
3935 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3936 // but sometimes does:
3937 // struct S { constexpr S() : p(&p) {} void *p; };
3938 // S s[10];
3939 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003940 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003941
Richard Smithec789162012-01-12 18:54:33 +00003942 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003943 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003944 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003945 return false;
3946 }
3947
Richard Smithe24f5fc2011-11-17 22:56:20 +00003948 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003949 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003950 cast<CXXConstructorDecl>(Definition),
3951 Info, Result.getArrayFiller());
3952}
3953
Richard Smithcc5d4f62011-11-07 09:22:26 +00003954//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003955// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003956//
3957// As a GNU extension, we support casting pointers to sufficiently-wide integer
3958// types and back in constant folding. Integer values are thus represented
3959// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003960//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003961
3962namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003963class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003964 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003965 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003966public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003967 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003968 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003969
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003970 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003971 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003972 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003973 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003974 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003975 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003976 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003977 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003978 return true;
3979 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003980 bool Success(const llvm::APSInt &SI, const Expr *E) {
3981 return Success(SI, E, Result);
3982 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003983
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003984 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003985 assert(E->getType()->isIntegralOrEnumerationType() &&
3986 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003987 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003988 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003989 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003990 Result.getInt().setIsUnsigned(
3991 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003992 return true;
3993 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003994 bool Success(const llvm::APInt &I, const Expr *E) {
3995 return Success(I, E, Result);
3996 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003997
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003998 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003999 assert(E->getType()->isIntegralOrEnumerationType() &&
4000 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004001 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004002 return true;
4003 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004004 bool Success(uint64_t Value, const Expr *E) {
4005 return Success(Value, E, Result);
4006 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004007
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004008 bool Success(CharUnits Size, const Expr *E) {
4009 return Success(Size.getQuantity(), E);
4010 }
4011
Richard Smith1aa0be82012-03-03 22:46:17 +00004012 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004013 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004014 Result = V;
4015 return true;
4016 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004017 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Richard Smith51201882011-12-30 21:15:51 +00004020 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004021
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004022 //===--------------------------------------------------------------------===//
4023 // Visitor Methods
4024 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004025
Chris Lattner4c4867e2008-07-12 00:38:25 +00004026 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004027 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004028 }
4029 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004030 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004031 }
Eli Friedman04309752009-11-24 05:28:59 +00004032
4033 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4034 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004035 if (CheckReferencedDecl(E, E->getDecl()))
4036 return true;
4037
4038 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004039 }
4040 bool VisitMemberExpr(const MemberExpr *E) {
4041 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004042 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004043 return true;
4044 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004045
4046 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004047 }
4048
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004049 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004050 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004051 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004052 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004053
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004054 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004055 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004056
Anders Carlsson3068d112008-11-16 19:01:22 +00004057 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004058 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004059 }
Mike Stump1eb44332009-09-09 15:08:12 +00004060
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004061 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4062 return Success(E->getValue(), E);
4063 }
4064
Richard Smithf10d9172011-10-11 21:43:33 +00004065 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004066 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004067 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004068 }
4069
Sebastian Redl64b45f72009-01-05 20:52:13 +00004070 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004071 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004072 }
4073
Francois Pichet6ad6f282010-12-07 00:08:36 +00004074 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4075 return Success(E->getValue(), E);
4076 }
4077
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004078 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4079 return Success(E->getValue(), E);
4080 }
4081
John Wiegley21ff2e52011-04-28 00:16:57 +00004082 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4083 return Success(E->getValue(), E);
4084 }
4085
John Wiegley55262202011-04-25 06:54:41 +00004086 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4087 return Success(E->getValue(), E);
4088 }
4089
Eli Friedman722c7172009-02-28 03:59:05 +00004090 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004091 bool VisitUnaryImag(const UnaryOperator *E);
4092
Sebastian Redl295995c2010-09-10 20:55:47 +00004093 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004094 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004095
Chris Lattnerfcee0012008-07-11 21:24:13 +00004096private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004097 CharUnits GetAlignOfExpr(const Expr *E);
4098 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004099 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004100 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004101 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004102};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004103} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004104
Richard Smithc49bd112011-10-28 17:51:58 +00004105/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4106/// produce either the integer value or a pointer.
4107///
4108/// GCC has a heinous extension which folds casts between pointer types and
4109/// pointer-sized integral types. We support this by allowing the evaluation of
4110/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4111/// Some simple arithmetic on such values is supported (they are treated much
4112/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004113static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004114 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004115 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004116 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004117}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004118
Richard Smithf48fdb02011-12-09 22:58:01 +00004119static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004120 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004121 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004122 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004123 if (!Val.isInt()) {
4124 // FIXME: It would be better to produce the diagnostic for casting
4125 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004126 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004127 return false;
4128 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004129 Result = Val.getInt();
4130 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004131}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004132
Richard Smithf48fdb02011-12-09 22:58:01 +00004133/// Check whether the given declaration can be directly converted to an integral
4134/// rvalue. If not, no diagnostic is produced; there are other things we can
4135/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004136bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004137 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004138 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004139 // Check for signedness/width mismatches between E type and ECD value.
4140 bool SameSign = (ECD->getInitVal().isSigned()
4141 == E->getType()->isSignedIntegerOrEnumerationType());
4142 bool SameWidth = (ECD->getInitVal().getBitWidth()
4143 == Info.Ctx.getIntWidth(E->getType()));
4144 if (SameSign && SameWidth)
4145 return Success(ECD->getInitVal(), E);
4146 else {
4147 // Get rid of mismatch (otherwise Success assertions will fail)
4148 // by computing a new value matching the type of E.
4149 llvm::APSInt Val = ECD->getInitVal();
4150 if (!SameSign)
4151 Val.setIsSigned(!ECD->getInitVal().isSigned());
4152 if (!SameWidth)
4153 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4154 return Success(Val, E);
4155 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004156 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004157 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004158}
4159
Chris Lattnera4d55d82008-10-06 06:40:35 +00004160/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4161/// as GCC.
4162static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4163 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004164 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004165 enum gcc_type_class {
4166 no_type_class = -1,
4167 void_type_class, integer_type_class, char_type_class,
4168 enumeral_type_class, boolean_type_class,
4169 pointer_type_class, reference_type_class, offset_type_class,
4170 real_type_class, complex_type_class,
4171 function_type_class, method_type_class,
4172 record_type_class, union_type_class,
4173 array_type_class, string_type_class,
4174 lang_type_class
4175 };
Mike Stump1eb44332009-09-09 15:08:12 +00004176
4177 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004178 // ideal, however it is what gcc does.
4179 if (E->getNumArgs() == 0)
4180 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004181
Chris Lattnera4d55d82008-10-06 06:40:35 +00004182 QualType ArgTy = E->getArg(0)->getType();
4183 if (ArgTy->isVoidType())
4184 return void_type_class;
4185 else if (ArgTy->isEnumeralType())
4186 return enumeral_type_class;
4187 else if (ArgTy->isBooleanType())
4188 return boolean_type_class;
4189 else if (ArgTy->isCharType())
4190 return string_type_class; // gcc doesn't appear to use char_type_class
4191 else if (ArgTy->isIntegerType())
4192 return integer_type_class;
4193 else if (ArgTy->isPointerType())
4194 return pointer_type_class;
4195 else if (ArgTy->isReferenceType())
4196 return reference_type_class;
4197 else if (ArgTy->isRealType())
4198 return real_type_class;
4199 else if (ArgTy->isComplexType())
4200 return complex_type_class;
4201 else if (ArgTy->isFunctionType())
4202 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004203 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004204 return record_type_class;
4205 else if (ArgTy->isUnionType())
4206 return union_type_class;
4207 else if (ArgTy->isArrayType())
4208 return array_type_class;
4209 else if (ArgTy->isUnionType())
4210 return union_type_class;
4211 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004212 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004213}
4214
Richard Smith80d4b552011-12-28 19:48:30 +00004215/// EvaluateBuiltinConstantPForLValue - Determine the result of
4216/// __builtin_constant_p when applied to the given lvalue.
4217///
4218/// An lvalue is only "constant" if it is a pointer or reference to the first
4219/// character of a string literal.
4220template<typename LValue>
4221static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004222 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004223 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4224}
4225
4226/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4227/// GCC as we can manage.
4228static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4229 QualType ArgType = Arg->getType();
4230
4231 // __builtin_constant_p always has one operand. The rules which gcc follows
4232 // are not precisely documented, but are as follows:
4233 //
4234 // - If the operand is of integral, floating, complex or enumeration type,
4235 // and can be folded to a known value of that type, it returns 1.
4236 // - If the operand and can be folded to a pointer to the first character
4237 // of a string literal (or such a pointer cast to an integral type), it
4238 // returns 1.
4239 //
4240 // Otherwise, it returns 0.
4241 //
4242 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4243 // its support for this does not currently work.
4244 if (ArgType->isIntegralOrEnumerationType()) {
4245 Expr::EvalResult Result;
4246 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4247 return false;
4248
4249 APValue &V = Result.Val;
4250 if (V.getKind() == APValue::Int)
4251 return true;
4252
4253 return EvaluateBuiltinConstantPForLValue(V);
4254 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4255 return Arg->isEvaluatable(Ctx);
4256 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4257 LValue LV;
4258 Expr::EvalStatus Status;
4259 EvalInfo Info(Ctx, Status);
4260 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4261 : EvaluatePointer(Arg, LV, Info)) &&
4262 !Status.HasSideEffects)
4263 return EvaluateBuiltinConstantPForLValue(LV);
4264 }
4265
4266 // Anything else isn't considered to be sufficiently constant.
4267 return false;
4268}
4269
John McCall42c8f872010-05-10 23:27:23 +00004270/// Retrieves the "underlying object type" of the given expression,
4271/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004272QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4273 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4274 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004275 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004276 } else if (const Expr *E = B.get<const Expr*>()) {
4277 if (isa<CompoundLiteralExpr>(E))
4278 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004279 }
4280
4281 return QualType();
4282}
4283
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004284bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004285 // TODO: Perhaps we should let LLVM lower this?
4286 LValue Base;
4287 if (!EvaluatePointer(E->getArg(0), Base, Info))
4288 return false;
4289
4290 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004291 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004292
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004293 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004294 if (T.isNull() ||
4295 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004296 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004297 T->isVariablyModifiedType() ||
4298 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004299 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004300
4301 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4302 CharUnits Offset = Base.getLValueOffset();
4303
4304 if (!Offset.isNegative() && Offset <= Size)
4305 Size -= Offset;
4306 else
4307 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004308 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004309}
4310
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004311bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004312 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004313 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004314 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004315
4316 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004317 if (TryEvaluateBuiltinObjectSize(E))
4318 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004319
Eric Christopherb2aaf512010-01-19 22:58:35 +00004320 // If evaluating the argument has side-effects we can't determine
4321 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004322 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004323 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004324 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004325 return Success(0, E);
4326 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004327
Richard Smithf48fdb02011-12-09 22:58:01 +00004328 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004329 }
4330
Chris Lattner019f4e82008-10-06 05:28:25 +00004331 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004332 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004333
Richard Smith80d4b552011-12-28 19:48:30 +00004334 case Builtin::BI__builtin_constant_p:
4335 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004336
Chris Lattner21fb98e2009-09-23 06:06:36 +00004337 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004338 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004339 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004340 return Success(Operand, E);
4341 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004342
4343 case Builtin::BI__builtin_expect:
4344 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004345
Douglas Gregor5726d402010-09-10 06:27:15 +00004346 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004347 // A call to strlen is not a constant expression.
4348 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004349 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004350 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4351 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004352 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004353 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004354 case Builtin::BI__builtin_strlen:
4355 // As an extension, we support strlen() and __builtin_strlen() as constant
4356 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004357 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004358 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4359 // The string literal may have embedded null characters. Find the first
4360 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004361 StringRef Str = S->getString();
4362 StringRef::size_type Pos = Str.find(0);
4363 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004364 Str = Str.substr(0, Pos);
4365
4366 return Success(Str.size(), E);
4367 }
4368
Richard Smithf48fdb02011-12-09 22:58:01 +00004369 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004370
Richard Smith2c39d712012-04-13 00:45:38 +00004371 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004372 case Builtin::BI__atomic_is_lock_free:
4373 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004374 APSInt SizeVal;
4375 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4376 return false;
4377
4378 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4379 // of two less than the maximum inline atomic width, we know it is
4380 // lock-free. If the size isn't a power of two, or greater than the
4381 // maximum alignment where we promote atomics, we know it is not lock-free
4382 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4383 // the answer can only be determined at runtime; for example, 16-byte
4384 // atomics have lock-free implementations on some, but not all,
4385 // x86-64 processors.
4386
4387 // Check power-of-two.
4388 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004389 if (Size.isPowerOfTwo()) {
4390 // Check against inlining width.
4391 unsigned InlineWidthBits =
4392 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4393 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4394 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4395 Size == CharUnits::One() ||
4396 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4397 Expr::NPC_NeverValueDependent))
4398 // OK, we will inline appropriately-aligned operations of this size,
4399 // and _Atomic(T) is appropriately-aligned.
4400 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004401
Richard Smith2c39d712012-04-13 00:45:38 +00004402 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4403 castAs<PointerType>()->getPointeeType();
4404 if (!PointeeType->isIncompleteType() &&
4405 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4406 // OK, we will inline operations on this object.
4407 return Success(1, E);
4408 }
4409 }
4410 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004411
Richard Smith2c39d712012-04-13 00:45:38 +00004412 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4413 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004414 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004415 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004416}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004417
Richard Smith625b8072011-10-31 01:37:14 +00004418static bool HasSameBase(const LValue &A, const LValue &B) {
4419 if (!A.getLValueBase())
4420 return !B.getLValueBase();
4421 if (!B.getLValueBase())
4422 return false;
4423
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004424 if (A.getLValueBase().getOpaqueValue() !=
4425 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004426 const Decl *ADecl = GetLValueBaseDecl(A);
4427 if (!ADecl)
4428 return false;
4429 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004430 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004431 return false;
4432 }
4433
4434 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004435 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004436}
4437
Richard Smith7b48a292012-02-01 05:53:12 +00004438/// Perform the given integer operation, which is known to need at most BitWidth
4439/// bits, and check for overflow in the original type (if that type was not an
4440/// unsigned type).
4441template<typename Operation>
4442static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4443 const APSInt &LHS, const APSInt &RHS,
4444 unsigned BitWidth, Operation Op) {
4445 if (LHS.isUnsigned())
4446 return Op(LHS, RHS);
4447
4448 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4449 APSInt Result = Value.trunc(LHS.getBitWidth());
4450 if (Result.extend(BitWidth) != Value)
4451 HandleOverflow(Info, E, Value, E->getType());
4452 return Result;
4453}
4454
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004455namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004456
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004457/// \brief Data recursive integer evaluator of certain binary operators.
4458///
4459/// We use a data recursive algorithm for binary operators so that we are able
4460/// to handle extreme cases of chained binary operators without causing stack
4461/// overflow.
4462class DataRecursiveIntBinOpEvaluator {
4463 struct EvalResult {
4464 APValue Val;
4465 bool Failed;
4466
4467 EvalResult() : Failed(false) { }
4468
4469 void swap(EvalResult &RHS) {
4470 Val.swap(RHS.Val);
4471 Failed = RHS.Failed;
4472 RHS.Failed = false;
4473 }
4474 };
4475
4476 struct Job {
4477 const Expr *E;
4478 EvalResult LHSResult; // meaningful only for binary operator expression.
4479 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4480
4481 Job() : StoredInfo(0) { }
4482 void startSpeculativeEval(EvalInfo &Info) {
4483 OldEvalStatus = Info.EvalStatus;
4484 Info.EvalStatus.Diag = 0;
4485 StoredInfo = &Info;
4486 }
4487 ~Job() {
4488 if (StoredInfo) {
4489 StoredInfo->EvalStatus = OldEvalStatus;
4490 }
4491 }
4492 private:
4493 EvalInfo *StoredInfo; // non-null if status changed.
4494 Expr::EvalStatus OldEvalStatus;
4495 };
4496
4497 SmallVector<Job, 16> Queue;
4498
4499 IntExprEvaluator &IntEval;
4500 EvalInfo &Info;
4501 APValue &FinalResult;
4502
4503public:
4504 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4505 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4506
4507 /// \brief True if \param E is a binary operator that we are going to handle
4508 /// data recursively.
4509 /// We handle binary operators that are comma, logical, or that have operands
4510 /// with integral or enumeration type.
4511 static bool shouldEnqueue(const BinaryOperator *E) {
4512 return E->getOpcode() == BO_Comma ||
4513 E->isLogicalOp() ||
4514 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4515 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004516 }
4517
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004518 bool Traverse(const BinaryOperator *E) {
4519 enqueue(E);
4520 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004521 while (!Queue.empty())
4522 process(PrevResult);
4523
4524 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004525
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004526 FinalResult.swap(PrevResult.Val);
4527 return true;
4528 }
4529
4530private:
4531 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4532 return IntEval.Success(Value, E, Result);
4533 }
4534 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4535 return IntEval.Success(Value, E, Result);
4536 }
4537 bool Error(const Expr *E) {
4538 return IntEval.Error(E);
4539 }
4540 bool Error(const Expr *E, diag::kind D) {
4541 return IntEval.Error(E, D);
4542 }
4543
4544 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4545 return Info.CCEDiag(E, D);
4546 }
4547
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004548 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4549 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004550 bool &SuppressRHSDiags);
4551
4552 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4553 const BinaryOperator *E, APValue &Result);
4554
4555 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4556 Result.Failed = !Evaluate(Result.Val, Info, E);
4557 if (Result.Failed)
4558 Result.Val = APValue();
4559 }
4560
Richard Trieub7783052012-03-21 23:30:30 +00004561 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004562
4563 void enqueue(const Expr *E) {
4564 E = E->IgnoreParens();
4565 Queue.resize(Queue.size()+1);
4566 Queue.back().E = E;
4567 Queue.back().Kind = Job::AnyExprKind;
4568 }
4569};
4570
4571}
4572
4573bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004574 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004575 bool &SuppressRHSDiags) {
4576 if (E->getOpcode() == BO_Comma) {
4577 // Ignore LHS but note if we could not evaluate it.
4578 if (LHSResult.Failed)
4579 Info.EvalStatus.HasSideEffects = true;
4580 return true;
4581 }
4582
4583 if (E->isLogicalOp()) {
4584 bool lhsResult;
4585 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004586 // We were able to evaluate the LHS, see if we can get away with not
4587 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004588 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004589 Success(lhsResult, E, LHSResult.Val);
4590 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004591 }
4592 } else {
4593 // Since we weren't able to evaluate the left hand side, it
4594 // must have had side effects.
4595 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004596
4597 // We can't evaluate the LHS; however, sometimes the result
4598 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4599 // Don't ignore RHS and suppress diagnostics from this arm.
4600 SuppressRHSDiags = true;
4601 }
4602
4603 return true;
4604 }
4605
4606 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4607 E->getRHS()->getType()->isIntegralOrEnumerationType());
4608
4609 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004610 return false; // Ignore RHS;
4611
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004612 return true;
4613}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004614
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004615bool DataRecursiveIntBinOpEvaluator::
4616 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4617 const BinaryOperator *E, APValue &Result) {
4618 if (E->getOpcode() == BO_Comma) {
4619 if (RHSResult.Failed)
4620 return false;
4621 Result = RHSResult.Val;
4622 return true;
4623 }
4624
4625 if (E->isLogicalOp()) {
4626 bool lhsResult, rhsResult;
4627 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4628 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4629
4630 if (LHSIsOK) {
4631 if (RHSIsOK) {
4632 if (E->getOpcode() == BO_LOr)
4633 return Success(lhsResult || rhsResult, E, Result);
4634 else
4635 return Success(lhsResult && rhsResult, E, Result);
4636 }
4637 } else {
4638 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004639 // We can't evaluate the LHS; however, sometimes the result
4640 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4641 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004642 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004643 }
4644 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004645
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004646 return false;
4647 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004648
4649 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4650 E->getRHS()->getType()->isIntegralOrEnumerationType());
4651
4652 if (LHSResult.Failed || RHSResult.Failed)
4653 return false;
4654
4655 const APValue &LHSVal = LHSResult.Val;
4656 const APValue &RHSVal = RHSResult.Val;
4657
4658 // Handle cases like (unsigned long)&a + 4.
4659 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4660 Result = LHSVal;
4661 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4662 RHSVal.getInt().getZExtValue());
4663 if (E->getOpcode() == BO_Add)
4664 Result.getLValueOffset() += AdditionalOffset;
4665 else
4666 Result.getLValueOffset() -= AdditionalOffset;
4667 return true;
4668 }
4669
4670 // Handle cases like 4 + (unsigned long)&a
4671 if (E->getOpcode() == BO_Add &&
4672 RHSVal.isLValue() && LHSVal.isInt()) {
4673 Result = RHSVal;
4674 Result.getLValueOffset() += CharUnits::fromQuantity(
4675 LHSVal.getInt().getZExtValue());
4676 return true;
4677 }
4678
4679 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4680 // Handle (intptr_t)&&A - (intptr_t)&&B.
4681 if (!LHSVal.getLValueOffset().isZero() ||
4682 !RHSVal.getLValueOffset().isZero())
4683 return false;
4684 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4685 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4686 if (!LHSExpr || !RHSExpr)
4687 return false;
4688 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4689 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4690 if (!LHSAddrExpr || !RHSAddrExpr)
4691 return false;
4692 // Make sure both labels come from the same function.
4693 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4694 RHSAddrExpr->getLabel()->getDeclContext())
4695 return false;
4696 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4697 return true;
4698 }
4699
4700 // All the following cases expect both operands to be an integer
4701 if (!LHSVal.isInt() || !RHSVal.isInt())
4702 return Error(E);
4703
4704 const APSInt &LHS = LHSVal.getInt();
4705 APSInt RHS = RHSVal.getInt();
4706
4707 switch (E->getOpcode()) {
4708 default:
4709 return Error(E);
4710 case BO_Mul:
4711 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4712 LHS.getBitWidth() * 2,
4713 std::multiplies<APSInt>()), E,
4714 Result);
4715 case BO_Add:
4716 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4717 LHS.getBitWidth() + 1,
4718 std::plus<APSInt>()), E, Result);
4719 case BO_Sub:
4720 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4721 LHS.getBitWidth() + 1,
4722 std::minus<APSInt>()), E, Result);
4723 case BO_And: return Success(LHS & RHS, E, Result);
4724 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4725 case BO_Or: return Success(LHS | RHS, E, Result);
4726 case BO_Div:
4727 case BO_Rem:
4728 if (RHS == 0)
4729 return Error(E, diag::note_expr_divide_by_zero);
4730 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4731 // not actually undefined behavior in C++11 due to a language defect.
4732 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4733 LHS.isSigned() && LHS.isMinSignedValue())
4734 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4735 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4736 Result);
4737 case BO_Shl: {
4738 // During constant-folding, a negative shift is an opposite shift. Such
4739 // a shift is not a constant expression.
4740 if (RHS.isSigned() && RHS.isNegative()) {
4741 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4742 RHS = -RHS;
4743 goto shift_right;
4744 }
4745
4746 shift_left:
4747 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4748 // the shifted type.
4749 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4750 if (SA != RHS) {
4751 CCEDiag(E, diag::note_constexpr_large_shift)
4752 << RHS << E->getType() << LHS.getBitWidth();
4753 } else if (LHS.isSigned()) {
4754 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4755 // operand, and must not overflow the corresponding unsigned type.
4756 if (LHS.isNegative())
4757 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4758 else if (LHS.countLeadingZeros() < SA)
4759 CCEDiag(E, diag::note_constexpr_lshift_discards);
4760 }
4761
4762 return Success(LHS << SA, E, Result);
4763 }
4764 case BO_Shr: {
4765 // During constant-folding, a negative shift is an opposite shift. Such a
4766 // shift is not a constant expression.
4767 if (RHS.isSigned() && RHS.isNegative()) {
4768 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4769 RHS = -RHS;
4770 goto shift_left;
4771 }
4772
4773 shift_right:
4774 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4775 // shifted type.
4776 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4777 if (SA != RHS)
4778 CCEDiag(E, diag::note_constexpr_large_shift)
4779 << RHS << E->getType() << LHS.getBitWidth();
4780
4781 return Success(LHS >> SA, E, Result);
4782 }
4783
4784 case BO_LT: return Success(LHS < RHS, E, Result);
4785 case BO_GT: return Success(LHS > RHS, E, Result);
4786 case BO_LE: return Success(LHS <= RHS, E, Result);
4787 case BO_GE: return Success(LHS >= RHS, E, Result);
4788 case BO_EQ: return Success(LHS == RHS, E, Result);
4789 case BO_NE: return Success(LHS != RHS, E, Result);
4790 }
4791}
4792
Richard Trieub7783052012-03-21 23:30:30 +00004793void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004794 Job &job = Queue.back();
4795
4796 switch (job.Kind) {
4797 case Job::AnyExprKind: {
4798 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4799 if (shouldEnqueue(Bop)) {
4800 job.Kind = Job::BinOpKind;
4801 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004802 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004803 }
4804 }
4805
4806 EvaluateExpr(job.E, Result);
4807 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004808 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004809 }
4810
4811 case Job::BinOpKind: {
4812 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004813 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004814 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004815 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004816 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004817 }
4818 if (SuppressRHSDiags)
4819 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004820 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004821 job.Kind = Job::BinOpVisitedLHSKind;
4822 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004823 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004824 }
4825
4826 case Job::BinOpVisitedLHSKind: {
4827 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4828 EvalResult RHS;
4829 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004830 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004831 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004832 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004833 }
4834 }
4835
4836 llvm_unreachable("Invalid Job::Kind!");
4837}
4838
4839bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4840 if (E->isAssignmentOp())
4841 return Error(E);
4842
4843 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4844 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004845
Anders Carlsson286f85e2008-11-16 07:17:21 +00004846 QualType LHSTy = E->getLHS()->getType();
4847 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004848
4849 if (LHSTy->isAnyComplexType()) {
4850 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004851 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004852
Richard Smith745f5142012-01-27 01:14:48 +00004853 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4854 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004855 return false;
4856
Richard Smith745f5142012-01-27 01:14:48 +00004857 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004858 return false;
4859
4860 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004861 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004862 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004863 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004864 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4865
John McCall2de56d12010-08-25 11:45:40 +00004866 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004867 return Success((CR_r == APFloat::cmpEqual &&
4868 CR_i == APFloat::cmpEqual), E);
4869 else {
John McCall2de56d12010-08-25 11:45:40 +00004870 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004871 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004872 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004873 CR_r == APFloat::cmpLessThan ||
4874 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004875 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004876 CR_i == APFloat::cmpLessThan ||
4877 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004878 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004879 } else {
John McCall2de56d12010-08-25 11:45:40 +00004880 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004881 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4882 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4883 else {
John McCall2de56d12010-08-25 11:45:40 +00004884 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004885 "Invalid compex comparison.");
4886 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4887 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4888 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004889 }
4890 }
Mike Stump1eb44332009-09-09 15:08:12 +00004891
Anders Carlsson286f85e2008-11-16 07:17:21 +00004892 if (LHSTy->isRealFloatingType() &&
4893 RHSTy->isRealFloatingType()) {
4894 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Richard Smith745f5142012-01-27 01:14:48 +00004896 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4897 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004898 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004899
Richard Smith745f5142012-01-27 01:14:48 +00004900 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004901 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004902
Anders Carlsson286f85e2008-11-16 07:17:21 +00004903 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004904
Anders Carlsson286f85e2008-11-16 07:17:21 +00004905 switch (E->getOpcode()) {
4906 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004907 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004908 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004909 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004910 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004911 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004912 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004913 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004914 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004915 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004916 E);
John McCall2de56d12010-08-25 11:45:40 +00004917 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004918 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004919 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004920 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004921 || CR == APFloat::cmpLessThan
4922 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004923 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004924 }
Mike Stump1eb44332009-09-09 15:08:12 +00004925
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004926 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004927 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004928 LValue LHSValue, RHSValue;
4929
4930 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4931 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004932 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004933
Richard Smith745f5142012-01-27 01:14:48 +00004934 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004935 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004936
Richard Smith625b8072011-10-31 01:37:14 +00004937 // Reject differing bases from the normal codepath; we special-case
4938 // comparisons to null.
4939 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004940 if (E->getOpcode() == BO_Sub) {
4941 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004942 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4943 return false;
4944 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4945 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4946 if (!LHSExpr || !RHSExpr)
4947 return false;
4948 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4949 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4950 if (!LHSAddrExpr || !RHSAddrExpr)
4951 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004952 // Make sure both labels come from the same function.
4953 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4954 RHSAddrExpr->getLabel()->getDeclContext())
4955 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004956 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004957 return true;
4958 }
Richard Smith9e36b532011-10-31 05:11:32 +00004959 // Inequalities and subtractions between unrelated pointers have
4960 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004961 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004962 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004963 // A constant address may compare equal to the address of a symbol.
4964 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004965 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004966 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4967 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004968 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004969 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004970 // distinct addresses. In clang, the result of such a comparison is
4971 // unspecified, so it is not a constant expression. However, we do know
4972 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004973 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4974 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004975 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004976 // We can't tell whether weak symbols will end up pointing to the same
4977 // object.
4978 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004979 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004980 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004981 // (Note that clang defaults to -fmerge-all-constants, which can
4982 // lead to inconsistent results for comparisons involving the address
4983 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004984 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004985 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004986
Richard Smith15efc4d2012-02-01 08:10:20 +00004987 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4988 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4989
Richard Smithf15fda02012-02-02 01:16:57 +00004990 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4991 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4992
John McCall2de56d12010-08-25 11:45:40 +00004993 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004994 // C++11 [expr.add]p6:
4995 // Unless both pointers point to elements of the same array object, or
4996 // one past the last element of the array object, the behavior is
4997 // undefined.
4998 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4999 !AreElementsOfSameArray(getType(LHSValue.Base),
5000 LHSDesignator, RHSDesignator))
5001 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5002
Chris Lattner4992bdd2010-04-20 17:13:14 +00005003 QualType Type = E->getLHS()->getType();
5004 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005005
Richard Smith180f4792011-11-10 06:34:14 +00005006 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005007 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005008 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005009
Richard Smith15efc4d2012-02-01 08:10:20 +00005010 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5011 // and produce incorrect results when it overflows. Such behavior
5012 // appears to be non-conforming, but is common, so perhaps we should
5013 // assume the standard intended for such cases to be undefined behavior
5014 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005015
Richard Smith15efc4d2012-02-01 08:10:20 +00005016 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5017 // overflow in the final conversion to ptrdiff_t.
5018 APSInt LHS(
5019 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5020 APSInt RHS(
5021 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5022 APSInt ElemSize(
5023 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5024 APSInt TrueResult = (LHS - RHS) / ElemSize;
5025 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5026
5027 if (Result.extend(65) != TrueResult)
5028 HandleOverflow(Info, E, TrueResult, E->getType());
5029 return Success(Result, E);
5030 }
Richard Smith82f28582012-01-31 06:41:30 +00005031
5032 // C++11 [expr.rel]p3:
5033 // Pointers to void (after pointer conversions) can be compared, with a
5034 // result defined as follows: If both pointers represent the same
5035 // address or are both the null pointer value, the result is true if the
5036 // operator is <= or >= and false otherwise; otherwise the result is
5037 // unspecified.
5038 // We interpret this as applying to pointers to *cv* void.
5039 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005040 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005041 CCEDiag(E, diag::note_constexpr_void_comparison);
5042
Richard Smithf15fda02012-02-02 01:16:57 +00005043 // C++11 [expr.rel]p2:
5044 // - If two pointers point to non-static data members of the same object,
5045 // or to subobjects or array elements fo such members, recursively, the
5046 // pointer to the later declared member compares greater provided the
5047 // two members have the same access control and provided their class is
5048 // not a union.
5049 // [...]
5050 // - Otherwise pointer comparisons are unspecified.
5051 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5052 E->isRelationalOp()) {
5053 bool WasArrayIndex;
5054 unsigned Mismatch =
5055 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5056 RHSDesignator, WasArrayIndex);
5057 // At the point where the designators diverge, the comparison has a
5058 // specified value if:
5059 // - we are comparing array indices
5060 // - we are comparing fields of a union, or fields with the same access
5061 // Otherwise, the result is unspecified and thus the comparison is not a
5062 // constant expression.
5063 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5064 Mismatch < RHSDesignator.Entries.size()) {
5065 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5066 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5067 if (!LF && !RF)
5068 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5069 else if (!LF)
5070 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5071 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5072 << RF->getParent() << RF;
5073 else if (!RF)
5074 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5075 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5076 << LF->getParent() << LF;
5077 else if (!LF->getParent()->isUnion() &&
5078 LF->getAccess() != RF->getAccess())
5079 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5080 << LF << LF->getAccess() << RF << RF->getAccess()
5081 << LF->getParent();
5082 }
5083 }
5084
Richard Smith625b8072011-10-31 01:37:14 +00005085 switch (E->getOpcode()) {
5086 default: llvm_unreachable("missing comparison operator");
5087 case BO_LT: return Success(LHSOffset < RHSOffset, E);
5088 case BO_GT: return Success(LHSOffset > RHSOffset, E);
5089 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
5090 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
5091 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
5092 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005093 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005094 }
5095 }
Richard Smithb02e4622012-02-01 01:42:44 +00005096
5097 if (LHSTy->isMemberPointerType()) {
5098 assert(E->isEqualityOp() && "unexpected member pointer operation");
5099 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5100
5101 MemberPtr LHSValue, RHSValue;
5102
5103 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5104 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5105 return false;
5106
5107 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5108 return false;
5109
5110 // C++11 [expr.eq]p2:
5111 // If both operands are null, they compare equal. Otherwise if only one is
5112 // null, they compare unequal.
5113 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5114 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5115 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5116 }
5117
5118 // Otherwise if either is a pointer to a virtual member function, the
5119 // result is unspecified.
5120 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5121 if (MD->isVirtual())
5122 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5123 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5124 if (MD->isVirtual())
5125 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5126
5127 // Otherwise they compare equal if and only if they would refer to the
5128 // same member of the same most derived object or the same subobject if
5129 // they were dereferenced with a hypothetical object of the associated
5130 // class type.
5131 bool Equal = LHSValue == RHSValue;
5132 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5133 }
5134
Richard Smith26f2cac2012-02-14 22:35:28 +00005135 if (LHSTy->isNullPtrType()) {
5136 assert(E->isComparisonOp() && "unexpected nullptr operation");
5137 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5138 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5139 // are compared, the result is true of the operator is <=, >= or ==, and
5140 // false otherwise.
5141 BinaryOperator::Opcode Opcode = E->getOpcode();
5142 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5143 }
5144
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005145 assert((!LHSTy->isIntegralOrEnumerationType() ||
5146 !RHSTy->isIntegralOrEnumerationType()) &&
5147 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5148 // We can't continue from here for non-integral types.
5149 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005150}
5151
Ken Dyck8b752f12010-01-27 17:10:57 +00005152CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005153 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5154 // result shall be the alignment of the referenced type."
5155 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5156 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005157
5158 // __alignof is defined to return the preferred alignment.
5159 return Info.Ctx.toCharUnitsFromBits(
5160 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005161}
5162
Ken Dyck8b752f12010-01-27 17:10:57 +00005163CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005164 E = E->IgnoreParens();
5165
5166 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005167 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005168 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005169 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5170 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005171
Chris Lattneraf707ab2009-01-24 21:53:27 +00005172 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005173 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5174 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005175
Chris Lattnere9feb472009-01-24 21:09:06 +00005176 return GetAlignOfType(E->getType());
5177}
5178
5179
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005180/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5181/// a result as the expression's type.
5182bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5183 const UnaryExprOrTypeTraitExpr *E) {
5184 switch(E->getKind()) {
5185 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005186 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005187 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005188 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005189 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005190 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005191
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005192 case UETT_VecStep: {
5193 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005194
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005195 if (Ty->isVectorType()) {
5196 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005197
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005198 // The vec_step built-in functions that take a 3-component
5199 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5200 if (n == 3)
5201 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005202
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005203 return Success(n, E);
5204 } else
5205 return Success(1, E);
5206 }
5207
5208 case UETT_SizeOf: {
5209 QualType SrcTy = E->getTypeOfArgument();
5210 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5211 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005212 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5213 SrcTy = Ref->getPointeeType();
5214
Richard Smith180f4792011-11-10 06:34:14 +00005215 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005216 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005217 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005218 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005219 }
5220 }
5221
5222 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005223}
5224
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005225bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005226 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005227 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005228 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005229 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005230 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005231 for (unsigned i = 0; i != n; ++i) {
5232 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5233 switch (ON.getKind()) {
5234 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005235 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005236 APSInt IdxResult;
5237 if (!EvaluateInteger(Idx, IdxResult, Info))
5238 return false;
5239 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5240 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005241 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005242 CurrentType = AT->getElementType();
5243 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5244 Result += IdxResult.getSExtValue() * ElementSize;
5245 break;
5246 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005247
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005248 case OffsetOfExpr::OffsetOfNode::Field: {
5249 FieldDecl *MemberDecl = ON.getField();
5250 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005251 if (!RT)
5252 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005253 RecordDecl *RD = RT->getDecl();
5254 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005255 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005256 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005257 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005258 CurrentType = MemberDecl->getType().getNonReferenceType();
5259 break;
5260 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005261
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005262 case OffsetOfExpr::OffsetOfNode::Identifier:
5263 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005264
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005265 case OffsetOfExpr::OffsetOfNode::Base: {
5266 CXXBaseSpecifier *BaseSpec = ON.getBase();
5267 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005268 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005269
5270 // Find the layout of the class whose base we are looking into.
5271 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005272 if (!RT)
5273 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005274 RecordDecl *RD = RT->getDecl();
5275 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5276
5277 // Find the base class itself.
5278 CurrentType = BaseSpec->getType();
5279 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5280 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005281 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005282
5283 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005284 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005285 break;
5286 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005287 }
5288 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005289 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005290}
5291
Chris Lattnerb542afe2008-07-11 19:10:17 +00005292bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005293 switch (E->getOpcode()) {
5294 default:
5295 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5296 // See C99 6.6p3.
5297 return Error(E);
5298 case UO_Extension:
5299 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5300 // If so, we could clear the diagnostic ID.
5301 return Visit(E->getSubExpr());
5302 case UO_Plus:
5303 // The result is just the value.
5304 return Visit(E->getSubExpr());
5305 case UO_Minus: {
5306 if (!Visit(E->getSubExpr()))
5307 return false;
5308 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005309 const APSInt &Value = Result.getInt();
5310 if (Value.isSigned() && Value.isMinSignedValue())
5311 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5312 E->getType());
5313 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005314 }
5315 case UO_Not: {
5316 if (!Visit(E->getSubExpr()))
5317 return false;
5318 if (!Result.isInt()) return Error(E);
5319 return Success(~Result.getInt(), E);
5320 }
5321 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005322 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005323 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005324 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005325 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005326 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005327 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005328}
Mike Stump1eb44332009-09-09 15:08:12 +00005329
Chris Lattner732b2232008-07-12 01:15:53 +00005330/// HandleCast - This is used to evaluate implicit or explicit casts where the
5331/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005332bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5333 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005334 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005335 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005336
Eli Friedman46a52322011-03-25 00:43:55 +00005337 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005338 case CK_BaseToDerived:
5339 case CK_DerivedToBase:
5340 case CK_UncheckedDerivedToBase:
5341 case CK_Dynamic:
5342 case CK_ToUnion:
5343 case CK_ArrayToPointerDecay:
5344 case CK_FunctionToPointerDecay:
5345 case CK_NullToPointer:
5346 case CK_NullToMemberPointer:
5347 case CK_BaseToDerivedMemberPointer:
5348 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005349 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005350 case CK_ConstructorConversion:
5351 case CK_IntegralToPointer:
5352 case CK_ToVoid:
5353 case CK_VectorSplat:
5354 case CK_IntegralToFloating:
5355 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005356 case CK_CPointerToObjCPointerCast:
5357 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005358 case CK_AnyPointerToBlockPointerCast:
5359 case CK_ObjCObjectLValueCast:
5360 case CK_FloatingRealToComplex:
5361 case CK_FloatingComplexToReal:
5362 case CK_FloatingComplexCast:
5363 case CK_FloatingComplexToIntegralComplex:
5364 case CK_IntegralRealToComplex:
5365 case CK_IntegralComplexCast:
5366 case CK_IntegralComplexToFloatingComplex:
5367 llvm_unreachable("invalid cast kind for integral value");
5368
Eli Friedmane50c2972011-03-25 19:07:11 +00005369 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005370 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005371 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005372 case CK_ARCProduceObject:
5373 case CK_ARCConsumeObject:
5374 case CK_ARCReclaimReturnedObject:
5375 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005376 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005377 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005378
Richard Smith7d580a42012-01-17 21:17:26 +00005379 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005380 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005381 case CK_AtomicToNonAtomic:
5382 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005383 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005384 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005385
5386 case CK_MemberPointerToBoolean:
5387 case CK_PointerToBoolean:
5388 case CK_IntegralToBoolean:
5389 case CK_FloatingToBoolean:
5390 case CK_FloatingComplexToBoolean:
5391 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005392 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005393 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005394 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005395 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005396 }
5397
Eli Friedman46a52322011-03-25 00:43:55 +00005398 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005399 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005400 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005401
Eli Friedmanbe265702009-02-20 01:15:07 +00005402 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005403 // Allow casts of address-of-label differences if they are no-ops
5404 // or narrowing. (The narrowing case isn't actually guaranteed to
5405 // be constant-evaluatable except in some narrow cases which are hard
5406 // to detect here. We let it through on the assumption the user knows
5407 // what they are doing.)
5408 if (Result.isAddrLabelDiff())
5409 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005410 // Only allow casts of lvalues if they are lossless.
5411 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5412 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005413
Richard Smithf72fccf2012-01-30 22:27:01 +00005414 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5415 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005416 }
Mike Stump1eb44332009-09-09 15:08:12 +00005417
Eli Friedman46a52322011-03-25 00:43:55 +00005418 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005419 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5420
John McCallefdb83e2010-05-07 21:00:08 +00005421 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005422 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005423 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005424
Daniel Dunbardd211642009-02-19 22:24:01 +00005425 if (LV.getLValueBase()) {
5426 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005427 // FIXME: Allow a larger integer size than the pointer size, and allow
5428 // narrowing back down to pointer width in subsequent integral casts.
5429 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005430 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005431 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005432
Richard Smithb755a9d2011-11-16 07:18:12 +00005433 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005434 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005435 return true;
5436 }
5437
Ken Dycka7305832010-01-15 12:37:54 +00005438 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5439 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005440 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005441 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005442
Eli Friedman46a52322011-03-25 00:43:55 +00005443 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005444 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005445 if (!EvaluateComplex(SubExpr, C, Info))
5446 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005447 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005448 }
Eli Friedman2217c872009-02-22 11:46:18 +00005449
Eli Friedman46a52322011-03-25 00:43:55 +00005450 case CK_FloatingToIntegral: {
5451 APFloat F(0.0);
5452 if (!EvaluateFloat(SubExpr, F, Info))
5453 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005454
Richard Smithc1c5f272011-12-13 06:39:58 +00005455 APSInt Value;
5456 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5457 return false;
5458 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005459 }
5460 }
Mike Stump1eb44332009-09-09 15:08:12 +00005461
Eli Friedman46a52322011-03-25 00:43:55 +00005462 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005463}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005464
Eli Friedman722c7172009-02-28 03:59:05 +00005465bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5466 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005467 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005468 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5469 return false;
5470 if (!LV.isComplexInt())
5471 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005472 return Success(LV.getComplexIntReal(), E);
5473 }
5474
5475 return Visit(E->getSubExpr());
5476}
5477
Eli Friedman664a1042009-02-27 04:45:43 +00005478bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005479 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005480 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005481 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5482 return false;
5483 if (!LV.isComplexInt())
5484 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005485 return Success(LV.getComplexIntImag(), E);
5486 }
5487
Richard Smith8327fad2011-10-24 18:44:57 +00005488 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005489 return Success(0, E);
5490}
5491
Douglas Gregoree8aff02011-01-04 17:33:58 +00005492bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5493 return Success(E->getPackLength(), E);
5494}
5495
Sebastian Redl295995c2010-09-10 20:55:47 +00005496bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5497 return Success(E->getValue(), E);
5498}
5499
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005500//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005501// Float Evaluation
5502//===----------------------------------------------------------------------===//
5503
5504namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005505class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005506 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005507 APFloat &Result;
5508public:
5509 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005510 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005511
Richard Smith1aa0be82012-03-03 22:46:17 +00005512 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005513 Result = V.getFloat();
5514 return true;
5515 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005516
Richard Smith51201882011-12-30 21:15:51 +00005517 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005518 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5519 return true;
5520 }
5521
Chris Lattner019f4e82008-10-06 05:28:25 +00005522 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005523
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005524 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005525 bool VisitBinaryOperator(const BinaryOperator *E);
5526 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005527 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005528
John McCallabd3a852010-05-07 22:08:54 +00005529 bool VisitUnaryReal(const UnaryOperator *E);
5530 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005531
Richard Smith51201882011-12-30 21:15:51 +00005532 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533};
5534} // end anonymous namespace
5535
5536static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005537 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005538 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005539}
5540
Jay Foad4ba2a172011-01-12 09:06:06 +00005541static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005542 QualType ResultTy,
5543 const Expr *Arg,
5544 bool SNaN,
5545 llvm::APFloat &Result) {
5546 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5547 if (!S) return false;
5548
5549 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5550
5551 llvm::APInt fill;
5552
5553 // Treat empty strings as if they were zero.
5554 if (S->getString().empty())
5555 fill = llvm::APInt(32, 0);
5556 else if (S->getString().getAsInteger(0, fill))
5557 return false;
5558
5559 if (SNaN)
5560 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5561 else
5562 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5563 return true;
5564}
5565
Chris Lattner019f4e82008-10-06 05:28:25 +00005566bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005567 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005568 default:
5569 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5570
Chris Lattner019f4e82008-10-06 05:28:25 +00005571 case Builtin::BI__builtin_huge_val:
5572 case Builtin::BI__builtin_huge_valf:
5573 case Builtin::BI__builtin_huge_vall:
5574 case Builtin::BI__builtin_inf:
5575 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005576 case Builtin::BI__builtin_infl: {
5577 const llvm::fltSemantics &Sem =
5578 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005579 Result = llvm::APFloat::getInf(Sem);
5580 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005581 }
Mike Stump1eb44332009-09-09 15:08:12 +00005582
John McCalldb7b72a2010-02-28 13:00:19 +00005583 case Builtin::BI__builtin_nans:
5584 case Builtin::BI__builtin_nansf:
5585 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005586 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5587 true, Result))
5588 return Error(E);
5589 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005590
Chris Lattner9e621712008-10-06 06:31:58 +00005591 case Builtin::BI__builtin_nan:
5592 case Builtin::BI__builtin_nanf:
5593 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005594 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005595 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005596 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5597 false, Result))
5598 return Error(E);
5599 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005600
5601 case Builtin::BI__builtin_fabs:
5602 case Builtin::BI__builtin_fabsf:
5603 case Builtin::BI__builtin_fabsl:
5604 if (!EvaluateFloat(E->getArg(0), Result, Info))
5605 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005606
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005607 if (Result.isNegative())
5608 Result.changeSign();
5609 return true;
5610
Mike Stump1eb44332009-09-09 15:08:12 +00005611 case Builtin::BI__builtin_copysign:
5612 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005613 case Builtin::BI__builtin_copysignl: {
5614 APFloat RHS(0.);
5615 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5616 !EvaluateFloat(E->getArg(1), RHS, Info))
5617 return false;
5618 Result.copySign(RHS);
5619 return true;
5620 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005621 }
5622}
5623
John McCallabd3a852010-05-07 22:08:54 +00005624bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005625 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5626 ComplexValue CV;
5627 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5628 return false;
5629 Result = CV.FloatReal;
5630 return true;
5631 }
5632
5633 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005634}
5635
5636bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005637 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5638 ComplexValue CV;
5639 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5640 return false;
5641 Result = CV.FloatImag;
5642 return true;
5643 }
5644
Richard Smith8327fad2011-10-24 18:44:57 +00005645 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005646 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5647 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005648 return true;
5649}
5650
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005651bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005652 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005653 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005654 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005655 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005656 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005657 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5658 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005659 Result.changeSign();
5660 return true;
5661 }
5662}
Chris Lattner019f4e82008-10-06 05:28:25 +00005663
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005664bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005665 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5666 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005667
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005668 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005669 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5670 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005671 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005672 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005673 return false;
5674
5675 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005676 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005677 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005678 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005679 break;
John McCall2de56d12010-08-25 11:45:40 +00005680 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005682 break;
John McCall2de56d12010-08-25 11:45:40 +00005683 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005684 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005685 break;
John McCall2de56d12010-08-25 11:45:40 +00005686 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005687 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005688 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005689 }
Richard Smith7b48a292012-02-01 05:53:12 +00005690
5691 if (Result.isInfinity() || Result.isNaN())
5692 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5693 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005694}
5695
5696bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5697 Result = E->getValue();
5698 return true;
5699}
5700
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005701bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5702 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005703
Eli Friedman2a523ee2011-03-25 00:54:52 +00005704 switch (E->getCastKind()) {
5705 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005706 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005707
5708 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005709 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005710 return EvaluateInteger(SubExpr, IntResult, Info) &&
5711 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5712 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005713 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005714
5715 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005716 if (!Visit(SubExpr))
5717 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005718 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5719 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005720 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005721
Eli Friedman2a523ee2011-03-25 00:54:52 +00005722 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005723 ComplexValue V;
5724 if (!EvaluateComplex(SubExpr, V, Info))
5725 return false;
5726 Result = V.getComplexFloatReal();
5727 return true;
5728 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005729 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005730}
5731
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005732//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005733// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005734//===----------------------------------------------------------------------===//
5735
5736namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005737class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005738 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005739 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005740
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005741public:
John McCallf4cf1a12010-05-07 17:22:02 +00005742 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005743 : ExprEvaluatorBaseTy(info), Result(Result) {}
5744
Richard Smith1aa0be82012-03-03 22:46:17 +00005745 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005746 Result.setFrom(V);
5747 return true;
5748 }
Mike Stump1eb44332009-09-09 15:08:12 +00005749
Eli Friedman7ead5c72012-01-10 04:58:17 +00005750 bool ZeroInitialization(const Expr *E);
5751
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005752 //===--------------------------------------------------------------------===//
5753 // Visitor Methods
5754 //===--------------------------------------------------------------------===//
5755
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005756 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005757 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005758 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005759 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005760 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005761};
5762} // end anonymous namespace
5763
John McCallf4cf1a12010-05-07 17:22:02 +00005764static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5765 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005766 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005767 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005768}
5769
Eli Friedman7ead5c72012-01-10 04:58:17 +00005770bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005771 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005772 if (ElemTy->isRealFloatingType()) {
5773 Result.makeComplexFloat();
5774 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5775 Result.FloatReal = Zero;
5776 Result.FloatImag = Zero;
5777 } else {
5778 Result.makeComplexInt();
5779 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5780 Result.IntReal = Zero;
5781 Result.IntImag = Zero;
5782 }
5783 return true;
5784}
5785
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005786bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5787 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005788
5789 if (SubExpr->getType()->isRealFloatingType()) {
5790 Result.makeComplexFloat();
5791 APFloat &Imag = Result.FloatImag;
5792 if (!EvaluateFloat(SubExpr, Imag, Info))
5793 return false;
5794
5795 Result.FloatReal = APFloat(Imag.getSemantics());
5796 return true;
5797 } else {
5798 assert(SubExpr->getType()->isIntegerType() &&
5799 "Unexpected imaginary literal.");
5800
5801 Result.makeComplexInt();
5802 APSInt &Imag = Result.IntImag;
5803 if (!EvaluateInteger(SubExpr, Imag, Info))
5804 return false;
5805
5806 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5807 return true;
5808 }
5809}
5810
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005811bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005812
John McCall8786da72010-12-14 17:51:41 +00005813 switch (E->getCastKind()) {
5814 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005815 case CK_BaseToDerived:
5816 case CK_DerivedToBase:
5817 case CK_UncheckedDerivedToBase:
5818 case CK_Dynamic:
5819 case CK_ToUnion:
5820 case CK_ArrayToPointerDecay:
5821 case CK_FunctionToPointerDecay:
5822 case CK_NullToPointer:
5823 case CK_NullToMemberPointer:
5824 case CK_BaseToDerivedMemberPointer:
5825 case CK_DerivedToBaseMemberPointer:
5826 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005827 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005828 case CK_ConstructorConversion:
5829 case CK_IntegralToPointer:
5830 case CK_PointerToIntegral:
5831 case CK_PointerToBoolean:
5832 case CK_ToVoid:
5833 case CK_VectorSplat:
5834 case CK_IntegralCast:
5835 case CK_IntegralToBoolean:
5836 case CK_IntegralToFloating:
5837 case CK_FloatingToIntegral:
5838 case CK_FloatingToBoolean:
5839 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005840 case CK_CPointerToObjCPointerCast:
5841 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005842 case CK_AnyPointerToBlockPointerCast:
5843 case CK_ObjCObjectLValueCast:
5844 case CK_FloatingComplexToReal:
5845 case CK_FloatingComplexToBoolean:
5846 case CK_IntegralComplexToReal:
5847 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005848 case CK_ARCProduceObject:
5849 case CK_ARCConsumeObject:
5850 case CK_ARCReclaimReturnedObject:
5851 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005852 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005853 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005854
John McCall8786da72010-12-14 17:51:41 +00005855 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005856 case CK_AtomicToNonAtomic:
5857 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005858 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005859 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005860
5861 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005862 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005863 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005864 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005865
5866 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005867 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005868 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005869 return false;
5870
John McCall8786da72010-12-14 17:51:41 +00005871 Result.makeComplexFloat();
5872 Result.FloatImag = APFloat(Real.getSemantics());
5873 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005874 }
5875
John McCall8786da72010-12-14 17:51:41 +00005876 case CK_FloatingComplexCast: {
5877 if (!Visit(E->getSubExpr()))
5878 return false;
5879
5880 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5881 QualType From
5882 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5883
Richard Smithc1c5f272011-12-13 06:39:58 +00005884 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5885 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005886 }
5887
5888 case CK_FloatingComplexToIntegralComplex: {
5889 if (!Visit(E->getSubExpr()))
5890 return false;
5891
5892 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5893 QualType From
5894 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5895 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005896 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5897 To, Result.IntReal) &&
5898 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5899 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005900 }
5901
5902 case CK_IntegralRealToComplex: {
5903 APSInt &Real = Result.IntReal;
5904 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5905 return false;
5906
5907 Result.makeComplexInt();
5908 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5909 return true;
5910 }
5911
5912 case CK_IntegralComplexCast: {
5913 if (!Visit(E->getSubExpr()))
5914 return false;
5915
5916 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5917 QualType From
5918 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5919
Richard Smithf72fccf2012-01-30 22:27:01 +00005920 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5921 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005922 return true;
5923 }
5924
5925 case CK_IntegralComplexToFloatingComplex: {
5926 if (!Visit(E->getSubExpr()))
5927 return false;
5928
5929 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5930 QualType From
5931 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5932 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005933 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5934 To, Result.FloatReal) &&
5935 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5936 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005937 }
5938 }
5939
5940 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005941}
5942
John McCallf4cf1a12010-05-07 17:22:02 +00005943bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005944 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005945 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5946
Richard Smith745f5142012-01-27 01:14:48 +00005947 bool LHSOK = Visit(E->getLHS());
5948 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005949 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005950
John McCallf4cf1a12010-05-07 17:22:02 +00005951 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005952 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005953 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005954
Daniel Dunbar3f279872009-01-29 01:32:56 +00005955 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5956 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005957 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005958 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005959 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005960 if (Result.isComplexFloat()) {
5961 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5962 APFloat::rmNearestTiesToEven);
5963 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5964 APFloat::rmNearestTiesToEven);
5965 } else {
5966 Result.getComplexIntReal() += RHS.getComplexIntReal();
5967 Result.getComplexIntImag() += RHS.getComplexIntImag();
5968 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005969 break;
John McCall2de56d12010-08-25 11:45:40 +00005970 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005971 if (Result.isComplexFloat()) {
5972 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5973 APFloat::rmNearestTiesToEven);
5974 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5975 APFloat::rmNearestTiesToEven);
5976 } else {
5977 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5978 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5979 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005980 break;
John McCall2de56d12010-08-25 11:45:40 +00005981 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005982 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005983 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005984 APFloat &LHS_r = LHS.getComplexFloatReal();
5985 APFloat &LHS_i = LHS.getComplexFloatImag();
5986 APFloat &RHS_r = RHS.getComplexFloatReal();
5987 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005988
Daniel Dunbar3f279872009-01-29 01:32:56 +00005989 APFloat Tmp = LHS_r;
5990 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5991 Result.getComplexFloatReal() = Tmp;
5992 Tmp = LHS_i;
5993 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5994 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5995
5996 Tmp = LHS_r;
5997 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5998 Result.getComplexFloatImag() = Tmp;
5999 Tmp = LHS_i;
6000 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6001 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6002 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006003 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006004 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006005 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6006 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006007 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006008 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6009 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6010 }
6011 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006012 case BO_Div:
6013 if (Result.isComplexFloat()) {
6014 ComplexValue LHS = Result;
6015 APFloat &LHS_r = LHS.getComplexFloatReal();
6016 APFloat &LHS_i = LHS.getComplexFloatImag();
6017 APFloat &RHS_r = RHS.getComplexFloatReal();
6018 APFloat &RHS_i = RHS.getComplexFloatImag();
6019 APFloat &Res_r = Result.getComplexFloatReal();
6020 APFloat &Res_i = Result.getComplexFloatImag();
6021
6022 APFloat Den = RHS_r;
6023 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6024 APFloat Tmp = RHS_i;
6025 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6026 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6027
6028 Res_r = LHS_r;
6029 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6030 Tmp = LHS_i;
6031 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6032 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6033 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6034
6035 Res_i = LHS_i;
6036 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6037 Tmp = LHS_r;
6038 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6039 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6040 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6041 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006042 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6043 return Error(E, diag::note_expr_divide_by_zero);
6044
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006045 ComplexValue LHS = Result;
6046 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6047 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6048 Result.getComplexIntReal() =
6049 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6050 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6051 Result.getComplexIntImag() =
6052 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6053 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6054 }
6055 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006056 }
6057
John McCallf4cf1a12010-05-07 17:22:02 +00006058 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006059}
6060
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006061bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6062 // Get the operand value into 'Result'.
6063 if (!Visit(E->getSubExpr()))
6064 return false;
6065
6066 switch (E->getOpcode()) {
6067 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006068 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006069 case UO_Extension:
6070 return true;
6071 case UO_Plus:
6072 // The result is always just the subexpr.
6073 return true;
6074 case UO_Minus:
6075 if (Result.isComplexFloat()) {
6076 Result.getComplexFloatReal().changeSign();
6077 Result.getComplexFloatImag().changeSign();
6078 }
6079 else {
6080 Result.getComplexIntReal() = -Result.getComplexIntReal();
6081 Result.getComplexIntImag() = -Result.getComplexIntImag();
6082 }
6083 return true;
6084 case UO_Not:
6085 if (Result.isComplexFloat())
6086 Result.getComplexFloatImag().changeSign();
6087 else
6088 Result.getComplexIntImag() = -Result.getComplexIntImag();
6089 return true;
6090 }
6091}
6092
Eli Friedman7ead5c72012-01-10 04:58:17 +00006093bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6094 if (E->getNumInits() == 2) {
6095 if (E->getType()->isComplexType()) {
6096 Result.makeComplexFloat();
6097 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6098 return false;
6099 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6100 return false;
6101 } else {
6102 Result.makeComplexInt();
6103 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6104 return false;
6105 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6106 return false;
6107 }
6108 return true;
6109 }
6110 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6111}
6112
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006113//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006114// Void expression evaluation, primarily for a cast to void on the LHS of a
6115// comma operator
6116//===----------------------------------------------------------------------===//
6117
6118namespace {
6119class VoidExprEvaluator
6120 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6121public:
6122 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6123
Richard Smith1aa0be82012-03-03 22:46:17 +00006124 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006125
6126 bool VisitCastExpr(const CastExpr *E) {
6127 switch (E->getCastKind()) {
6128 default:
6129 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6130 case CK_ToVoid:
6131 VisitIgnoredValue(E->getSubExpr());
6132 return true;
6133 }
6134 }
6135};
6136} // end anonymous namespace
6137
6138static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6139 assert(E->isRValue() && E->getType()->isVoidType());
6140 return VoidExprEvaluator(Info).Visit(E);
6141}
6142
6143//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006144// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006145//===----------------------------------------------------------------------===//
6146
Richard Smith1aa0be82012-03-03 22:46:17 +00006147static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006148 // In C, function designators are not lvalues, but we evaluate them as if they
6149 // are.
6150 if (E->isGLValue() || E->getType()->isFunctionType()) {
6151 LValue LV;
6152 if (!EvaluateLValue(E, LV, Info))
6153 return false;
6154 LV.moveInto(Result);
6155 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006156 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006157 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006158 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006159 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006160 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006161 } else if (E->getType()->hasPointerRepresentation()) {
6162 LValue LV;
6163 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006164 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006165 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006166 } else if (E->getType()->isRealFloatingType()) {
6167 llvm::APFloat F(0.0);
6168 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006169 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006170 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006171 } else if (E->getType()->isAnyComplexType()) {
6172 ComplexValue C;
6173 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006174 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006175 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006176 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006177 MemberPtr P;
6178 if (!EvaluateMemberPointer(E, P, Info))
6179 return false;
6180 P.moveInto(Result);
6181 return true;
Richard Smith51201882011-12-30 21:15:51 +00006182 } else if (E->getType()->isArrayType()) {
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 (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006186 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006187 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006188 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006189 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006190 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006191 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6192 return false;
6193 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006194 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006195 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006196 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006197 << E->getType();
6198 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006199 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006200 if (!EvaluateVoid(E, Info))
6201 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006202 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006203 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006204 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006205 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006206 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006207 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006208 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006209
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006210 return true;
6211}
6212
Richard Smith83587db2012-02-15 02:18:13 +00006213/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6214/// cases, the in-place evaluation is essential, since later initializers for
6215/// an object can indirectly refer to subobjects which were initialized earlier.
6216static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6217 const Expr *E, CheckConstantExpressionKind CCEK,
6218 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006219 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006220 return false;
6221
6222 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006223 // Evaluate arrays and record types in-place, so that later initializers can
6224 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006225 if (E->getType()->isArrayType())
6226 return EvaluateArray(E, This, Result, Info);
6227 else if (E->getType()->isRecordType())
6228 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006229 }
6230
6231 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006232 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006233}
6234
Richard Smithf48fdb02011-12-09 22:58:01 +00006235/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6236/// lvalue-to-rvalue cast if it is an lvalue.
6237static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006238 if (!CheckLiteralType(Info, E))
6239 return false;
6240
Richard Smith1aa0be82012-03-03 22:46:17 +00006241 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006242 return false;
6243
6244 if (E->isGLValue()) {
6245 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006246 LV.setFrom(Info.Ctx, Result);
6247 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006248 return false;
6249 }
6250
Richard Smith1aa0be82012-03-03 22:46:17 +00006251 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006252 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006253}
Richard Smithc49bd112011-10-28 17:51:58 +00006254
Richard Smith51f47082011-10-29 00:50:52 +00006255/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006256/// any crazy technique (that has nothing to do with language standards) that
6257/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006258/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6259/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006260bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006261 // Fast-path evaluations of integer literals, since we sometimes see files
6262 // containing vast quantities of these.
6263 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6264 Result.Val = APValue(APSInt(L->getValue(),
6265 L->getType()->isUnsignedIntegerType()));
6266 return true;
6267 }
6268
Richard Smith2d6a5672012-01-14 04:30:29 +00006269 // FIXME: Evaluating values of large array and record types can cause
6270 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006271 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006272 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006273 return false;
6274
Richard Smithf48fdb02011-12-09 22:58:01 +00006275 EvalInfo Info(Ctx, Result);
6276 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006277}
6278
Jay Foad4ba2a172011-01-12 09:06:06 +00006279bool Expr::EvaluateAsBooleanCondition(bool &Result,
6280 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006281 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006282 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006283 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006284}
6285
Richard Smith80d4b552011-12-28 19:48:30 +00006286bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6287 SideEffectsKind AllowSideEffects) const {
6288 if (!getType()->isIntegralOrEnumerationType())
6289 return false;
6290
Richard Smithc49bd112011-10-28 17:51:58 +00006291 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006292 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6293 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006294 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006295
Richard Smithc49bd112011-10-28 17:51:58 +00006296 Result = ExprResult.Val.getInt();
6297 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006298}
6299
Jay Foad4ba2a172011-01-12 09:06:06 +00006300bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006301 EvalInfo Info(Ctx, Result);
6302
John McCallefdb83e2010-05-07 21:00:08 +00006303 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006304 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6305 !CheckLValueConstantExpression(Info, getExprLoc(),
6306 Ctx.getLValueReferenceType(getType()), LV))
6307 return false;
6308
Richard Smith1aa0be82012-03-03 22:46:17 +00006309 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006310 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006311}
6312
Richard Smith099e7f62011-12-19 06:19:21 +00006313bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6314 const VarDecl *VD,
6315 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006316 // FIXME: Evaluating initializers for large array and record types can cause
6317 // performance problems. Only do so in C++11 for now.
6318 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006319 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006320 return false;
6321
Richard Smith099e7f62011-12-19 06:19:21 +00006322 Expr::EvalStatus EStatus;
6323 EStatus.Diag = &Notes;
6324
6325 EvalInfo InitInfo(Ctx, EStatus);
6326 InitInfo.setEvaluatingDecl(VD, Value);
6327
6328 LValue LVal;
6329 LVal.set(VD);
6330
Richard Smith51201882011-12-30 21:15:51 +00006331 // C++11 [basic.start.init]p2:
6332 // Variables with static storage duration or thread storage duration shall be
6333 // zero-initialized before any other initialization takes place.
6334 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006335 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006336 !VD->getType()->isReferenceType()) {
6337 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006338 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6339 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006340 return false;
6341 }
6342
Richard Smith83587db2012-02-15 02:18:13 +00006343 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6344 /*AllowNonLiteralTypes=*/true) ||
6345 EStatus.HasSideEffects)
6346 return false;
6347
6348 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6349 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006350}
6351
Richard Smith51f47082011-10-29 00:50:52 +00006352/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6353/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006354bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006355 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006356 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006357}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006358
Jay Foad4ba2a172011-01-12 09:06:06 +00006359bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006360 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006361}
6362
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006363APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006364 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006365 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006366 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006367 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006368 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006369
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006370 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006371}
John McCalld905f5a2010-05-07 05:32:02 +00006372
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006373 bool Expr::EvalResult::isGlobalLValue() const {
6374 assert(Val.isLValue());
6375 return IsGlobalLValue(Val.getLValueBase());
6376 }
6377
6378
John McCalld905f5a2010-05-07 05:32:02 +00006379/// isIntegerConstantExpr - this recursive routine will test if an expression is
6380/// an integer constant expression.
6381
6382/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6383/// comma, etc
6384///
6385/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6386/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6387/// cast+dereference.
6388
6389// CheckICE - This function does the fundamental ICE checking: the returned
6390// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6391// Note that to reduce code duplication, this helper does no evaluation
6392// itself; the caller checks whether the expression is evaluatable, and
6393// in the rare cases where CheckICE actually cares about the evaluated
6394// value, it calls into Evalute.
6395//
6396// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006397// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006398// 1: This expression is not an ICE, but if it isn't evaluated, it's
6399// a legal subexpression for an ICE. This return value is used to handle
6400// the comma operator in C99 mode.
6401// 2: This expression is not an ICE, and is not a legal subexpression for one.
6402
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006403namespace {
6404
John McCalld905f5a2010-05-07 05:32:02 +00006405struct ICEDiag {
6406 unsigned Val;
6407 SourceLocation Loc;
6408
6409 public:
6410 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6411 ICEDiag() : Val(0) {}
6412};
6413
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006414}
6415
6416static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006417
6418static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6419 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006420 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006421 !EVResult.Val.isInt()) {
6422 return ICEDiag(2, E->getLocStart());
6423 }
6424 return NoDiag();
6425}
6426
6427static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6428 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006429 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006430 return ICEDiag(2, E->getLocStart());
6431 }
6432
6433 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006434#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006435#define STMT(Node, Base) case Expr::Node##Class:
6436#define EXPR(Node, Base)
6437#include "clang/AST/StmtNodes.inc"
6438 case Expr::PredefinedExprClass:
6439 case Expr::FloatingLiteralClass:
6440 case Expr::ImaginaryLiteralClass:
6441 case Expr::StringLiteralClass:
6442 case Expr::ArraySubscriptExprClass:
6443 case Expr::MemberExprClass:
6444 case Expr::CompoundAssignOperatorClass:
6445 case Expr::CompoundLiteralExprClass:
6446 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006447 case Expr::DesignatedInitExprClass:
6448 case Expr::ImplicitValueInitExprClass:
6449 case Expr::ParenListExprClass:
6450 case Expr::VAArgExprClass:
6451 case Expr::AddrLabelExprClass:
6452 case Expr::StmtExprClass:
6453 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006454 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006455 case Expr::CXXDynamicCastExprClass:
6456 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006457 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006458 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006459 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006460 case Expr::CXXThisExprClass:
6461 case Expr::CXXThrowExprClass:
6462 case Expr::CXXNewExprClass:
6463 case Expr::CXXDeleteExprClass:
6464 case Expr::CXXPseudoDestructorExprClass:
6465 case Expr::UnresolvedLookupExprClass:
6466 case Expr::DependentScopeDeclRefExprClass:
6467 case Expr::CXXConstructExprClass:
6468 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006469 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006470 case Expr::CXXTemporaryObjectExprClass:
6471 case Expr::CXXUnresolvedConstructExprClass:
6472 case Expr::CXXDependentScopeMemberExprClass:
6473 case Expr::UnresolvedMemberExprClass:
6474 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006475 case Expr::ObjCNumericLiteralClass:
6476 case Expr::ObjCArrayLiteralClass:
6477 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006478 case Expr::ObjCEncodeExprClass:
6479 case Expr::ObjCMessageExprClass:
6480 case Expr::ObjCSelectorExprClass:
6481 case Expr::ObjCProtocolExprClass:
6482 case Expr::ObjCIvarRefExprClass:
6483 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006484 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006485 case Expr::ObjCIsaExprClass:
6486 case Expr::ShuffleVectorExprClass:
6487 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006488 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006489 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006490 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006491 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006492 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006493 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006494 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006495 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006496 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006497 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006498 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006499 return ICEDiag(2, E->getLocStart());
6500
Douglas Gregoree8aff02011-01-04 17:33:58 +00006501 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006502 case Expr::GNUNullExprClass:
6503 // GCC considers the GNU __null value to be an integral constant expression.
6504 return NoDiag();
6505
John McCall91a57552011-07-15 05:09:51 +00006506 case Expr::SubstNonTypeTemplateParmExprClass:
6507 return
6508 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6509
John McCalld905f5a2010-05-07 05:32:02 +00006510 case Expr::ParenExprClass:
6511 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006512 case Expr::GenericSelectionExprClass:
6513 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006514 case Expr::IntegerLiteralClass:
6515 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006516 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006517 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006518 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006519 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006520 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006521 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006522 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006523 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006524 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006525 return NoDiag();
6526 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006527 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006528 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6529 // constant expressions, but they can never be ICEs because an ICE cannot
6530 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006531 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006532 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006533 return CheckEvalInICE(E, Ctx);
6534 return ICEDiag(2, E->getLocStart());
6535 }
Richard Smith359c89d2012-02-24 22:12:32 +00006536 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006537 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6538 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006539 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006540 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006541 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006542 // Parameter variables are never constants. Without this check,
6543 // getAnyInitializer() can find a default argument, which leads
6544 // to chaos.
6545 if (isa<ParmVarDecl>(D))
6546 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6547
6548 // C++ 7.1.5.1p2
6549 // A variable of non-volatile const-qualified integral or enumeration
6550 // type initialized by an ICE can be used in ICEs.
6551 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006552 if (!Dcl->getType()->isIntegralOrEnumerationType())
6553 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6554
Richard Smith099e7f62011-12-19 06:19:21 +00006555 const VarDecl *VD;
6556 // Look for a declaration of this variable that has an initializer, and
6557 // check whether it is an ICE.
6558 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6559 return NoDiag();
6560 else
6561 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006562 }
6563 }
6564 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006565 }
John McCalld905f5a2010-05-07 05:32:02 +00006566 case Expr::UnaryOperatorClass: {
6567 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6568 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006569 case UO_PostInc:
6570 case UO_PostDec:
6571 case UO_PreInc:
6572 case UO_PreDec:
6573 case UO_AddrOf:
6574 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006575 // C99 6.6/3 allows increment and decrement within unevaluated
6576 // subexpressions of constant expressions, but they can never be ICEs
6577 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006578 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006579 case UO_Extension:
6580 case UO_LNot:
6581 case UO_Plus:
6582 case UO_Minus:
6583 case UO_Not:
6584 case UO_Real:
6585 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006586 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006587 }
6588
6589 // OffsetOf falls through here.
6590 }
6591 case Expr::OffsetOfExprClass: {
6592 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006593 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006594 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006595 // compliance: we should warn earlier for offsetof expressions with
6596 // array subscripts that aren't ICEs, and if the array subscripts
6597 // are ICEs, the value of the offsetof must be an integer constant.
6598 return CheckEvalInICE(E, Ctx);
6599 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006600 case Expr::UnaryExprOrTypeTraitExprClass: {
6601 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6602 if ((Exp->getKind() == UETT_SizeOf) &&
6603 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006604 return ICEDiag(2, E->getLocStart());
6605 return NoDiag();
6606 }
6607 case Expr::BinaryOperatorClass: {
6608 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6609 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006610 case BO_PtrMemD:
6611 case BO_PtrMemI:
6612 case BO_Assign:
6613 case BO_MulAssign:
6614 case BO_DivAssign:
6615 case BO_RemAssign:
6616 case BO_AddAssign:
6617 case BO_SubAssign:
6618 case BO_ShlAssign:
6619 case BO_ShrAssign:
6620 case BO_AndAssign:
6621 case BO_XorAssign:
6622 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006623 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6624 // constant expressions, but they can never be ICEs because an ICE cannot
6625 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006626 return ICEDiag(2, E->getLocStart());
6627
John McCall2de56d12010-08-25 11:45:40 +00006628 case BO_Mul:
6629 case BO_Div:
6630 case BO_Rem:
6631 case BO_Add:
6632 case BO_Sub:
6633 case BO_Shl:
6634 case BO_Shr:
6635 case BO_LT:
6636 case BO_GT:
6637 case BO_LE:
6638 case BO_GE:
6639 case BO_EQ:
6640 case BO_NE:
6641 case BO_And:
6642 case BO_Xor:
6643 case BO_Or:
6644 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006645 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6646 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006647 if (Exp->getOpcode() == BO_Div ||
6648 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006649 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006650 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006651 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006652 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006653 if (REval == 0)
6654 return ICEDiag(1, E->getLocStart());
6655 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006656 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006657 if (LEval.isMinSignedValue())
6658 return ICEDiag(1, E->getLocStart());
6659 }
6660 }
6661 }
John McCall2de56d12010-08-25 11:45:40 +00006662 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006663 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006664 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6665 // if it isn't evaluated.
6666 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6667 return ICEDiag(1, E->getLocStart());
6668 } else {
6669 // In both C89 and C++, commas in ICEs are illegal.
6670 return ICEDiag(2, E->getLocStart());
6671 }
6672 }
6673 if (LHSResult.Val >= RHSResult.Val)
6674 return LHSResult;
6675 return RHSResult;
6676 }
John McCall2de56d12010-08-25 11:45:40 +00006677 case BO_LAnd:
6678 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006679 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6680 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6681 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6682 // Rare case where the RHS has a comma "side-effect"; we need
6683 // to actually check the condition to see whether the side
6684 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006685 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006686 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006687 return RHSResult;
6688 return NoDiag();
6689 }
6690
6691 if (LHSResult.Val >= RHSResult.Val)
6692 return LHSResult;
6693 return RHSResult;
6694 }
6695 }
6696 }
6697 case Expr::ImplicitCastExprClass:
6698 case Expr::CStyleCastExprClass:
6699 case Expr::CXXFunctionalCastExprClass:
6700 case Expr::CXXStaticCastExprClass:
6701 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006702 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006703 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006704 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006705 if (isa<ExplicitCastExpr>(E)) {
6706 if (const FloatingLiteral *FL
6707 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6708 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6709 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6710 APSInt IgnoredVal(DestWidth, !DestSigned);
6711 bool Ignored;
6712 // If the value does not fit in the destination type, the behavior is
6713 // undefined, so we are not required to treat it as a constant
6714 // expression.
6715 if (FL->getValue().convertToInteger(IgnoredVal,
6716 llvm::APFloat::rmTowardZero,
6717 &Ignored) & APFloat::opInvalidOp)
6718 return ICEDiag(2, E->getLocStart());
6719 return NoDiag();
6720 }
6721 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006722 switch (cast<CastExpr>(E)->getCastKind()) {
6723 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006724 case CK_AtomicToNonAtomic:
6725 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006726 case CK_NoOp:
6727 case CK_IntegralToBoolean:
6728 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006729 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006730 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006731 return ICEDiag(2, E->getLocStart());
6732 }
John McCalld905f5a2010-05-07 05:32:02 +00006733 }
John McCall56ca35d2011-02-17 10:25:35 +00006734 case Expr::BinaryConditionalOperatorClass: {
6735 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6736 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6737 if (CommonResult.Val == 2) return CommonResult;
6738 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6739 if (FalseResult.Val == 2) return FalseResult;
6740 if (CommonResult.Val == 1) return CommonResult;
6741 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006742 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006743 return FalseResult;
6744 }
John McCalld905f5a2010-05-07 05:32:02 +00006745 case Expr::ConditionalOperatorClass: {
6746 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6747 // If the condition (ignoring parens) is a __builtin_constant_p call,
6748 // then only the true side is actually considered in an integer constant
6749 // expression, and it is fully evaluated. This is an important GNU
6750 // extension. See GCC PR38377 for discussion.
6751 if (const CallExpr *CallCE
6752 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006753 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6754 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006755 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006756 if (CondResult.Val == 2)
6757 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006758
Richard Smithf48fdb02011-12-09 22:58:01 +00006759 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6760 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006761
John McCalld905f5a2010-05-07 05:32:02 +00006762 if (TrueResult.Val == 2)
6763 return TrueResult;
6764 if (FalseResult.Val == 2)
6765 return FalseResult;
6766 if (CondResult.Val == 1)
6767 return CondResult;
6768 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6769 return NoDiag();
6770 // Rare case where the diagnostics depend on which side is evaluated
6771 // Note that if we get here, CondResult is 0, and at least one of
6772 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006773 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006774 return FalseResult;
6775 }
6776 return TrueResult;
6777 }
6778 case Expr::CXXDefaultArgExprClass:
6779 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6780 case Expr::ChooseExprClass: {
6781 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6782 }
6783 }
6784
David Blaikie30263482012-01-20 21:50:17 +00006785 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006786}
6787
Richard Smithf48fdb02011-12-09 22:58:01 +00006788/// Evaluate an expression as a C++11 integral constant expression.
6789static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6790 const Expr *E,
6791 llvm::APSInt *Value,
6792 SourceLocation *Loc) {
6793 if (!E->getType()->isIntegralOrEnumerationType()) {
6794 if (Loc) *Loc = E->getExprLoc();
6795 return false;
6796 }
6797
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006798 APValue Result;
6799 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006800 return false;
6801
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006802 assert(Result.isInt() && "pointer cast to int is not an ICE");
6803 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006804 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006805}
6806
Richard Smithdd1f29b2011-12-12 09:28:41 +00006807bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006808 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006809 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6810
John McCalld905f5a2010-05-07 05:32:02 +00006811 ICEDiag d = CheckICE(this, Ctx);
6812 if (d.Val != 0) {
6813 if (Loc) *Loc = d.Loc;
6814 return false;
6815 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006816 return true;
6817}
6818
6819bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6820 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006821 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006822 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6823
6824 if (!isIntegerConstantExpr(Ctx, Loc))
6825 return false;
6826 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006827 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006828 return true;
6829}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006830
Richard Smith70488e22012-02-14 21:38:30 +00006831bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6832 return CheckICE(this, Ctx).Val == 0;
6833}
6834
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006835bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6836 SourceLocation *Loc) const {
6837 // We support this checking in C++98 mode in order to diagnose compatibility
6838 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006839 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006840
Richard Smith70488e22012-02-14 21:38:30 +00006841 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006842 Expr::EvalStatus Status;
6843 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6844 Status.Diag = &Diags;
6845 EvalInfo Info(Ctx, Status);
6846
6847 APValue Scratch;
6848 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6849
6850 if (!Diags.empty()) {
6851 IsConstExpr = false;
6852 if (Loc) *Loc = Diags[0].first;
6853 } else if (!IsConstExpr) {
6854 // FIXME: This shouldn't happen.
6855 if (Loc) *Loc = getExprLoc();
6856 }
6857
6858 return IsConstExpr;
6859}
Richard Smith745f5142012-01-27 01:14:48 +00006860
6861bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6862 llvm::SmallVectorImpl<
6863 PartialDiagnosticAt> &Diags) {
6864 // FIXME: It would be useful to check constexpr function templates, but at the
6865 // moment the constant expression evaluator cannot cope with the non-rigorous
6866 // ASTs which we build for dependent expressions.
6867 if (FD->isDependentContext())
6868 return true;
6869
6870 Expr::EvalStatus Status;
6871 Status.Diag = &Diags;
6872
6873 EvalInfo Info(FD->getASTContext(), Status);
6874 Info.CheckingPotentialConstantExpression = true;
6875
6876 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6877 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6878
6879 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6880 // is a temporary being used as the 'this' pointer.
6881 LValue This;
6882 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006883 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006884
Richard Smith745f5142012-01-27 01:14:48 +00006885 ArrayRef<const Expr*> Args;
6886
6887 SourceLocation Loc = FD->getLocation();
6888
Richard Smith1aa0be82012-03-03 22:46:17 +00006889 APValue Scratch;
6890 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006891 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006892 else
Richard Smith745f5142012-01-27 01:14:48 +00006893 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6894 Args, FD->getBody(), Info, Scratch);
6895
6896 return Diags.empty();
6897}