blob: 5362320f4997a834c4822b5f5952cb46ba22a35a [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:
Francois Pichete275a182012-04-16 04:08:35 +0000937 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000938 return true;
939 case Expr::CallExprClass:
940 return IsStringLiteralCall(cast<CallExpr>(E));
941 // For GCC compatibility, &&label has static storage duration.
942 case Expr::AddrLabelExprClass:
943 return true;
944 // A Block literal expression may be used as the initialization value for
945 // Block variables at global or local static scope.
946 case Expr::BlockExprClass:
947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000948 case Expr::ImplicitValueInitExprClass:
949 // FIXME:
950 // We can never form an lvalue with an implicit value initialization as its
951 // base through expression evaluation, so these only appear in one case: the
952 // implicit variable declaration we invent when checking whether a constexpr
953 // constructor can produce a constant expression. We must assume that such
954 // an expression might be a global lvalue.
955 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000956 }
John McCall42c8f872010-05-10 23:27:23 +0000957}
958
Richard Smith83587db2012-02-15 02:18:13 +0000959static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
960 assert(Base && "no location for a null lvalue");
961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
962 if (VD)
963 Info.Note(VD->getLocation(), diag::note_declared_at);
964 else
965 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
966 diag::note_constexpr_temporary_here);
967}
968
Richard Smith9a17a682011-11-07 05:07:52 +0000969/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000970/// value for an address or reference constant expression. Return true if we
971/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000972static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
973 QualType Type, const LValue &LVal) {
974 bool IsReferenceType = Type->isReferenceType();
975
Richard Smithc1c5f272011-12-13 06:39:58 +0000976 APValue::LValueBase Base = LVal.getLValueBase();
977 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
978
Richard Smithb78ae972012-02-18 04:58:18 +0000979 // Check that the object is a global. Note that the fake 'this' object we
980 // manufacture when checking potential constant expressions is conservatively
981 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 if (!IsGlobalLValue(Base)) {
983 if (Info.getLangOpts().CPlusPlus0x) {
984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000985 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
986 << IsReferenceType << !Designator.Entries.empty()
987 << !!VD << VD;
988 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000989 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000990 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000991 }
Richard Smith61e61622012-01-12 06:08:57 +0000992 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000993 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000994 }
Richard Smith83587db2012-02-15 02:18:13 +0000995 assert((Info.CheckingPotentialConstantExpression ||
996 LVal.getLValueCallIndex() == 0) &&
997 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998
999 // Allow address constant expressions to be past-the-end pointers. This is
1000 // an extension: the standard requires them to point to an object.
1001 if (!IsReferenceType)
1002 return true;
1003
1004 // A reference constant expression must refer to an object.
1005 if (!Base) {
1006 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001007 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001008 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001009 }
1010
Richard Smithc1c5f272011-12-13 06:39:58 +00001011 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001012 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001013 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001014 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001015 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001016 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001017 }
1018
Richard Smith9a17a682011-11-07 05:07:52 +00001019 return true;
1020}
1021
Richard Smith51201882011-12-30 21:15:51 +00001022/// Check that this core constant expression is of literal type, and if not,
1023/// produce an appropriate diagnostic.
1024static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1025 if (!E->isRValue() || E->getType()->isLiteralType())
1026 return true;
1027
1028 // Prvalue constant expressions must be of literal types.
1029 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001030 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001031 << E->getType();
1032 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001033 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001034 return false;
1035}
1036
Richard Smith47a1eed2011-10-29 20:57:55 +00001037/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001038/// constant expression. If not, report an appropriate diagnostic. Does not
1039/// check that the expression is of literal type.
1040static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1041 QualType Type, const APValue &Value) {
1042 // Core issue 1454: For a literal constant expression of array or class type,
1043 // each subobject of its value shall have been initialized by a constant
1044 // expression.
1045 if (Value.isArray()) {
1046 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1047 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1048 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1049 Value.getArrayInitializedElt(I)))
1050 return false;
1051 }
1052 if (!Value.hasArrayFiller())
1053 return true;
1054 return CheckConstantExpression(Info, DiagLoc, EltTy,
1055 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001056 }
Richard Smith83587db2012-02-15 02:18:13 +00001057 if (Value.isUnion() && Value.getUnionField()) {
1058 return CheckConstantExpression(Info, DiagLoc,
1059 Value.getUnionField()->getType(),
1060 Value.getUnionValue());
1061 }
1062 if (Value.isStruct()) {
1063 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1064 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1065 unsigned BaseIndex = 0;
1066 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1067 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1068 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1069 Value.getStructBase(BaseIndex)))
1070 return false;
1071 }
1072 }
1073 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1074 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001075 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1076 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001077 return false;
1078 }
1079 }
1080
1081 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001082 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001083 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001084 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1085 }
1086
1087 // Everything else is fine.
1088 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001089}
1090
Richard Smith9e36b532011-10-31 05:11:32 +00001091const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001092 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001093}
1094
1095static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001096 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001097}
1098
Richard Smith65ac5982011-11-01 21:06:14 +00001099static bool IsWeakLValue(const LValue &Value) {
1100 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001101 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001102}
1103
Richard Smith1aa0be82012-03-03 22:46:17 +00001104static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001105 // A null base expression indicates a null pointer. These are always
1106 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001107 if (!Value.getLValueBase()) {
1108 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001109 return true;
1110 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001111
Richard Smithe24f5fc2011-11-17 22:56:20 +00001112 // We have a non-null base. These are generally known to be true, but if it's
1113 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001114 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001115 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001116 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001117}
1118
Richard Smith1aa0be82012-03-03 22:46:17 +00001119static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001120 switch (Val.getKind()) {
1121 case APValue::Uninitialized:
1122 return false;
1123 case APValue::Int:
1124 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001125 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001126 case APValue::Float:
1127 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001128 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001129 case APValue::ComplexInt:
1130 Result = Val.getComplexIntReal().getBoolValue() ||
1131 Val.getComplexIntImag().getBoolValue();
1132 return true;
1133 case APValue::ComplexFloat:
1134 Result = !Val.getComplexFloatReal().isZero() ||
1135 !Val.getComplexFloatImag().isZero();
1136 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001137 case APValue::LValue:
1138 return EvalPointerValueAsBool(Val, Result);
1139 case APValue::MemberPointer:
1140 Result = Val.getMemberPointerDecl();
1141 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001142 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001143 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001144 case APValue::Struct:
1145 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001146 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001147 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001148 }
1149
Richard Smithc49bd112011-10-28 17:51:58 +00001150 llvm_unreachable("unknown APValue kind");
1151}
1152
1153static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1154 EvalInfo &Info) {
1155 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001156 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001157 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001158 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001159 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001160}
1161
Richard Smithc1c5f272011-12-13 06:39:58 +00001162template<typename T>
1163static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1164 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001165 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001166 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001167 return false;
1168}
1169
1170static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1171 QualType SrcType, const APFloat &Value,
1172 QualType DestType, APSInt &Result) {
1173 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001174 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001175 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Richard Smithc1c5f272011-12-13 06:39:58 +00001177 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001178 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001179 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1180 & APFloat::opInvalidOp)
1181 return HandleOverflow(Info, E, Value, DestType);
1182 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001183}
1184
Richard Smithc1c5f272011-12-13 06:39:58 +00001185static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1186 QualType SrcType, QualType DestType,
1187 APFloat &Result) {
1188 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001189 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001190 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1191 APFloat::rmNearestTiesToEven, &ignored)
1192 & APFloat::opOverflow)
1193 return HandleOverflow(Info, E, Value, DestType);
1194 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001195}
1196
Richard Smithf72fccf2012-01-30 22:27:01 +00001197static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1198 QualType DestType, QualType SrcType,
1199 APSInt &Value) {
1200 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001201 APSInt Result = Value;
1202 // Figure out if this is a truncate, extend or noop cast.
1203 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001204 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001205 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001206 return Result;
1207}
1208
Richard Smithc1c5f272011-12-13 06:39:58 +00001209static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1210 QualType SrcType, const APSInt &Value,
1211 QualType DestType, APFloat &Result) {
1212 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1213 if (Result.convertFromAPInt(Value, Value.isSigned(),
1214 APFloat::rmNearestTiesToEven)
1215 & APFloat::opOverflow)
1216 return HandleOverflow(Info, E, Value, DestType);
1217 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001218}
1219
Eli Friedmane6a24e82011-12-22 03:51:45 +00001220static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1221 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001222 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001223 if (!Evaluate(SVal, Info, E))
1224 return false;
1225 if (SVal.isInt()) {
1226 Res = SVal.getInt();
1227 return true;
1228 }
1229 if (SVal.isFloat()) {
1230 Res = SVal.getFloat().bitcastToAPInt();
1231 return true;
1232 }
1233 if (SVal.isVector()) {
1234 QualType VecTy = E->getType();
1235 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1236 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1237 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1238 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1239 Res = llvm::APInt::getNullValue(VecSize);
1240 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1241 APValue &Elt = SVal.getVectorElt(i);
1242 llvm::APInt EltAsInt;
1243 if (Elt.isInt()) {
1244 EltAsInt = Elt.getInt();
1245 } else if (Elt.isFloat()) {
1246 EltAsInt = Elt.getFloat().bitcastToAPInt();
1247 } else {
1248 // Don't try to handle vectors of anything other than int or float
1249 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001250 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001251 return false;
1252 }
1253 unsigned BaseEltSize = EltAsInt.getBitWidth();
1254 if (BigEndian)
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1256 else
1257 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1258 }
1259 return true;
1260 }
1261 // Give up if the input isn't an int, float, or vector. For example, we
1262 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001263 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001264 return false;
1265}
1266
Richard Smithb4e85ed2012-01-06 16:39:00 +00001267/// Cast an lvalue referring to a base subobject to a derived class, by
1268/// truncating the lvalue's path to the given length.
1269static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1270 const RecordDecl *TruncatedType,
1271 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001272 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001273
1274 // Check we actually point to a derived class object.
1275 if (TruncatedElements == D.Entries.size())
1276 return true;
1277 assert(TruncatedElements >= D.MostDerivedPathLength &&
1278 "not casting to a derived class");
1279 if (!Result.checkSubobject(Info, E, CSK_Derived))
1280 return false;
1281
1282 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001283 const RecordDecl *RD = TruncatedType;
1284 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001285 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001286 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1287 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001290 else
Richard Smith180f4792011-11-10 06:34:14 +00001291 Result.Offset -= Layout.getBaseClassOffset(Base);
1292 RD = Base;
1293 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001294 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001295 return true;
1296}
1297
John McCall8d59dee2012-05-01 00:38:49 +00001298static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001299 const CXXRecordDecl *Derived,
1300 const CXXRecordDecl *Base,
1301 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001302 if (!RL) {
1303 if (Derived->isInvalidDecl()) return false;
1304 RL = &Info.Ctx.getASTRecordLayout(Derived);
1305 }
1306
Richard Smith180f4792011-11-10 06:34:14 +00001307 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001308 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001309 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001310}
1311
Richard Smithb4e85ed2012-01-06 16:39:00 +00001312static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001313 const CXXRecordDecl *DerivedDecl,
1314 const CXXBaseSpecifier *Base) {
1315 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1316
John McCall8d59dee2012-05-01 00:38:49 +00001317 if (!Base->isVirtual())
1318 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001319
Richard Smithb4e85ed2012-01-06 16:39:00 +00001320 SubobjectDesignator &D = Obj.Designator;
1321 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001322 return false;
1323
Richard Smithb4e85ed2012-01-06 16:39:00 +00001324 // Extract most-derived object and corresponding type.
1325 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1326 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1327 return false;
1328
1329 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001330 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001331 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1332 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001334 return true;
1335}
1336
1337/// Update LVal to refer to the given field, which must be a member of the type
1338/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001339static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001340 const FieldDecl *FD,
1341 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001342 if (!RL) {
1343 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001344 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001345 }
Richard Smith180f4792011-11-10 06:34:14 +00001346
1347 unsigned I = FD->getFieldIndex();
1348 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001349 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001350 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001351}
1352
Richard Smithd9b02e72012-01-25 22:15:11 +00001353/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001354static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001355 LValue &LVal,
1356 const IndirectFieldDecl *IFD) {
1357 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1358 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001359 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1360 return false;
1361 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001362}
1363
Richard Smith180f4792011-11-10 06:34:14 +00001364/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001365static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1366 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001367 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1368 // extension.
1369 if (Type->isVoidType() || Type->isFunctionType()) {
1370 Size = CharUnits::One();
1371 return true;
1372 }
1373
1374 if (!Type->isConstantSizeType()) {
1375 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001376 // FIXME: Better diagnostic.
1377 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001378 return false;
1379 }
1380
1381 Size = Info.Ctx.getTypeSizeInChars(Type);
1382 return true;
1383}
1384
1385/// Update a pointer value to model pointer arithmetic.
1386/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001387/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001388/// \param LVal - The pointer value to be updated.
1389/// \param EltTy - The pointee type represented by LVal.
1390/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1392 LValue &LVal, QualType EltTy,
1393 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001394 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001395 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001396 return false;
1397
1398 // Compute the new offset in the appropriate width.
1399 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001400 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001401 return true;
1402}
1403
Richard Smith86024012012-02-18 22:04:06 +00001404/// Update an lvalue to refer to a component of a complex number.
1405/// \param Info - Information about the ongoing evaluation.
1406/// \param LVal - The lvalue to be updated.
1407/// \param EltTy - The complex number's component type.
1408/// \param Imag - False for the real component, true for the imaginary.
1409static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1410 LValue &LVal, QualType EltTy,
1411 bool Imag) {
1412 if (Imag) {
1413 CharUnits SizeOfComponent;
1414 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1415 return false;
1416 LVal.Offset += SizeOfComponent;
1417 }
1418 LVal.addComplex(Info, E, EltTy, Imag);
1419 return true;
1420}
1421
Richard Smith03f96112011-10-24 17:54:18 +00001422/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001423static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1424 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001425 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001426 // If this is a parameter to an active constexpr function call, perform
1427 // argument substitution.
1428 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001429 // Assume arguments of a potential constant expression are unknown
1430 // constant expressions.
1431 if (Info.CheckingPotentialConstantExpression)
1432 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001433 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001434 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001435 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001436 }
Richard Smith177dce72011-11-01 16:57:24 +00001437 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1438 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001439 }
Richard Smith03f96112011-10-24 17:54:18 +00001440
Richard Smith099e7f62011-12-19 06:19:21 +00001441 // Dig out the initializer, and use the declaration which it's attached to.
1442 const Expr *Init = VD->getAnyInitializer(VD);
1443 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001444 // If we're checking a potential constant expression, the variable could be
1445 // initialized later.
1446 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001447 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001448 return false;
1449 }
1450
Richard Smith180f4792011-11-10 06:34:14 +00001451 // If we're currently evaluating the initializer of this declaration, use that
1452 // in-flight value.
1453 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001454 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001455 return !Result.isUninit();
1456 }
1457
Richard Smith65ac5982011-11-01 21:06:14 +00001458 // Never evaluate the initializer of a weak variable. We can't be sure that
1459 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001460 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001461 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001462 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001463 }
Richard Smith65ac5982011-11-01 21:06:14 +00001464
Richard Smith099e7f62011-12-19 06:19:21 +00001465 // Check that we can fold the initializer. In C++, we will have already done
1466 // this in the cases where it matters for conformance.
1467 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1468 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001469 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001470 Notes.size() + 1) << VD;
1471 Info.Note(VD->getLocation(), diag::note_declared_at);
1472 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001473 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001474 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001475 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001476 Notes.size() + 1) << VD;
1477 Info.Note(VD->getLocation(), diag::note_declared_at);
1478 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001479 }
Richard Smith03f96112011-10-24 17:54:18 +00001480
Richard Smith1aa0be82012-03-03 22:46:17 +00001481 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001482 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001483}
1484
Richard Smithc49bd112011-10-28 17:51:58 +00001485static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001486 Qualifiers Quals = T.getQualifiers();
1487 return Quals.hasConst() && !Quals.hasVolatile();
1488}
1489
Richard Smith59efe262011-11-11 04:05:33 +00001490/// Get the base index of the given base class within an APValue representing
1491/// the given derived class.
1492static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1493 const CXXRecordDecl *Base) {
1494 Base = Base->getCanonicalDecl();
1495 unsigned Index = 0;
1496 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1497 E = Derived->bases_end(); I != E; ++I, ++Index) {
1498 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1499 return Index;
1500 }
1501
1502 llvm_unreachable("base class missing from derived class's bases list");
1503}
1504
Richard Smithfe587202012-04-15 02:50:59 +00001505/// Extract the value of a character from a string literal. CharType is used to
1506/// determine the expected signedness of the result -- a string literal used to
1507/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1508/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001509static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001510 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001511 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1512 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1513 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001514 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001515
1516 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001517 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001518 if (Index < S->getLength())
1519 Value = S->getCodeUnit(Index);
1520 return Value;
1521}
1522
Richard Smithcc5d4f62011-11-07 09:22:26 +00001523/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001524static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001525 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001527 if (Sub.Invalid)
1528 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001530 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001531 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001532 (unsigned)diag::note_constexpr_read_past_end :
1533 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001534 return false;
1535 }
Richard Smithf64699e2011-11-11 08:28:03 +00001536 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001537 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001538 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1539 // This object might be initialized later.
1540 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541
Richard Smith0069b842012-03-10 00:28:11 +00001542 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001543 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001546 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001549 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001550 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001551 // Note, it should not be possible to form a pointer with a valid
1552 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001553 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001554 (unsigned)diag::note_constexpr_read_past_end :
1555 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001556 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001557 }
Richard Smithf3908f22012-02-17 03:35:37 +00001558 // An array object is represented as either an Array APValue or as an
1559 // LValue which refers to a string literal.
1560 if (O->isLValue()) {
1561 assert(I == N - 1 && "extracting subobject of character?");
1562 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001563 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001564 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001565 return true;
1566 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001567 O = &O->getArrayInitializedElt(Index);
1568 else
1569 O = &O->getArrayFiller();
1570 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001571 } else if (ObjType->isAnyComplexType()) {
1572 // Next subobject is a complex number.
1573 uint64_t Index = Sub.Entries[I].ArrayIndex;
1574 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001575 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001576 (unsigned)diag::note_constexpr_read_past_end :
1577 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1578 return false;
1579 }
1580 assert(I == N - 1 && "extracting subobject of scalar?");
1581 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001582 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001583 : O->getComplexIntReal());
1584 } else {
1585 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001586 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001587 : O->getComplexFloatReal());
1588 }
1589 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001590 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001591 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001592 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001593 << Field;
1594 Info.Note(Field->getLocation(), diag::note_declared_at);
1595 return false;
1596 }
1597
Richard Smith180f4792011-11-10 06:34:14 +00001598 // Next subobject is a class, struct or union field.
1599 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1600 if (RD->isUnion()) {
1601 const FieldDecl *UnionField = O->getUnionField();
1602 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001603 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001604 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001605 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001606 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001607 }
Richard Smith180f4792011-11-10 06:34:14 +00001608 O = &O->getUnionValue();
1609 } else
1610 O = &O->getStructField(Field->getFieldIndex());
1611 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001612
1613 if (ObjType.isVolatileQualified()) {
1614 if (Info.getLangOpts().CPlusPlus) {
1615 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001616 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001617 << 2 << Field;
1618 Info.Note(Field->getLocation(), diag::note_declared_at);
1619 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001620 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001621 }
1622 return false;
1623 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001624 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001625 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001626 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1627 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1628 O = &O->getStructBase(getBaseIndex(Derived, Base));
1629 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001630 }
Richard Smith180f4792011-11-10 06:34:14 +00001631
Richard Smithf48fdb02011-12-09 22:58:01 +00001632 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001633 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001634 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001635 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001636 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 }
1638
Richard Smith0069b842012-03-10 00:28:11 +00001639 // This may look super-stupid, but it serves an important purpose: if we just
1640 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1641 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1642 // object, which is destroyed by Tmp's destructor.
1643 APValue Tmp;
1644 O->swap(Tmp);
1645 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001646 return true;
1647}
1648
Richard Smithf15fda02012-02-02 01:16:57 +00001649/// Find the position where two subobject designators diverge, or equivalently
1650/// the length of the common initial subsequence.
1651static unsigned FindDesignatorMismatch(QualType ObjType,
1652 const SubobjectDesignator &A,
1653 const SubobjectDesignator &B,
1654 bool &WasArrayIndex) {
1655 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1656 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001657 if (!ObjType.isNull() &&
1658 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001659 // Next subobject is an array element.
1660 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1661 WasArrayIndex = true;
1662 return I;
1663 }
Richard Smith86024012012-02-18 22:04:06 +00001664 if (ObjType->isAnyComplexType())
1665 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1666 else
1667 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001668 } else {
1669 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1670 WasArrayIndex = false;
1671 return I;
1672 }
1673 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1674 // Next subobject is a field.
1675 ObjType = FD->getType();
1676 else
1677 // Next subobject is a base class.
1678 ObjType = QualType();
1679 }
1680 }
1681 WasArrayIndex = false;
1682 return I;
1683}
1684
1685/// Determine whether the given subobject designators refer to elements of the
1686/// same array object.
1687static bool AreElementsOfSameArray(QualType ObjType,
1688 const SubobjectDesignator &A,
1689 const SubobjectDesignator &B) {
1690 if (A.Entries.size() != B.Entries.size())
1691 return false;
1692
1693 bool IsArray = A.MostDerivedArraySize != 0;
1694 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1695 // A is a subobject of the array element.
1696 return false;
1697
1698 // If A (and B) designates an array element, the last entry will be the array
1699 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1700 // of length 1' case, and the entire path must match.
1701 bool WasArrayIndex;
1702 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1703 return CommonLength >= A.Entries.size() - IsArray;
1704}
1705
Richard Smith180f4792011-11-10 06:34:14 +00001706/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1707/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1708/// for looking up the glvalue referred to by an entity of reference type.
1709///
1710/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001711/// \param Conv - The expression for which we are performing the conversion.
1712/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001713/// \param Type - The type we expect this conversion to produce, before
1714/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001715/// \param LVal - The glvalue on which we are attempting to perform this action.
1716/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001717static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1718 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001719 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001720 if (LVal.Designator.Invalid)
1721 // A diagnostic will have already been produced.
1722 return false;
1723
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001724 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001725
Richard Smithf48fdb02011-12-09 22:58:01 +00001726 if (!LVal.Base) {
1727 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001728 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001729 return false;
1730 }
1731
Richard Smith83587db2012-02-15 02:18:13 +00001732 CallStackFrame *Frame = 0;
1733 if (LVal.CallIndex) {
1734 Frame = Info.getCallFrame(LVal.CallIndex);
1735 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001736 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001737 NoteLValueLocation(Info, LVal.Base);
1738 return false;
1739 }
1740 }
1741
Richard Smith7098cbd2011-12-21 05:04:46 +00001742 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1743 // is not a constant expression (even if the object is non-volatile). We also
1744 // apply this rule to C++98, in order to conform to the expected 'volatile'
1745 // semantics.
1746 if (Type.isVolatileQualified()) {
1747 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001748 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001749 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001750 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001751 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001752 }
Richard Smithc49bd112011-10-28 17:51:58 +00001753
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001754 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001755 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1756 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001757 // expressions are constant expressions too. Inside constexpr functions,
1758 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001759 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001760 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001761 if (VD) {
1762 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1763 VD = VDef;
1764 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001765 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001766 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001767 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001768 }
1769
Richard Smith7098cbd2011-12-21 05:04:46 +00001770 // DR1313: If the object is volatile-qualified but the glvalue was not,
1771 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001772 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001773 if (VT.isVolatileQualified()) {
1774 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001775 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001776 Info.Note(VD->getLocation(), diag::note_declared_at);
1777 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001778 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001779 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 return false;
1781 }
1782
1783 if (!isa<ParmVarDecl>(VD)) {
1784 if (VD->isConstexpr()) {
1785 // OK, we can read this variable.
1786 } else if (VT->isIntegralOrEnumerationType()) {
1787 if (!VT.isConstQualified()) {
1788 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001789 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001790 Info.Note(VD->getLocation(), diag::note_declared_at);
1791 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001792 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001793 }
1794 return false;
1795 }
1796 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1797 // We support folding of const floating-point types, in order to make
1798 // static const data members of such types (supported as an extension)
1799 // more useful.
1800 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001801 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001802 Info.Note(VD->getLocation(), diag::note_declared_at);
1803 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001804 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001805 }
1806 } else {
1807 // FIXME: Allow folding of values of any literal type in all languages.
1808 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001809 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001810 Info.Note(VD->getLocation(), diag::note_declared_at);
1811 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001812 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001813 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001815 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001816 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001817
Richard Smithf48fdb02011-12-09 22:58:01 +00001818 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001819 return false;
1820
Richard Smith47a1eed2011-10-29 20:57:55 +00001821 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001823
1824 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1825 // conversion. This happens when the declaration and the lvalue should be
1826 // considered synonymous, for instance when initializing an array of char
1827 // from a string literal. Continue as if the initializer lvalue was the
1828 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001829 assert(RVal.getLValueOffset().isZero() &&
1830 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001831 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001832
1833 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1834 Frame = Info.getCallFrame(CallIndex);
1835 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001836 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001837 NoteLValueLocation(Info, RVal.getLValueBase());
1838 return false;
1839 }
1840 } else {
1841 Frame = 0;
1842 }
Richard Smithc49bd112011-10-28 17:51:58 +00001843 }
1844
Richard Smith7098cbd2011-12-21 05:04:46 +00001845 // Volatile temporary objects cannot be read in constant expressions.
1846 if (Base->getType().isVolatileQualified()) {
1847 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001848 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001849 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1850 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001851 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001852 }
1853 return false;
1854 }
1855
Richard Smithcc5d4f62011-11-07 09:22:26 +00001856 if (Frame) {
1857 // If this is a temporary expression with a nontrivial initializer, grab the
1858 // value from the relevant stack frame.
1859 RVal = Frame->Temporaries[Base];
1860 } else if (const CompoundLiteralExpr *CLE
1861 = dyn_cast<CompoundLiteralExpr>(Base)) {
1862 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1863 // initializer until now for such expressions. Such an expression can't be
1864 // an ICE in C, so this only matters for fold.
1865 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1866 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1867 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001868 } else if (isa<StringLiteral>(Base)) {
1869 // We represent a string literal array as an lvalue pointing at the
1870 // corresponding expression, rather than building an array of chars.
1871 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001872 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001873 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001874 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001875 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001876 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001877
Richard Smithf48fdb02011-12-09 22:58:01 +00001878 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1879 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001880}
1881
Richard Smith59efe262011-11-11 04:05:33 +00001882/// Build an lvalue for the object argument of a member function call.
1883static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1884 LValue &This) {
1885 if (Object->getType()->isPointerType())
1886 return EvaluatePointer(Object, This, Info);
1887
1888 if (Object->isGLValue())
1889 return EvaluateLValue(Object, This, Info);
1890
Richard Smithe24f5fc2011-11-17 22:56:20 +00001891 if (Object->getType()->isLiteralType())
1892 return EvaluateTemporary(Object, This, Info);
1893
1894 return false;
1895}
1896
1897/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1898/// lvalue referring to the result.
1899///
1900/// \param Info - Information about the ongoing evaluation.
1901/// \param BO - The member pointer access operation.
1902/// \param LV - Filled in with a reference to the resulting object.
1903/// \param IncludeMember - Specifies whether the member itself is included in
1904/// the resulting LValue subobject designator. This is not possible when
1905/// creating a bound member function.
1906/// \return The field or method declaration to which the member pointer refers,
1907/// or 0 if evaluation fails.
1908static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1909 const BinaryOperator *BO,
1910 LValue &LV,
1911 bool IncludeMember = true) {
1912 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1913
Richard Smith745f5142012-01-27 01:14:48 +00001914 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1915 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001916 return 0;
1917
1918 MemberPtr MemPtr;
1919 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1920 return 0;
1921
1922 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1923 // member value, the behavior is undefined.
1924 if (!MemPtr.getDecl())
1925 return 0;
1926
Richard Smith745f5142012-01-27 01:14:48 +00001927 if (!EvalObjOK)
1928 return 0;
1929
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 if (MemPtr.isDerivedMember()) {
1931 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001932 // The end of the derived-to-base path for the base object must match the
1933 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001934 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001935 LV.Designator.Entries.size())
1936 return 0;
1937 unsigned PathLengthToMember =
1938 LV.Designator.Entries.size() - MemPtr.Path.size();
1939 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1940 const CXXRecordDecl *LVDecl = getAsBaseClass(
1941 LV.Designator.Entries[PathLengthToMember + I]);
1942 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1943 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1944 return 0;
1945 }
1946
1947 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001948 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1949 PathLengthToMember))
1950 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001951 } else if (!MemPtr.Path.empty()) {
1952 // Extend the LValue path with the member pointer's path.
1953 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1954 MemPtr.Path.size() + IncludeMember);
1955
1956 // Walk down to the appropriate base class.
1957 QualType LVType = BO->getLHS()->getType();
1958 if (const PointerType *PT = LVType->getAs<PointerType>())
1959 LVType = PT->getPointeeType();
1960 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1961 assert(RD && "member pointer access on non-class-type expression");
1962 // The first class in the path is that of the lvalue.
1963 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1964 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001965 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1966 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967 RD = Base;
1968 }
1969 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001970 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1971 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001972 }
1973
1974 // Add the member. Note that we cannot build bound member functions here.
1975 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001976 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1977 if (!HandleLValueMember(Info, BO, LV, FD))
1978 return 0;
1979 } else if (const IndirectFieldDecl *IFD =
1980 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1981 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1982 return 0;
1983 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001984 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001985 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 }
1987
1988 return MemPtr.getDecl();
1989}
1990
1991/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1992/// the provided lvalue, which currently refers to the base object.
1993static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1994 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001996 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001997 return false;
1998
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 QualType TargetQT = E->getType();
2000 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2001 TargetQT = PT->getPointeeType();
2002
2003 // Check this cast lands within the final derived-to-base subobject path.
2004 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002005 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 << D.MostDerivedType << TargetQT;
2007 return false;
2008 }
2009
Richard Smithe24f5fc2011-11-17 22:56:20 +00002010 // Check the type of the final cast. We don't need to check the path,
2011 // since a cast can only be formed if the path is unique.
2012 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002013 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2014 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002015 if (NewEntriesSize == D.MostDerivedPathLength)
2016 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2017 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002018 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002019 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002020 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002021 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002022 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002023 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002024
2025 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002026 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002027}
2028
Mike Stumpc4c90452009-10-27 22:09:17 +00002029namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002030enum EvalStmtResult {
2031 /// Evaluation failed.
2032 ESR_Failed,
2033 /// Hit a 'return' statement.
2034 ESR_Returned,
2035 /// Evaluation succeeded.
2036 ESR_Succeeded
2037};
2038}
2039
2040// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002041static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002042 const Stmt *S) {
2043 switch (S->getStmtClass()) {
2044 default:
2045 return ESR_Failed;
2046
2047 case Stmt::NullStmtClass:
2048 case Stmt::DeclStmtClass:
2049 return ESR_Succeeded;
2050
Richard Smithc1c5f272011-12-13 06:39:58 +00002051 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002052 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002053 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002054 return ESR_Failed;
2055 return ESR_Returned;
2056 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002057
2058 case Stmt::CompoundStmtClass: {
2059 const CompoundStmt *CS = cast<CompoundStmt>(S);
2060 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2061 BE = CS->body_end(); BI != BE; ++BI) {
2062 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2063 if (ESR != ESR_Succeeded)
2064 return ESR;
2065 }
2066 return ESR_Succeeded;
2067 }
2068 }
2069}
2070
Richard Smith61802452011-12-22 02:22:31 +00002071/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2072/// default constructor. If so, we'll fold it whether or not it's marked as
2073/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2074/// so we need special handling.
2075static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002076 const CXXConstructorDecl *CD,
2077 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002078 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2079 return false;
2080
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002081 // Value-initialization does not call a trivial default constructor, so such a
2082 // call is a core constant expression whether or not the constructor is
2083 // constexpr.
2084 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002085 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002086 // FIXME: If DiagDecl is an implicitly-declared special member function,
2087 // we should be much more explicit about why it's not constexpr.
2088 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2089 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2090 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002091 } else {
2092 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2093 }
2094 }
2095 return true;
2096}
2097
Richard Smithc1c5f272011-12-13 06:39:58 +00002098/// CheckConstexprFunction - Check that a function can be called in a constant
2099/// expression.
2100static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2101 const FunctionDecl *Declaration,
2102 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002103 // Potential constant expressions can contain calls to declared, but not yet
2104 // defined, constexpr functions.
2105 if (Info.CheckingPotentialConstantExpression && !Definition &&
2106 Declaration->isConstexpr())
2107 return false;
2108
Richard Smithc1c5f272011-12-13 06:39:58 +00002109 // Can we evaluate this function call?
2110 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2111 return true;
2112
2113 if (Info.getLangOpts().CPlusPlus0x) {
2114 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002115 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2116 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002117 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2118 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2119 << DiagDecl;
2120 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2121 } else {
2122 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2123 }
2124 return false;
2125}
2126
Richard Smith180f4792011-11-10 06:34:14 +00002127namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002128typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002129}
2130
2131/// EvaluateArgs - Evaluate the arguments to a function call.
2132static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2133 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002134 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002135 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002136 I != E; ++I) {
2137 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2138 // If we're checking for a potential constant expression, evaluate all
2139 // initializers even if some of them fail.
2140 if (!Info.keepEvaluatingAfterFailure())
2141 return false;
2142 Success = false;
2143 }
2144 }
2145 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002146}
2147
Richard Smithd0dccea2011-10-28 22:34:42 +00002148/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002149static bool HandleFunctionCall(SourceLocation CallLoc,
2150 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002151 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +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;
Richard Smithd0dccea2011-10-28 22:34:42 +00002156
Richard Smith745f5142012-01-27 01:14:48 +00002157 if (!Info.CheckCallLimit(CallLoc))
2158 return false;
2159
2160 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002161 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2162}
2163
Richard Smith180f4792011-11-10 06:34:14 +00002164/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002165static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002166 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002167 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002168 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002169 ArgVector ArgValues(Args.size());
2170 if (!EvaluateArgs(Args, ArgValues, Info))
2171 return false;
2172
Richard Smith745f5142012-01-27 01:14:48 +00002173 if (!Info.CheckCallLimit(CallLoc))
2174 return false;
2175
Richard Smith86c3ae42012-02-13 03:54:03 +00002176 const CXXRecordDecl *RD = Definition->getParent();
2177 if (RD->getNumVBases()) {
2178 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2179 return false;
2180 }
2181
Richard Smith745f5142012-01-27 01:14:48 +00002182 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002183
2184 // If it's a delegating constructor, just delegate.
2185 if (Definition->isDelegatingConstructor()) {
2186 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002187 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002188 }
2189
Richard Smith610a60c2012-01-10 04:32:03 +00002190 // For a trivial copy or move constructor, perform an APValue copy. This is
2191 // essential for unions, where the operations performed by the constructor
2192 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002193 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002194 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2195 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002196 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002197 RHS.setFrom(Info.Ctx, ArgValues[0]);
2198 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2199 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002200 }
2201
2202 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002203 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002204 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2205 std::distance(RD->field_begin(), RD->field_end()));
2206
John McCall8d59dee2012-05-01 00:38:49 +00002207 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002208 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2209
Richard Smith745f5142012-01-27 01:14:48 +00002210 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002211 unsigned BasesSeen = 0;
2212#ifndef NDEBUG
2213 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2214#endif
2215 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2216 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002217 LValue Subobject = This;
2218 APValue *Value = &Result;
2219
2220 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002221 if ((*I)->isBaseInitializer()) {
2222 QualType BaseType((*I)->getBaseClass(), 0);
2223#ifndef NDEBUG
2224 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002225 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002226 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2227 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2228 "base class initializers not in expected order");
2229 ++BaseIt;
2230#endif
John McCall8d59dee2012-05-01 00:38:49 +00002231 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2232 BaseType->getAsCXXRecordDecl(), &Layout))
2233 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002234 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002235 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002236 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2237 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002238 if (RD->isUnion()) {
2239 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002240 Value = &Result.getUnionValue();
2241 } else {
2242 Value = &Result.getStructField(FD->getFieldIndex());
2243 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002244 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002245 // Walk the indirect field decl's chain to find the object to initialize,
2246 // and make sure we've initialized every step along it.
2247 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2248 CE = IFD->chain_end();
2249 C != CE; ++C) {
2250 FieldDecl *FD = cast<FieldDecl>(*C);
2251 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2252 // Switch the union field if it differs. This happens if we had
2253 // preceding zero-initialization, and we're now initializing a union
2254 // subobject other than the first.
2255 // FIXME: In this case, the values of the other subobjects are
2256 // specified, since zero-initialization sets all padding bits to zero.
2257 if (Value->isUninit() ||
2258 (Value->isUnion() && Value->getUnionField() != FD)) {
2259 if (CD->isUnion())
2260 *Value = APValue(FD);
2261 else
2262 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2263 std::distance(CD->field_begin(), CD->field_end()));
2264 }
John McCall8d59dee2012-05-01 00:38:49 +00002265 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2266 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002267 if (CD->isUnion())
2268 Value = &Value->getUnionValue();
2269 else
2270 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002271 }
Richard Smith180f4792011-11-10 06:34:14 +00002272 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002273 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002274 }
Richard Smith745f5142012-01-27 01:14:48 +00002275
Richard Smith83587db2012-02-15 02:18:13 +00002276 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2277 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002278 ? CCEK_Constant : CCEK_MemberInit)) {
2279 // If we're checking for a potential constant expression, evaluate all
2280 // initializers even if some of them fail.
2281 if (!Info.keepEvaluatingAfterFailure())
2282 return false;
2283 Success = false;
2284 }
Richard Smith180f4792011-11-10 06:34:14 +00002285 }
2286
Richard Smith745f5142012-01-27 01:14:48 +00002287 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002288}
2289
Richard Smithd0dccea2011-10-28 22:34:42 +00002290namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002291class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002293 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002294public:
2295
Richard Smith1e12c592011-10-16 21:26:27 +00002296 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002297
2298 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002300 return true;
2301 }
2302
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002303 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2304 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002305 return Visit(E->getResultExpr());
2306 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002308 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002309 return true;
2310 return false;
2311 }
John McCallf85e1932011-06-15 23:02:42 +00002312 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002313 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002314 return true;
2315 return false;
2316 }
John McCallf85e1932011-06-15 23:02:42 +00002317
Mike Stumpc4c90452009-10-27 22:09:17 +00002318 // We don't want to evaluate BlockExprs multiple times, as they generate
2319 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002320 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2321 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2322 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002323 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2325 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2326 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2327 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2328 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2329 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002330 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002332 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002333 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002334 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2336 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2337 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2338 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002339 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2341 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2342 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2343 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2344 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002345 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002346 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002347 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002348 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002349 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002350
2351 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002352 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002353 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2354 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002356 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002357 return false;
2358 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002359
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002360 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002361};
2362
John McCall56ca35d2011-02-17 10:25:35 +00002363class OpaqueValueEvaluation {
2364 EvalInfo &info;
2365 OpaqueValueExpr *opaqueValue;
2366
2367public:
2368 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2369 Expr *value)
2370 : info(info), opaqueValue(opaqueValue) {
2371
2372 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002373 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002374 this->opaqueValue = 0;
2375 return;
2376 }
John McCall56ca35d2011-02-17 10:25:35 +00002377 }
2378
2379 bool hasError() const { return opaqueValue == 0; }
2380
2381 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002382 // FIXME: For a recursive constexpr call, an outer stack frame might have
2383 // been using this opaque value too, and will now have to re-evaluate the
2384 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002385 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2386 }
2387};
2388
Mike Stumpc4c90452009-10-27 22:09:17 +00002389} // end anonymous namespace
2390
Eli Friedman4efaa272008-11-12 09:44:48 +00002391//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002392// Generic Evaluation
2393//===----------------------------------------------------------------------===//
2394namespace {
2395
Richard Smithf48fdb02011-12-09 22:58:01 +00002396// FIXME: RetTy is always bool. Remove it.
2397template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002398class ExprEvaluatorBase
2399 : public ConstStmtVisitor<Derived, RetTy> {
2400private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002401 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002402 return static_cast<Derived*>(this)->Success(V, E);
2403 }
Richard Smith51201882011-12-30 21:15:51 +00002404 RetTy DerivedZeroInitialization(const Expr *E) {
2405 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002406 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002407
Richard Smith74e1ad92012-02-16 02:46:34 +00002408 // Check whether a conditional operator with a non-constant condition is a
2409 // potential constant expression. If neither arm is a potential constant
2410 // expression, then the conditional operator is not either.
2411 template<typename ConditionalOperator>
2412 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2413 assert(Info.CheckingPotentialConstantExpression);
2414
2415 // Speculatively evaluate both arms.
2416 {
2417 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2418 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2419
2420 StmtVisitorTy::Visit(E->getFalseExpr());
2421 if (Diag.empty())
2422 return;
2423
2424 Diag.clear();
2425 StmtVisitorTy::Visit(E->getTrueExpr());
2426 if (Diag.empty())
2427 return;
2428 }
2429
2430 Error(E, diag::note_constexpr_conditional_never_const);
2431 }
2432
2433
2434 template<typename ConditionalOperator>
2435 bool HandleConditionalOperator(const ConditionalOperator *E) {
2436 bool BoolResult;
2437 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2438 if (Info.CheckingPotentialConstantExpression)
2439 CheckPotentialConstantConditional(E);
2440 return false;
2441 }
2442
2443 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2444 return StmtVisitorTy::Visit(EvalExpr);
2445 }
2446
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447protected:
2448 EvalInfo &Info;
2449 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2450 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2451
Richard Smithdd1f29b2011-12-12 09:28:41 +00002452 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002453 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002454 }
2455
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002456 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2457
2458public:
2459 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2460
2461 EvalInfo &getEvalInfo() { return Info; }
2462
Richard Smithf48fdb02011-12-09 22:58:01 +00002463 /// Report an evaluation error. This should only be called when an error is
2464 /// first discovered. When propagating an error, just return false.
2465 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002466 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002467 return false;
2468 }
2469 bool Error(const Expr *E) {
2470 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2471 }
2472
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002473 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002474 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002475 }
2476 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002477 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002478 }
2479
2480 RetTy VisitParenExpr(const ParenExpr *E)
2481 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2482 RetTy VisitUnaryExtension(const UnaryOperator *E)
2483 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2484 RetTy VisitUnaryPlus(const UnaryOperator *E)
2485 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2486 RetTy VisitChooseExpr(const ChooseExpr *E)
2487 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2488 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2489 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002490 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2491 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002492 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2493 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002494 // We cannot create any objects for which cleanups are required, so there is
2495 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2496 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2497 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002498
Richard Smithc216a012011-12-12 12:46:16 +00002499 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2500 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2501 return static_cast<Derived*>(this)->VisitCastExpr(E);
2502 }
2503 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2504 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2505 return static_cast<Derived*>(this)->VisitCastExpr(E);
2506 }
2507
Richard Smithe24f5fc2011-11-17 22:56:20 +00002508 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2509 switch (E->getOpcode()) {
2510 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002511 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512
2513 case BO_Comma:
2514 VisitIgnoredValue(E->getLHS());
2515 return StmtVisitorTy::Visit(E->getRHS());
2516
2517 case BO_PtrMemD:
2518 case BO_PtrMemI: {
2519 LValue Obj;
2520 if (!HandleMemberPointerAccess(Info, E, Obj))
2521 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002522 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002523 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002524 return false;
2525 return DerivedSuccess(Result, E);
2526 }
2527 }
2528 }
2529
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002530 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002531 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002532 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2533 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002535
Richard Smith74e1ad92012-02-16 02:46:34 +00002536 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002537 }
2538
2539 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002540 bool IsBcpCall = false;
2541 // If the condition (ignoring parens) is a __builtin_constant_p call,
2542 // the result is a constant expression if it can be folded without
2543 // side-effects. This is an important GNU extension. See GCC PR38377
2544 // for discussion.
2545 if (const CallExpr *CallCE =
2546 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2547 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2548 IsBcpCall = true;
2549
2550 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2551 // constant expression; we can't check whether it's potentially foldable.
2552 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2553 return false;
2554
2555 FoldConstant Fold(Info);
2556
Richard Smith74e1ad92012-02-16 02:46:34 +00002557 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002558 return false;
2559
2560 if (IsBcpCall)
2561 Fold.Fold(Info);
2562
2563 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002564 }
2565
2566 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002567 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002568 if (!Value) {
2569 const Expr *Source = E->getSourceExpr();
2570 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002571 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002572 if (Source == E) { // sanity checking.
2573 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002575 }
2576 return StmtVisitorTy::Visit(Source);
2577 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002578 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002579 }
Richard Smithf10d9172011-10-11 21:43:33 +00002580
Richard Smithd0dccea2011-10-28 22:34:42 +00002581 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002583 QualType CalleeType = Callee->getType();
2584
Richard Smithd0dccea2011-10-28 22:34:42 +00002585 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002586 LValue *This = 0, ThisVal;
2587 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002588 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002589
Richard Smith59efe262011-11-11 04:05:33 +00002590 // Extract function decl and 'this' pointer from the callee.
2591 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002592 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002593 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2594 // Explicit bound member calls, such as x.f() or p->g();
2595 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002596 return false;
2597 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002598 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002599 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002600 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2601 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002602 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2603 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002604 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002605 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002606 return Error(Callee);
2607
2608 FD = dyn_cast<FunctionDecl>(Member);
2609 if (!FD)
2610 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002611 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002612 LValue Call;
2613 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002614 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002615
Richard Smithb4e85ed2012-01-06 16:39:00 +00002616 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002617 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002618 FD = dyn_cast_or_null<FunctionDecl>(
2619 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002620 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002621 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002622
2623 // Overloaded operator calls to member functions are represented as normal
2624 // calls with '*this' as the first argument.
2625 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2626 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002627 // FIXME: When selecting an implicit conversion for an overloaded
2628 // operator delete, we sometimes try to evaluate calls to conversion
2629 // operators without a 'this' parameter!
2630 if (Args.empty())
2631 return Error(E);
2632
Richard Smith59efe262011-11-11 04:05:33 +00002633 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2634 return false;
2635 This = &ThisVal;
2636 Args = Args.slice(1);
2637 }
2638
2639 // Don't call function pointers which have been cast to some other type.
2640 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002641 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002642 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002643 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002644
Richard Smithb04035a2012-02-01 02:39:43 +00002645 if (This && !This->checkSubobject(Info, E, CSK_This))
2646 return false;
2647
Richard Smith86c3ae42012-02-13 03:54:03 +00002648 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2649 // calls to such functions in constant expressions.
2650 if (This && !HasQualifier &&
2651 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2652 return Error(E, diag::note_constexpr_virtual_call);
2653
Richard Smithc1c5f272011-12-13 06:39:58 +00002654 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002655 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002656 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002657
Richard Smithc1c5f272011-12-13 06:39:58 +00002658 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002659 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2660 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002661 return false;
2662
Richard Smith83587db2012-02-15 02:18:13 +00002663 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002664 }
2665
Richard Smithc49bd112011-10-28 17:51:58 +00002666 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2667 return StmtVisitorTy::Visit(E->getInitializer());
2668 }
Richard Smithf10d9172011-10-11 21:43:33 +00002669 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002670 if (E->getNumInits() == 0)
2671 return DerivedZeroInitialization(E);
2672 if (E->getNumInits() == 1)
2673 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002674 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002675 }
2676 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002677 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002678 }
2679 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002680 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002681 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002682 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002683 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002684 }
Richard Smithf10d9172011-10-11 21:43:33 +00002685
Richard Smith180f4792011-11-10 06:34:14 +00002686 /// A member expression where the object is a prvalue is itself a prvalue.
2687 RetTy VisitMemberExpr(const MemberExpr *E) {
2688 assert(!E->isArrow() && "missing call to bound member function?");
2689
Richard Smith1aa0be82012-03-03 22:46:17 +00002690 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002691 if (!Evaluate(Val, Info, E->getBase()))
2692 return false;
2693
2694 QualType BaseTy = E->getBase()->getType();
2695
2696 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002697 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002698 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2699 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2700 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2701
Richard Smithb4e85ed2012-01-06 16:39:00 +00002702 SubobjectDesignator Designator(BaseTy);
2703 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002704
Richard Smithf48fdb02011-12-09 22:58:01 +00002705 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002706 DerivedSuccess(Val, E);
2707 }
2708
Richard Smithc49bd112011-10-28 17:51:58 +00002709 RetTy VisitCastExpr(const CastExpr *E) {
2710 switch (E->getCastKind()) {
2711 default:
2712 break;
2713
David Chisnall7a7ee302012-01-16 17:27:18 +00002714 case CK_AtomicToNonAtomic:
2715 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002716 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002717 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002718 return StmtVisitorTy::Visit(E->getSubExpr());
2719
2720 case CK_LValueToRValue: {
2721 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002722 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2723 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002724 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002725 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2726 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2727 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002728 return false;
2729 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002730 }
2731 }
2732
Richard Smithf48fdb02011-12-09 22:58:01 +00002733 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002734 }
2735
Richard Smith8327fad2011-10-24 18:44:57 +00002736 /// Visit a value which is evaluated, but whose value is ignored.
2737 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002738 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002739 if (!Evaluate(Scratch, Info, E))
2740 Info.EvalStatus.HasSideEffects = true;
2741 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002742};
2743
2744}
2745
2746//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002747// Common base class for lvalue and temporary evaluation.
2748//===----------------------------------------------------------------------===//
2749namespace {
2750template<class Derived>
2751class LValueExprEvaluatorBase
2752 : public ExprEvaluatorBase<Derived, bool> {
2753protected:
2754 LValue &Result;
2755 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2756 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2757
2758 bool Success(APValue::LValueBase B) {
2759 Result.set(B);
2760 return true;
2761 }
2762
2763public:
2764 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2765 ExprEvaluatorBaseTy(Info), Result(Result) {}
2766
Richard Smith1aa0be82012-03-03 22:46:17 +00002767 bool Success(const APValue &V, const Expr *E) {
2768 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002769 return true;
2770 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002771
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 bool VisitMemberExpr(const MemberExpr *E) {
2773 // Handle non-static data members.
2774 QualType BaseTy;
2775 if (E->isArrow()) {
2776 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2777 return false;
2778 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002779 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002780 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002781 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2782 return false;
2783 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002784 } else {
2785 if (!this->Visit(E->getBase()))
2786 return false;
2787 BaseTy = E->getBase()->getType();
2788 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789
Richard Smithd9b02e72012-01-25 22:15:11 +00002790 const ValueDecl *MD = E->getMemberDecl();
2791 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2792 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2793 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2794 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002795 if (!HandleLValueMember(this->Info, E, Result, FD))
2796 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002797 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002798 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2799 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002800 } else
2801 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002802
Richard Smithd9b02e72012-01-25 22:15:11 +00002803 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002804 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002805 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002806 RefValue))
2807 return false;
2808 return Success(RefValue, E);
2809 }
2810 return true;
2811 }
2812
2813 bool VisitBinaryOperator(const BinaryOperator *E) {
2814 switch (E->getOpcode()) {
2815 default:
2816 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2817
2818 case BO_PtrMemD:
2819 case BO_PtrMemI:
2820 return HandleMemberPointerAccess(this->Info, E, Result);
2821 }
2822 }
2823
2824 bool VisitCastExpr(const CastExpr *E) {
2825 switch (E->getCastKind()) {
2826 default:
2827 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2828
2829 case CK_DerivedToBase:
2830 case CK_UncheckedDerivedToBase: {
2831 if (!this->Visit(E->getSubExpr()))
2832 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002833
2834 // Now figure out the necessary offset to add to the base LV to get from
2835 // the derived class to the base class.
2836 QualType Type = E->getSubExpr()->getType();
2837
2838 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2839 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002840 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002841 *PathI))
2842 return false;
2843 Type = (*PathI)->getType();
2844 }
2845
2846 return true;
2847 }
2848 }
2849 }
2850};
2851}
2852
2853//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002854// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002855//
2856// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2857// function designators (in C), decl references to void objects (in C), and
2858// temporaries (if building with -Wno-address-of-temporary).
2859//
2860// LValue evaluation produces values comprising a base expression of one of the
2861// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002862// - Declarations
2863// * VarDecl
2864// * FunctionDecl
2865// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002866// * CompoundLiteralExpr in C
2867// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002868// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002869// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002870// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002871// * ObjCEncodeExpr
2872// * AddrLabelExpr
2873// * BlockExpr
2874// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002875// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002876// * Any Expr, with a CallIndex indicating the function in which the temporary
2877// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002878// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002879//===----------------------------------------------------------------------===//
2880namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002881class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002882 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002883public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002884 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2885 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002886
Richard Smithc49bd112011-10-28 17:51:58 +00002887 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2888
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002889 bool VisitDeclRefExpr(const DeclRefExpr *E);
2890 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002891 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002892 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2893 bool VisitMemberExpr(const MemberExpr *E);
2894 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2895 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002896 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002897 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002898 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2899 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002900 bool VisitUnaryReal(const UnaryOperator *E);
2901 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002902
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002903 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002904 switch (E->getCastKind()) {
2905 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002906 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002907
Eli Friedmandb924222011-10-11 00:13:24 +00002908 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002909 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002910 if (!Visit(E->getSubExpr()))
2911 return false;
2912 Result.Designator.setInvalid();
2913 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002914
Richard Smithe24f5fc2011-11-17 22:56:20 +00002915 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002916 if (!Visit(E->getSubExpr()))
2917 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002918 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002919 }
2920 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002921};
2922} // end anonymous namespace
2923
Richard Smithc49bd112011-10-28 17:51:58 +00002924/// Evaluate an expression as an lvalue. This can be legitimately called on
2925/// expressions which are not glvalues, in a few cases:
2926/// * function designators in C,
2927/// * "extern void" objects,
2928/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002929static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002930 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2931 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2932 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002933 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002934}
2935
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002936bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002937 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2938 return Success(FD);
2939 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002940 return VisitVarDecl(E, VD);
2941 return Error(E);
2942}
Richard Smith436c8892011-10-24 23:14:33 +00002943
Richard Smithc49bd112011-10-28 17:51:58 +00002944bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002945 if (!VD->getType()->isReferenceType()) {
2946 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002947 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002948 return true;
2949 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002950 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002951 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002952
Richard Smith1aa0be82012-03-03 22:46:17 +00002953 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002954 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2955 return false;
2956 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002957}
2958
Richard Smithbd552ef2011-10-31 05:52:43 +00002959bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2960 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002961 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002962 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002963 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2964
Richard Smith83587db2012-02-15 02:18:13 +00002965 Result.set(E, Info.CurrentCall->Index);
2966 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2967 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002968 }
2969
2970 // Materialization of an lvalue temporary occurs when we need to force a copy
2971 // (for instance, if it's a bitfield).
2972 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2973 if (!Visit(E->GetTemporaryExpr()))
2974 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002975 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002976 Info.CurrentCall->Temporaries[E]))
2977 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002978 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002979 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002980}
2981
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002982bool
2983LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002984 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2985 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2986 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002987 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002988}
2989
Richard Smith47d21452011-12-27 12:18:28 +00002990bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2991 if (E->isTypeOperand())
2992 return Success(E);
2993 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2994 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002995 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002996 << E->getExprOperand()->getType()
2997 << E->getExprOperand()->getSourceRange();
2998 return false;
2999 }
3000 return Success(E);
3001}
3002
Francois Pichete275a182012-04-16 04:08:35 +00003003bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3004 return Success(E);
3005}
3006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003007bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003008 // Handle static data members.
3009 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3010 VisitIgnoredValue(E->getBase());
3011 return VisitVarDecl(E, VD);
3012 }
3013
Richard Smithd0dccea2011-10-28 22:34:42 +00003014 // Handle static member functions.
3015 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3016 if (MD->isStatic()) {
3017 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003018 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003019 }
3020 }
3021
Richard Smith180f4792011-11-10 06:34:14 +00003022 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003023 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003024}
3025
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003026bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003027 // FIXME: Deal with vectors as array subscript bases.
3028 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003029 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003030
Anders Carlsson3068d112008-11-16 19:01:22 +00003031 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003032 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Anders Carlsson3068d112008-11-16 19:01:22 +00003034 APSInt Index;
3035 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003036 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003037 int64_t IndexValue
3038 = Index.isSigned() ? Index.getSExtValue()
3039 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003040
Richard Smithb4e85ed2012-01-06 16:39:00 +00003041 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003042}
Eli Friedman4efaa272008-11-12 09:44:48 +00003043
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003044bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003045 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003046}
3047
Richard Smith86024012012-02-18 22:04:06 +00003048bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3049 if (!Visit(E->getSubExpr()))
3050 return false;
3051 // __real is a no-op on scalar lvalues.
3052 if (E->getSubExpr()->getType()->isAnyComplexType())
3053 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3054 return true;
3055}
3056
3057bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3058 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3059 "lvalue __imag__ on scalar?");
3060 if (!Visit(E->getSubExpr()))
3061 return false;
3062 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3063 return true;
3064}
3065
Eli Friedman4efaa272008-11-12 09:44:48 +00003066//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003067// Pointer Evaluation
3068//===----------------------------------------------------------------------===//
3069
Anders Carlssonc754aa62008-07-08 05:13:58 +00003070namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003071class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003072 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003073 LValue &Result;
3074
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003075 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003076 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003077 return true;
3078 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003079public:
Mike Stump1eb44332009-09-09 15:08:12 +00003080
John McCallefdb83e2010-05-07 21:00:08 +00003081 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003082 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003083
Richard Smith1aa0be82012-03-03 22:46:17 +00003084 bool Success(const APValue &V, const Expr *E) {
3085 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003086 return true;
3087 }
Richard Smith51201882011-12-30 21:15:51 +00003088 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003089 return Success((Expr*)0);
3090 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003091
John McCallefdb83e2010-05-07 21:00:08 +00003092 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003093 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003094 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003095 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003096 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003097 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003098 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003099 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003100 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003101 bool VisitCallExpr(const CallExpr *E);
3102 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003103 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003104 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003105 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003106 }
Richard Smith180f4792011-11-10 06:34:14 +00003107 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3108 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003109 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003110 Result = *Info.CurrentCall->This;
3111 return true;
3112 }
John McCall56ca35d2011-02-17 10:25:35 +00003113
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003114 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003115};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003116} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003117
John McCallefdb83e2010-05-07 21:00:08 +00003118static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003119 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003120 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003121}
3122
John McCallefdb83e2010-05-07 21:00:08 +00003123bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003124 if (E->getOpcode() != BO_Add &&
3125 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003126 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003128 const Expr *PExp = E->getLHS();
3129 const Expr *IExp = E->getRHS();
3130 if (IExp->getType()->isPointerType())
3131 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003132
Richard Smith745f5142012-01-27 01:14:48 +00003133 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3134 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003135 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003136
John McCallefdb83e2010-05-07 21:00:08 +00003137 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003138 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003139 return false;
3140 int64_t AdditionalOffset
3141 = Offset.isSigned() ? Offset.getSExtValue()
3142 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003143 if (E->getOpcode() == BO_Sub)
3144 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003145
Richard Smith180f4792011-11-10 06:34:14 +00003146 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003147 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3148 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003149}
Eli Friedman4efaa272008-11-12 09:44:48 +00003150
John McCallefdb83e2010-05-07 21:00:08 +00003151bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3152 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003153}
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003155bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3156 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003157
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003158 switch (E->getCastKind()) {
3159 default:
3160 break;
3161
John McCall2de56d12010-08-25 11:45:40 +00003162 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003163 case CK_CPointerToObjCPointerCast:
3164 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003165 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003166 if (!Visit(SubExpr))
3167 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003168 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3169 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3170 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003171 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003172 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003173 if (SubExpr->getType()->isVoidPointerType())
3174 CCEDiag(E, diag::note_constexpr_invalid_cast)
3175 << 3 << SubExpr->getType();
3176 else
3177 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3178 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003179 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003180
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003181 case CK_DerivedToBase:
3182 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003183 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003184 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003185 if (!Result.Base && Result.Offset.isZero())
3186 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003187
Richard Smith180f4792011-11-10 06:34:14 +00003188 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003189 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003190 QualType Type =
3191 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003192
Richard Smith180f4792011-11-10 06:34:14 +00003193 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003194 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003195 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3196 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003197 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003198 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003199 }
3200
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003201 return true;
3202 }
3203
Richard Smithe24f5fc2011-11-17 22:56:20 +00003204 case CK_BaseToDerived:
3205 if (!Visit(E->getSubExpr()))
3206 return false;
3207 if (!Result.Base && Result.Offset.isZero())
3208 return true;
3209 return HandleBaseToDerivedCast(Info, E, Result);
3210
Richard Smith47a1eed2011-10-29 20:57:55 +00003211 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003212 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003213 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003214
John McCall2de56d12010-08-25 11:45:40 +00003215 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003216 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3217
Richard Smith1aa0be82012-03-03 22:46:17 +00003218 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003219 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003220 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003221
John McCallefdb83e2010-05-07 21:00:08 +00003222 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003223 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3224 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003225 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003226 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003227 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003228 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003229 return true;
3230 } else {
3231 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003232 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003233 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003234 }
3235 }
John McCall2de56d12010-08-25 11:45:40 +00003236 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003237 if (SubExpr->isGLValue()) {
3238 if (!EvaluateLValue(SubExpr, Result, Info))
3239 return false;
3240 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003241 Result.set(SubExpr, Info.CurrentCall->Index);
3242 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3243 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003244 return false;
3245 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003246 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003247 if (const ConstantArrayType *CAT
3248 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3249 Result.addArray(Info, E, CAT);
3250 else
3251 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003252 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003253
John McCall2de56d12010-08-25 11:45:40 +00003254 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003255 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003256 }
3257
Richard Smithc49bd112011-10-28 17:51:58 +00003258 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003259}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003260
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003261bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003262 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003263 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003265 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003266}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003267
3268//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003269// Member Pointer Evaluation
3270//===----------------------------------------------------------------------===//
3271
3272namespace {
3273class MemberPointerExprEvaluator
3274 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3275 MemberPtr &Result;
3276
3277 bool Success(const ValueDecl *D) {
3278 Result = MemberPtr(D);
3279 return true;
3280 }
3281public:
3282
3283 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3284 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3285
Richard Smith1aa0be82012-03-03 22:46:17 +00003286 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003287 Result.setFrom(V);
3288 return true;
3289 }
Richard Smith51201882011-12-30 21:15:51 +00003290 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003291 return Success((const ValueDecl*)0);
3292 }
3293
3294 bool VisitCastExpr(const CastExpr *E);
3295 bool VisitUnaryAddrOf(const UnaryOperator *E);
3296};
3297} // end anonymous namespace
3298
3299static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3300 EvalInfo &Info) {
3301 assert(E->isRValue() && E->getType()->isMemberPointerType());
3302 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3303}
3304
3305bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3306 switch (E->getCastKind()) {
3307 default:
3308 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3309
3310 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003311 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003312 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003313
3314 case CK_BaseToDerivedMemberPointer: {
3315 if (!Visit(E->getSubExpr()))
3316 return false;
3317 if (E->path_empty())
3318 return true;
3319 // Base-to-derived member pointer casts store the path in derived-to-base
3320 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3321 // the wrong end of the derived->base arc, so stagger the path by one class.
3322 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3323 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3324 PathI != PathE; ++PathI) {
3325 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3326 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3327 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003328 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003329 }
3330 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3331 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003332 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003333 return true;
3334 }
3335
3336 case CK_DerivedToBaseMemberPointer:
3337 if (!Visit(E->getSubExpr()))
3338 return false;
3339 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3340 PathE = E->path_end(); PathI != PathE; ++PathI) {
3341 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3342 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3343 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003344 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003345 }
3346 return true;
3347 }
3348}
3349
3350bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3351 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3352 // member can be formed.
3353 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3354}
3355
3356//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003357// Record Evaluation
3358//===----------------------------------------------------------------------===//
3359
3360namespace {
3361 class RecordExprEvaluator
3362 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3363 const LValue &This;
3364 APValue &Result;
3365 public:
3366
3367 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3368 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3369
Richard Smith1aa0be82012-03-03 22:46:17 +00003370 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003371 Result = V;
3372 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003373 }
Richard Smith51201882011-12-30 21:15:51 +00003374 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003375
Richard Smith59efe262011-11-11 04:05:33 +00003376 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003377 bool VisitInitListExpr(const InitListExpr *E);
3378 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3379 };
3380}
3381
Richard Smith51201882011-12-30 21:15:51 +00003382/// Perform zero-initialization on an object of non-union class type.
3383/// C++11 [dcl.init]p5:
3384/// To zero-initialize an object or reference of type T means:
3385/// [...]
3386/// -- if T is a (possibly cv-qualified) non-union class type,
3387/// each non-static data member and each base-class subobject is
3388/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003389static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3390 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003391 const LValue &This, APValue &Result) {
3392 assert(!RD->isUnion() && "Expected non-union class type");
3393 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3394 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3395 std::distance(RD->field_begin(), RD->field_end()));
3396
John McCall8d59dee2012-05-01 00:38:49 +00003397 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003398 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3399
3400 if (CD) {
3401 unsigned Index = 0;
3402 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003403 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003404 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3405 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003406 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3407 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003408 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003409 Result.getStructBase(Index)))
3410 return false;
3411 }
3412 }
3413
Richard Smithb4e85ed2012-01-06 16:39:00 +00003414 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3415 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003416 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003417 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003418 continue;
3419
3420 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003421 if (!HandleLValueMember(Info, E, Subobject, &*I, &Layout))
3422 return false;
Richard Smith51201882011-12-30 21:15:51 +00003423
David Blaikie262bc182012-04-30 02:36:29 +00003424 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003425 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003426 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003427 return false;
3428 }
3429
3430 return true;
3431}
3432
3433bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3434 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003435 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003436 if (RD->isUnion()) {
3437 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3438 // object's first non-static named data member is zero-initialized
3439 RecordDecl::field_iterator I = RD->field_begin();
3440 if (I == RD->field_end()) {
3441 Result = APValue((const FieldDecl*)0);
3442 return true;
3443 }
3444
3445 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003446 if (!HandleLValueMember(Info, E, Subobject, &*I))
3447 return false;
David Blaikie262bc182012-04-30 02:36:29 +00003448 Result = APValue(&*I);
3449 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003450 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003451 }
3452
Richard Smithce582fe2012-02-17 00:44:16 +00003453 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003454 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003455 return false;
3456 }
3457
Richard Smithb4e85ed2012-01-06 16:39:00 +00003458 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003459}
3460
Richard Smith59efe262011-11-11 04:05:33 +00003461bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3462 switch (E->getCastKind()) {
3463 default:
3464 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3465
3466 case CK_ConstructorConversion:
3467 return Visit(E->getSubExpr());
3468
3469 case CK_DerivedToBase:
3470 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003471 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003472 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003473 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003474 if (!DerivedObject.isStruct())
3475 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003476
3477 // Derived-to-base rvalue conversion: just slice off the derived part.
3478 APValue *Value = &DerivedObject;
3479 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3480 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3481 PathE = E->path_end(); PathI != PathE; ++PathI) {
3482 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3483 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3484 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3485 RD = Base;
3486 }
3487 Result = *Value;
3488 return true;
3489 }
3490 }
3491}
3492
Richard Smith180f4792011-11-10 06:34:14 +00003493bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003494 // Cannot constant-evaluate std::initializer_list inits.
3495 if (E->initializesStdInitializerList())
3496 return false;
3497
Richard Smith180f4792011-11-10 06:34:14 +00003498 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003499 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003500 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3501
3502 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003503 const FieldDecl *Field = E->getInitializedFieldInUnion();
3504 Result = APValue(Field);
3505 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003506 return true;
Richard Smithec789162012-01-12 18:54:33 +00003507
3508 // If the initializer list for a union does not contain any elements, the
3509 // first element of the union is value-initialized.
3510 ImplicitValueInitExpr VIE(Field->getType());
3511 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3512
Richard Smith180f4792011-11-10 06:34:14 +00003513 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003514 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3515 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003516 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003517 }
3518
3519 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3520 "initializer list for class with base classes");
3521 Result = APValue(APValue::UninitStruct(), 0,
3522 std::distance(RD->field_begin(), RD->field_end()));
3523 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003524 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003525 for (RecordDecl::field_iterator Field = RD->field_begin(),
3526 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3527 // Anonymous bit-fields are not considered members of the class for
3528 // purposes of aggregate initialization.
3529 if (Field->isUnnamedBitfield())
3530 continue;
3531
3532 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003533
Richard Smith745f5142012-01-27 01:14:48 +00003534 bool HaveInit = ElementNo < E->getNumInits();
3535
3536 // FIXME: Diagnostics here should point to the end of the initializer
3537 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003538 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
3539 Subobject, &*Field, &Layout))
3540 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003541
3542 // Perform an implicit value-initialization for members beyond the end of
3543 // the initializer list.
3544 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3545
Richard Smith83587db2012-02-15 02:18:13 +00003546 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003547 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003548 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3549 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003550 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003551 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003552 }
3553 }
3554
Richard Smith745f5142012-01-27 01:14:48 +00003555 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003556}
3557
3558bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3559 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003560 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3561
Richard Smith51201882011-12-30 21:15:51 +00003562 bool ZeroInit = E->requiresZeroInitialization();
3563 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003564 // If we've already performed zero-initialization, we're already done.
3565 if (!Result.isUninit())
3566 return true;
3567
Richard Smith51201882011-12-30 21:15:51 +00003568 if (ZeroInit)
3569 return ZeroInitialization(E);
3570
Richard Smith61802452011-12-22 02:22:31 +00003571 const CXXRecordDecl *RD = FD->getParent();
3572 if (RD->isUnion())
3573 Result = APValue((FieldDecl*)0);
3574 else
3575 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3576 std::distance(RD->field_begin(), RD->field_end()));
3577 return true;
3578 }
3579
Richard Smith180f4792011-11-10 06:34:14 +00003580 const FunctionDecl *Definition = 0;
3581 FD->getBody(Definition);
3582
Richard Smithc1c5f272011-12-13 06:39:58 +00003583 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3584 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003585
Richard Smith610a60c2012-01-10 04:32:03 +00003586 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003587 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003588 if (const MaterializeTemporaryExpr *ME
3589 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3590 return Visit(ME->GetTemporaryExpr());
3591
Richard Smith51201882011-12-30 21:15:51 +00003592 if (ZeroInit && !ZeroInitialization(E))
3593 return false;
3594
Richard Smith180f4792011-11-10 06:34:14 +00003595 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003596 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003597 cast<CXXConstructorDecl>(Definition), Info,
3598 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003599}
3600
3601static bool EvaluateRecord(const Expr *E, const LValue &This,
3602 APValue &Result, EvalInfo &Info) {
3603 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003604 "can't evaluate expression as a record rvalue");
3605 return RecordExprEvaluator(Info, This, Result).Visit(E);
3606}
3607
3608//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003609// Temporary Evaluation
3610//
3611// Temporaries are represented in the AST as rvalues, but generally behave like
3612// lvalues. The full-object of which the temporary is a subobject is implicitly
3613// materialized so that a reference can bind to it.
3614//===----------------------------------------------------------------------===//
3615namespace {
3616class TemporaryExprEvaluator
3617 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3618public:
3619 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3620 LValueExprEvaluatorBaseTy(Info, Result) {}
3621
3622 /// Visit an expression which constructs the value of this temporary.
3623 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003624 Result.set(E, Info.CurrentCall->Index);
3625 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003626 }
3627
3628 bool VisitCastExpr(const CastExpr *E) {
3629 switch (E->getCastKind()) {
3630 default:
3631 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3632
3633 case CK_ConstructorConversion:
3634 return VisitConstructExpr(E->getSubExpr());
3635 }
3636 }
3637 bool VisitInitListExpr(const InitListExpr *E) {
3638 return VisitConstructExpr(E);
3639 }
3640 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3641 return VisitConstructExpr(E);
3642 }
3643 bool VisitCallExpr(const CallExpr *E) {
3644 return VisitConstructExpr(E);
3645 }
3646};
3647} // end anonymous namespace
3648
3649/// Evaluate an expression of record type as a temporary.
3650static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003651 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003652 return TemporaryExprEvaluator(Info, Result).Visit(E);
3653}
3654
3655//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003656// Vector Evaluation
3657//===----------------------------------------------------------------------===//
3658
3659namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003660 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003661 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3662 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003663 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003664
Richard Smith07fc6572011-10-22 21:10:00 +00003665 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3666 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Richard Smith07fc6572011-10-22 21:10:00 +00003668 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3669 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3670 // FIXME: remove this APValue copy.
3671 Result = APValue(V.data(), V.size());
3672 return true;
3673 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003674 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003675 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003676 Result = V;
3677 return true;
3678 }
Richard Smith51201882011-12-30 21:15:51 +00003679 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003680
Richard Smith07fc6572011-10-22 21:10:00 +00003681 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003682 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003683 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003684 bool VisitInitListExpr(const InitListExpr *E);
3685 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003686 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003687 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003688 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003689 };
3690} // end anonymous namespace
3691
3692static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003693 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003694 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003695}
3696
Richard Smith07fc6572011-10-22 21:10:00 +00003697bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3698 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003699 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003700
Richard Smithd62ca372011-12-06 22:44:34 +00003701 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003702 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003703
Eli Friedman46a52322011-03-25 00:43:55 +00003704 switch (E->getCastKind()) {
3705 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003706 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003707 if (SETy->isIntegerType()) {
3708 APSInt IntResult;
3709 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003710 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003711 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003712 } else if (SETy->isRealFloatingType()) {
3713 APFloat F(0.0);
3714 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003715 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003716 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003717 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003718 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003719 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003720
3721 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003722 SmallVector<APValue, 4> Elts(NElts, Val);
3723 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003724 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003725 case CK_BitCast: {
3726 // Evaluate the operand into an APInt we can extract from.
3727 llvm::APInt SValInt;
3728 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3729 return false;
3730 // Extract the elements
3731 QualType EltTy = VTy->getElementType();
3732 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3733 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3734 SmallVector<APValue, 4> Elts;
3735 if (EltTy->isRealFloatingType()) {
3736 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3737 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3738 unsigned FloatEltSize = EltSize;
3739 if (&Sem == &APFloat::x87DoubleExtended)
3740 FloatEltSize = 80;
3741 for (unsigned i = 0; i < NElts; i++) {
3742 llvm::APInt Elt;
3743 if (BigEndian)
3744 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3745 else
3746 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3747 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3748 }
3749 } else if (EltTy->isIntegerType()) {
3750 for (unsigned i = 0; i < NElts; i++) {
3751 llvm::APInt Elt;
3752 if (BigEndian)
3753 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3754 else
3755 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3756 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3757 }
3758 } else {
3759 return Error(E);
3760 }
3761 return Success(Elts, E);
3762 }
Eli Friedman46a52322011-03-25 00:43:55 +00003763 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003764 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003765 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003766}
3767
Richard Smith07fc6572011-10-22 21:10:00 +00003768bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003769VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003770 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003771 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003772 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003773
Nate Begeman59b5da62009-01-18 03:20:47 +00003774 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003775 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003776
Eli Friedman3edd5a92012-01-03 23:24:20 +00003777 // The number of initializers can be less than the number of
3778 // vector elements. For OpenCL, this can be due to nested vector
3779 // initialization. For GCC compatibility, missing trailing elements
3780 // should be initialized with zeroes.
3781 unsigned CountInits = 0, CountElts = 0;
3782 while (CountElts < NumElements) {
3783 // Handle nested vector initialization.
3784 if (CountInits < NumInits
3785 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3786 APValue v;
3787 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3788 return Error(E);
3789 unsigned vlen = v.getVectorLength();
3790 for (unsigned j = 0; j < vlen; j++)
3791 Elements.push_back(v.getVectorElt(j));
3792 CountElts += vlen;
3793 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003794 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003795 if (CountInits < NumInits) {
3796 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003797 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003798 } else // trailing integer zero.
3799 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3800 Elements.push_back(APValue(sInt));
3801 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003802 } else {
3803 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003804 if (CountInits < NumInits) {
3805 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003806 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003807 } else // trailing float zero.
3808 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3809 Elements.push_back(APValue(f));
3810 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003811 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003812 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003813 }
Richard Smith07fc6572011-10-22 21:10:00 +00003814 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003815}
3816
Richard Smith07fc6572011-10-22 21:10:00 +00003817bool
Richard Smith51201882011-12-30 21:15:51 +00003818VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003819 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003820 QualType EltTy = VT->getElementType();
3821 APValue ZeroElement;
3822 if (EltTy->isIntegerType())
3823 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3824 else
3825 ZeroElement =
3826 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3827
Chris Lattner5f9e2722011-07-23 10:55:15 +00003828 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003829 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003830}
3831
Richard Smith07fc6572011-10-22 21:10:00 +00003832bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003833 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003834 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003835}
3836
Nate Begeman59b5da62009-01-18 03:20:47 +00003837//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003838// Array Evaluation
3839//===----------------------------------------------------------------------===//
3840
3841namespace {
3842 class ArrayExprEvaluator
3843 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003844 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003845 APValue &Result;
3846 public:
3847
Richard Smith180f4792011-11-10 06:34:14 +00003848 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3849 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003850
3851 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003852 assert((V.isArray() || V.isLValue()) &&
3853 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003854 Result = V;
3855 return true;
3856 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003857
Richard Smith51201882011-12-30 21:15:51 +00003858 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003859 const ConstantArrayType *CAT =
3860 Info.Ctx.getAsConstantArrayType(E->getType());
3861 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003862 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003863
3864 Result = APValue(APValue::UninitArray(), 0,
3865 CAT->getSize().getZExtValue());
3866 if (!Result.hasArrayFiller()) return true;
3867
Richard Smith51201882011-12-30 21:15:51 +00003868 // Zero-initialize all elements.
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 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003872 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003873 }
3874
Richard Smithcc5d4f62011-11-07 09:22:26 +00003875 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003876 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003877 };
3878} // end anonymous namespace
3879
Richard Smith180f4792011-11-10 06:34:14 +00003880static bool EvaluateArray(const Expr *E, const LValue &This,
3881 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003882 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003883 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003884}
3885
3886bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3887 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3888 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003889 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003890
Richard Smith974c5f92011-12-22 01:07:19 +00003891 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3892 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003893 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003894 LValue LV;
3895 if (!EvaluateLValue(E->getInit(0), LV, Info))
3896 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003897 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003898 LV.moveInto(Val);
3899 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003900 }
3901
Richard Smith745f5142012-01-27 01:14:48 +00003902 bool Success = true;
3903
Richard Smithcc5d4f62011-11-07 09:22:26 +00003904 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3905 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003906 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003907 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003908 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003909 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003910 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003911 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3912 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003913 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3914 CAT->getElementType(), 1)) {
3915 if (!Info.keepEvaluatingAfterFailure())
3916 return false;
3917 Success = false;
3918 }
Richard Smith180f4792011-11-10 06:34:14 +00003919 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003920
Richard Smith745f5142012-01-27 01:14:48 +00003921 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003922 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003923 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3924 // but sometimes does:
3925 // struct S { constexpr S() : p(&p) {} void *p; };
3926 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003927 return EvaluateInPlace(Result.getArrayFiller(), Info,
3928 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003929}
3930
Richard Smithe24f5fc2011-11-17 22:56:20 +00003931bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3932 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3933 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003934 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003935
Richard Smithec789162012-01-12 18:54:33 +00003936 bool HadZeroInit = !Result.isUninit();
3937 if (!HadZeroInit)
3938 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003939 if (!Result.hasArrayFiller())
3940 return true;
3941
3942 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003943
Richard Smith51201882011-12-30 21:15:51 +00003944 bool ZeroInit = E->requiresZeroInitialization();
3945 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003946 if (HadZeroInit)
3947 return true;
3948
Richard Smith51201882011-12-30 21:15:51 +00003949 if (ZeroInit) {
3950 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003951 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003952 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003953 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003954 }
3955
Richard Smith61802452011-12-22 02:22:31 +00003956 const CXXRecordDecl *RD = FD->getParent();
3957 if (RD->isUnion())
3958 Result.getArrayFiller() = APValue((FieldDecl*)0);
3959 else
3960 Result.getArrayFiller() =
3961 APValue(APValue::UninitStruct(), RD->getNumBases(),
3962 std::distance(RD->field_begin(), RD->field_end()));
3963 return true;
3964 }
3965
Richard Smithe24f5fc2011-11-17 22:56:20 +00003966 const FunctionDecl *Definition = 0;
3967 FD->getBody(Definition);
3968
Richard Smithc1c5f272011-12-13 06:39:58 +00003969 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3970 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003971
3972 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3973 // but sometimes does:
3974 // struct S { constexpr S() : p(&p) {} void *p; };
3975 // S s[10];
3976 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003977 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003978
Richard Smithec789162012-01-12 18:54:33 +00003979 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003980 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003981 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003982 return false;
3983 }
3984
Richard Smithe24f5fc2011-11-17 22:56:20 +00003985 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003986 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003987 cast<CXXConstructorDecl>(Definition),
3988 Info, Result.getArrayFiller());
3989}
3990
Richard Smithcc5d4f62011-11-07 09:22:26 +00003991//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003992// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003993//
3994// As a GNU extension, we support casting pointers to sufficiently-wide integer
3995// types and back in constant folding. Integer values are thus represented
3996// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003997//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003998
3999namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004000class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004001 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00004002 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004003public:
Richard Smith1aa0be82012-03-03 22:46:17 +00004004 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004005 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004006
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004007 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004008 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004009 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004010 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004011 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004012 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004013 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004014 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004015 return true;
4016 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004017 bool Success(const llvm::APSInt &SI, const Expr *E) {
4018 return Success(SI, E, Result);
4019 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004020
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004021 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004022 assert(E->getType()->isIntegralOrEnumerationType() &&
4023 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004024 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004025 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004026 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004027 Result.getInt().setIsUnsigned(
4028 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004029 return true;
4030 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004031 bool Success(const llvm::APInt &I, const Expr *E) {
4032 return Success(I, E, Result);
4033 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004034
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004035 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004036 assert(E->getType()->isIntegralOrEnumerationType() &&
4037 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004038 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004039 return true;
4040 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004041 bool Success(uint64_t Value, const Expr *E) {
4042 return Success(Value, E, Result);
4043 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004044
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004045 bool Success(CharUnits Size, const Expr *E) {
4046 return Success(Size.getQuantity(), E);
4047 }
4048
Richard Smith1aa0be82012-03-03 22:46:17 +00004049 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004050 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004051 Result = V;
4052 return true;
4053 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004054 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004055 }
Mike Stump1eb44332009-09-09 15:08:12 +00004056
Richard Smith51201882011-12-30 21:15:51 +00004057 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059 //===--------------------------------------------------------------------===//
4060 // Visitor Methods
4061 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004062
Chris Lattner4c4867e2008-07-12 00:38:25 +00004063 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004064 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004065 }
4066 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004067 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004068 }
Eli Friedman04309752009-11-24 05:28:59 +00004069
4070 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4071 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004072 if (CheckReferencedDecl(E, E->getDecl()))
4073 return true;
4074
4075 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004076 }
4077 bool VisitMemberExpr(const MemberExpr *E) {
4078 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004079 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004080 return true;
4081 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004082
4083 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004084 }
4085
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004086 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004087 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004088 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004089 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004090
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004091 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004092 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004093
Anders Carlsson3068d112008-11-16 19:01:22 +00004094 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004095 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004096 }
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004098 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4099 return Success(E->getValue(), E);
4100 }
4101
Richard Smithf10d9172011-10-11 21:43:33 +00004102 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004103 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004104 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004105 }
4106
Sebastian Redl64b45f72009-01-05 20:52:13 +00004107 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004108 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004109 }
4110
Francois Pichet6ad6f282010-12-07 00:08:36 +00004111 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4112 return Success(E->getValue(), E);
4113 }
4114
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004115 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4116 return Success(E->getValue(), E);
4117 }
4118
John Wiegley21ff2e52011-04-28 00:16:57 +00004119 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4120 return Success(E->getValue(), E);
4121 }
4122
John Wiegley55262202011-04-25 06:54:41 +00004123 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4124 return Success(E->getValue(), E);
4125 }
4126
Eli Friedman722c7172009-02-28 03:59:05 +00004127 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004128 bool VisitUnaryImag(const UnaryOperator *E);
4129
Sebastian Redl295995c2010-09-10 20:55:47 +00004130 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004131 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004132
Chris Lattnerfcee0012008-07-11 21:24:13 +00004133private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004134 CharUnits GetAlignOfExpr(const Expr *E);
4135 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004136 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004137 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004138 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004139};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004140} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004141
Richard Smithc49bd112011-10-28 17:51:58 +00004142/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4143/// produce either the integer value or a pointer.
4144///
4145/// GCC has a heinous extension which folds casts between pointer types and
4146/// pointer-sized integral types. We support this by allowing the evaluation of
4147/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4148/// Some simple arithmetic on such values is supported (they are treated much
4149/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004150static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004151 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004152 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004153 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004154}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004155
Richard Smithf48fdb02011-12-09 22:58:01 +00004156static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004157 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004158 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004159 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004160 if (!Val.isInt()) {
4161 // FIXME: It would be better to produce the diagnostic for casting
4162 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004163 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004164 return false;
4165 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004166 Result = Val.getInt();
4167 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004168}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004169
Richard Smithf48fdb02011-12-09 22:58:01 +00004170/// Check whether the given declaration can be directly converted to an integral
4171/// rvalue. If not, no diagnostic is produced; there are other things we can
4172/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004173bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004174 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004175 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004176 // Check for signedness/width mismatches between E type and ECD value.
4177 bool SameSign = (ECD->getInitVal().isSigned()
4178 == E->getType()->isSignedIntegerOrEnumerationType());
4179 bool SameWidth = (ECD->getInitVal().getBitWidth()
4180 == Info.Ctx.getIntWidth(E->getType()));
4181 if (SameSign && SameWidth)
4182 return Success(ECD->getInitVal(), E);
4183 else {
4184 // Get rid of mismatch (otherwise Success assertions will fail)
4185 // by computing a new value matching the type of E.
4186 llvm::APSInt Val = ECD->getInitVal();
4187 if (!SameSign)
4188 Val.setIsSigned(!ECD->getInitVal().isSigned());
4189 if (!SameWidth)
4190 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4191 return Success(Val, E);
4192 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004193 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004194 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004195}
4196
Chris Lattnera4d55d82008-10-06 06:40:35 +00004197/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4198/// as GCC.
4199static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4200 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004201 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004202 enum gcc_type_class {
4203 no_type_class = -1,
4204 void_type_class, integer_type_class, char_type_class,
4205 enumeral_type_class, boolean_type_class,
4206 pointer_type_class, reference_type_class, offset_type_class,
4207 real_type_class, complex_type_class,
4208 function_type_class, method_type_class,
4209 record_type_class, union_type_class,
4210 array_type_class, string_type_class,
4211 lang_type_class
4212 };
Mike Stump1eb44332009-09-09 15:08:12 +00004213
4214 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004215 // ideal, however it is what gcc does.
4216 if (E->getNumArgs() == 0)
4217 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Chris Lattnera4d55d82008-10-06 06:40:35 +00004219 QualType ArgTy = E->getArg(0)->getType();
4220 if (ArgTy->isVoidType())
4221 return void_type_class;
4222 else if (ArgTy->isEnumeralType())
4223 return enumeral_type_class;
4224 else if (ArgTy->isBooleanType())
4225 return boolean_type_class;
4226 else if (ArgTy->isCharType())
4227 return string_type_class; // gcc doesn't appear to use char_type_class
4228 else if (ArgTy->isIntegerType())
4229 return integer_type_class;
4230 else if (ArgTy->isPointerType())
4231 return pointer_type_class;
4232 else if (ArgTy->isReferenceType())
4233 return reference_type_class;
4234 else if (ArgTy->isRealType())
4235 return real_type_class;
4236 else if (ArgTy->isComplexType())
4237 return complex_type_class;
4238 else if (ArgTy->isFunctionType())
4239 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004240 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004241 return record_type_class;
4242 else if (ArgTy->isUnionType())
4243 return union_type_class;
4244 else if (ArgTy->isArrayType())
4245 return array_type_class;
4246 else if (ArgTy->isUnionType())
4247 return union_type_class;
4248 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004249 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004250}
4251
Richard Smith80d4b552011-12-28 19:48:30 +00004252/// EvaluateBuiltinConstantPForLValue - Determine the result of
4253/// __builtin_constant_p when applied to the given lvalue.
4254///
4255/// An lvalue is only "constant" if it is a pointer or reference to the first
4256/// character of a string literal.
4257template<typename LValue>
4258static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004259 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004260 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4261}
4262
4263/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4264/// GCC as we can manage.
4265static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4266 QualType ArgType = Arg->getType();
4267
4268 // __builtin_constant_p always has one operand. The rules which gcc follows
4269 // are not precisely documented, but are as follows:
4270 //
4271 // - If the operand is of integral, floating, complex or enumeration type,
4272 // and can be folded to a known value of that type, it returns 1.
4273 // - If the operand and can be folded to a pointer to the first character
4274 // of a string literal (or such a pointer cast to an integral type), it
4275 // returns 1.
4276 //
4277 // Otherwise, it returns 0.
4278 //
4279 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4280 // its support for this does not currently work.
4281 if (ArgType->isIntegralOrEnumerationType()) {
4282 Expr::EvalResult Result;
4283 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4284 return false;
4285
4286 APValue &V = Result.Val;
4287 if (V.getKind() == APValue::Int)
4288 return true;
4289
4290 return EvaluateBuiltinConstantPForLValue(V);
4291 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4292 return Arg->isEvaluatable(Ctx);
4293 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4294 LValue LV;
4295 Expr::EvalStatus Status;
4296 EvalInfo Info(Ctx, Status);
4297 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4298 : EvaluatePointer(Arg, LV, Info)) &&
4299 !Status.HasSideEffects)
4300 return EvaluateBuiltinConstantPForLValue(LV);
4301 }
4302
4303 // Anything else isn't considered to be sufficiently constant.
4304 return false;
4305}
4306
John McCall42c8f872010-05-10 23:27:23 +00004307/// Retrieves the "underlying object type" of the given expression,
4308/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004309QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4310 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4311 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004312 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004313 } else if (const Expr *E = B.get<const Expr*>()) {
4314 if (isa<CompoundLiteralExpr>(E))
4315 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004316 }
4317
4318 return QualType();
4319}
4320
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004321bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004322 // TODO: Perhaps we should let LLVM lower this?
4323 LValue Base;
4324 if (!EvaluatePointer(E->getArg(0), Base, Info))
4325 return false;
4326
4327 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004328 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004329
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004330 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004331 if (T.isNull() ||
4332 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004333 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004334 T->isVariablyModifiedType() ||
4335 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004336 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004337
4338 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4339 CharUnits Offset = Base.getLValueOffset();
4340
4341 if (!Offset.isNegative() && Offset <= Size)
4342 Size -= Offset;
4343 else
4344 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004345 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004346}
4347
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004348bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004349 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004350 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004351 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004352
4353 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004354 if (TryEvaluateBuiltinObjectSize(E))
4355 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004356
Eric Christopherb2aaf512010-01-19 22:58:35 +00004357 // If evaluating the argument has side-effects we can't determine
4358 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004359 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004360 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004361 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004362 return Success(0, E);
4363 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004364
Richard Smithf48fdb02011-12-09 22:58:01 +00004365 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004366 }
4367
Chris Lattner019f4e82008-10-06 05:28:25 +00004368 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004369 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004370
Richard Smith80d4b552011-12-28 19:48:30 +00004371 case Builtin::BI__builtin_constant_p:
4372 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004373
Chris Lattner21fb98e2009-09-23 06:06:36 +00004374 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004375 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004376 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004377 return Success(Operand, E);
4378 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004379
4380 case Builtin::BI__builtin_expect:
4381 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004382
Douglas Gregor5726d402010-09-10 06:27:15 +00004383 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004384 // A call to strlen is not a constant expression.
4385 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004386 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004387 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4388 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004389 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004390 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004391 case Builtin::BI__builtin_strlen:
4392 // As an extension, we support strlen() and __builtin_strlen() as constant
4393 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004394 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004395 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4396 // The string literal may have embedded null characters. Find the first
4397 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004398 StringRef Str = S->getString();
4399 StringRef::size_type Pos = Str.find(0);
4400 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004401 Str = Str.substr(0, Pos);
4402
4403 return Success(Str.size(), E);
4404 }
4405
Richard Smithf48fdb02011-12-09 22:58:01 +00004406 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004407
Richard Smith2c39d712012-04-13 00:45:38 +00004408 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004409 case Builtin::BI__atomic_is_lock_free:
4410 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004411 APSInt SizeVal;
4412 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4413 return false;
4414
4415 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4416 // of two less than the maximum inline atomic width, we know it is
4417 // lock-free. If the size isn't a power of two, or greater than the
4418 // maximum alignment where we promote atomics, we know it is not lock-free
4419 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4420 // the answer can only be determined at runtime; for example, 16-byte
4421 // atomics have lock-free implementations on some, but not all,
4422 // x86-64 processors.
4423
4424 // Check power-of-two.
4425 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004426 if (Size.isPowerOfTwo()) {
4427 // Check against inlining width.
4428 unsigned InlineWidthBits =
4429 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4430 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4431 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4432 Size == CharUnits::One() ||
4433 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4434 Expr::NPC_NeverValueDependent))
4435 // OK, we will inline appropriately-aligned operations of this size,
4436 // and _Atomic(T) is appropriately-aligned.
4437 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004438
Richard Smith2c39d712012-04-13 00:45:38 +00004439 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4440 castAs<PointerType>()->getPointeeType();
4441 if (!PointeeType->isIncompleteType() &&
4442 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4443 // OK, we will inline operations on this object.
4444 return Success(1, E);
4445 }
4446 }
4447 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004448
Richard Smith2c39d712012-04-13 00:45:38 +00004449 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4450 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004451 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004452 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004453}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004454
Richard Smith625b8072011-10-31 01:37:14 +00004455static bool HasSameBase(const LValue &A, const LValue &B) {
4456 if (!A.getLValueBase())
4457 return !B.getLValueBase();
4458 if (!B.getLValueBase())
4459 return false;
4460
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004461 if (A.getLValueBase().getOpaqueValue() !=
4462 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004463 const Decl *ADecl = GetLValueBaseDecl(A);
4464 if (!ADecl)
4465 return false;
4466 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004467 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004468 return false;
4469 }
4470
4471 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004472 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004473}
4474
Richard Smith7b48a292012-02-01 05:53:12 +00004475/// Perform the given integer operation, which is known to need at most BitWidth
4476/// bits, and check for overflow in the original type (if that type was not an
4477/// unsigned type).
4478template<typename Operation>
4479static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4480 const APSInt &LHS, const APSInt &RHS,
4481 unsigned BitWidth, Operation Op) {
4482 if (LHS.isUnsigned())
4483 return Op(LHS, RHS);
4484
4485 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4486 APSInt Result = Value.trunc(LHS.getBitWidth());
4487 if (Result.extend(BitWidth) != Value)
4488 HandleOverflow(Info, E, Value, E->getType());
4489 return Result;
4490}
4491
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004492namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004493
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004494/// \brief Data recursive integer evaluator of certain binary operators.
4495///
4496/// We use a data recursive algorithm for binary operators so that we are able
4497/// to handle extreme cases of chained binary operators without causing stack
4498/// overflow.
4499class DataRecursiveIntBinOpEvaluator {
4500 struct EvalResult {
4501 APValue Val;
4502 bool Failed;
4503
4504 EvalResult() : Failed(false) { }
4505
4506 void swap(EvalResult &RHS) {
4507 Val.swap(RHS.Val);
4508 Failed = RHS.Failed;
4509 RHS.Failed = false;
4510 }
4511 };
4512
4513 struct Job {
4514 const Expr *E;
4515 EvalResult LHSResult; // meaningful only for binary operator expression.
4516 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4517
4518 Job() : StoredInfo(0) { }
4519 void startSpeculativeEval(EvalInfo &Info) {
4520 OldEvalStatus = Info.EvalStatus;
4521 Info.EvalStatus.Diag = 0;
4522 StoredInfo = &Info;
4523 }
4524 ~Job() {
4525 if (StoredInfo) {
4526 StoredInfo->EvalStatus = OldEvalStatus;
4527 }
4528 }
4529 private:
4530 EvalInfo *StoredInfo; // non-null if status changed.
4531 Expr::EvalStatus OldEvalStatus;
4532 };
4533
4534 SmallVector<Job, 16> Queue;
4535
4536 IntExprEvaluator &IntEval;
4537 EvalInfo &Info;
4538 APValue &FinalResult;
4539
4540public:
4541 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4542 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4543
4544 /// \brief True if \param E is a binary operator that we are going to handle
4545 /// data recursively.
4546 /// We handle binary operators that are comma, logical, or that have operands
4547 /// with integral or enumeration type.
4548 static bool shouldEnqueue(const BinaryOperator *E) {
4549 return E->getOpcode() == BO_Comma ||
4550 E->isLogicalOp() ||
4551 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4552 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004553 }
4554
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004555 bool Traverse(const BinaryOperator *E) {
4556 enqueue(E);
4557 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004558 while (!Queue.empty())
4559 process(PrevResult);
4560
4561 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004562
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004563 FinalResult.swap(PrevResult.Val);
4564 return true;
4565 }
4566
4567private:
4568 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4569 return IntEval.Success(Value, E, Result);
4570 }
4571 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4572 return IntEval.Success(Value, E, Result);
4573 }
4574 bool Error(const Expr *E) {
4575 return IntEval.Error(E);
4576 }
4577 bool Error(const Expr *E, diag::kind D) {
4578 return IntEval.Error(E, D);
4579 }
4580
4581 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4582 return Info.CCEDiag(E, D);
4583 }
4584
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004585 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4586 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004587 bool &SuppressRHSDiags);
4588
4589 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4590 const BinaryOperator *E, APValue &Result);
4591
4592 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4593 Result.Failed = !Evaluate(Result.Val, Info, E);
4594 if (Result.Failed)
4595 Result.Val = APValue();
4596 }
4597
Richard Trieub7783052012-03-21 23:30:30 +00004598 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004599
4600 void enqueue(const Expr *E) {
4601 E = E->IgnoreParens();
4602 Queue.resize(Queue.size()+1);
4603 Queue.back().E = E;
4604 Queue.back().Kind = Job::AnyExprKind;
4605 }
4606};
4607
4608}
4609
4610bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004611 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004612 bool &SuppressRHSDiags) {
4613 if (E->getOpcode() == BO_Comma) {
4614 // Ignore LHS but note if we could not evaluate it.
4615 if (LHSResult.Failed)
4616 Info.EvalStatus.HasSideEffects = true;
4617 return true;
4618 }
4619
4620 if (E->isLogicalOp()) {
4621 bool lhsResult;
4622 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004623 // We were able to evaluate the LHS, see if we can get away with not
4624 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004625 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004626 Success(lhsResult, E, LHSResult.Val);
4627 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004628 }
4629 } else {
4630 // Since we weren't able to evaluate the left hand side, it
4631 // must have had side effects.
4632 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004633
4634 // We can't evaluate the LHS; however, sometimes the result
4635 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4636 // Don't ignore RHS and suppress diagnostics from this arm.
4637 SuppressRHSDiags = true;
4638 }
4639
4640 return true;
4641 }
4642
4643 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4644 E->getRHS()->getType()->isIntegralOrEnumerationType());
4645
4646 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004647 return false; // Ignore RHS;
4648
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004649 return true;
4650}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004651
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004652bool DataRecursiveIntBinOpEvaluator::
4653 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4654 const BinaryOperator *E, APValue &Result) {
4655 if (E->getOpcode() == BO_Comma) {
4656 if (RHSResult.Failed)
4657 return false;
4658 Result = RHSResult.Val;
4659 return true;
4660 }
4661
4662 if (E->isLogicalOp()) {
4663 bool lhsResult, rhsResult;
4664 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4665 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4666
4667 if (LHSIsOK) {
4668 if (RHSIsOK) {
4669 if (E->getOpcode() == BO_LOr)
4670 return Success(lhsResult || rhsResult, E, Result);
4671 else
4672 return Success(lhsResult && rhsResult, E, Result);
4673 }
4674 } else {
4675 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004676 // We can't evaluate the LHS; however, sometimes the result
4677 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4678 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004679 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004680 }
4681 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004682
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004683 return false;
4684 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004685
4686 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4687 E->getRHS()->getType()->isIntegralOrEnumerationType());
4688
4689 if (LHSResult.Failed || RHSResult.Failed)
4690 return false;
4691
4692 const APValue &LHSVal = LHSResult.Val;
4693 const APValue &RHSVal = RHSResult.Val;
4694
4695 // Handle cases like (unsigned long)&a + 4.
4696 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4697 Result = LHSVal;
4698 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4699 RHSVal.getInt().getZExtValue());
4700 if (E->getOpcode() == BO_Add)
4701 Result.getLValueOffset() += AdditionalOffset;
4702 else
4703 Result.getLValueOffset() -= AdditionalOffset;
4704 return true;
4705 }
4706
4707 // Handle cases like 4 + (unsigned long)&a
4708 if (E->getOpcode() == BO_Add &&
4709 RHSVal.isLValue() && LHSVal.isInt()) {
4710 Result = RHSVal;
4711 Result.getLValueOffset() += CharUnits::fromQuantity(
4712 LHSVal.getInt().getZExtValue());
4713 return true;
4714 }
4715
4716 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4717 // Handle (intptr_t)&&A - (intptr_t)&&B.
4718 if (!LHSVal.getLValueOffset().isZero() ||
4719 !RHSVal.getLValueOffset().isZero())
4720 return false;
4721 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4722 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4723 if (!LHSExpr || !RHSExpr)
4724 return false;
4725 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4726 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4727 if (!LHSAddrExpr || !RHSAddrExpr)
4728 return false;
4729 // Make sure both labels come from the same function.
4730 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4731 RHSAddrExpr->getLabel()->getDeclContext())
4732 return false;
4733 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4734 return true;
4735 }
4736
4737 // All the following cases expect both operands to be an integer
4738 if (!LHSVal.isInt() || !RHSVal.isInt())
4739 return Error(E);
4740
4741 const APSInt &LHS = LHSVal.getInt();
4742 APSInt RHS = RHSVal.getInt();
4743
4744 switch (E->getOpcode()) {
4745 default:
4746 return Error(E);
4747 case BO_Mul:
4748 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4749 LHS.getBitWidth() * 2,
4750 std::multiplies<APSInt>()), E,
4751 Result);
4752 case BO_Add:
4753 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4754 LHS.getBitWidth() + 1,
4755 std::plus<APSInt>()), E, Result);
4756 case BO_Sub:
4757 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4758 LHS.getBitWidth() + 1,
4759 std::minus<APSInt>()), E, Result);
4760 case BO_And: return Success(LHS & RHS, E, Result);
4761 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4762 case BO_Or: return Success(LHS | RHS, E, Result);
4763 case BO_Div:
4764 case BO_Rem:
4765 if (RHS == 0)
4766 return Error(E, diag::note_expr_divide_by_zero);
4767 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4768 // not actually undefined behavior in C++11 due to a language defect.
4769 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4770 LHS.isSigned() && LHS.isMinSignedValue())
4771 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4772 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4773 Result);
4774 case BO_Shl: {
4775 // During constant-folding, a negative shift is an opposite shift. Such
4776 // a shift is not a constant expression.
4777 if (RHS.isSigned() && RHS.isNegative()) {
4778 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4779 RHS = -RHS;
4780 goto shift_right;
4781 }
4782
4783 shift_left:
4784 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4785 // the shifted type.
4786 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4787 if (SA != RHS) {
4788 CCEDiag(E, diag::note_constexpr_large_shift)
4789 << RHS << E->getType() << LHS.getBitWidth();
4790 } else if (LHS.isSigned()) {
4791 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4792 // operand, and must not overflow the corresponding unsigned type.
4793 if (LHS.isNegative())
4794 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4795 else if (LHS.countLeadingZeros() < SA)
4796 CCEDiag(E, diag::note_constexpr_lshift_discards);
4797 }
4798
4799 return Success(LHS << SA, E, Result);
4800 }
4801 case BO_Shr: {
4802 // During constant-folding, a negative shift is an opposite shift. Such a
4803 // shift is not a constant expression.
4804 if (RHS.isSigned() && RHS.isNegative()) {
4805 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4806 RHS = -RHS;
4807 goto shift_left;
4808 }
4809
4810 shift_right:
4811 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4812 // shifted type.
4813 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4814 if (SA != RHS)
4815 CCEDiag(E, diag::note_constexpr_large_shift)
4816 << RHS << E->getType() << LHS.getBitWidth();
4817
4818 return Success(LHS >> SA, E, Result);
4819 }
4820
4821 case BO_LT: return Success(LHS < RHS, E, Result);
4822 case BO_GT: return Success(LHS > RHS, E, Result);
4823 case BO_LE: return Success(LHS <= RHS, E, Result);
4824 case BO_GE: return Success(LHS >= RHS, E, Result);
4825 case BO_EQ: return Success(LHS == RHS, E, Result);
4826 case BO_NE: return Success(LHS != RHS, E, Result);
4827 }
4828}
4829
Richard Trieub7783052012-03-21 23:30:30 +00004830void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004831 Job &job = Queue.back();
4832
4833 switch (job.Kind) {
4834 case Job::AnyExprKind: {
4835 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4836 if (shouldEnqueue(Bop)) {
4837 job.Kind = Job::BinOpKind;
4838 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004839 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004840 }
4841 }
4842
4843 EvaluateExpr(job.E, Result);
4844 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004845 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004846 }
4847
4848 case Job::BinOpKind: {
4849 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004850 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004851 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004852 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004853 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004854 }
4855 if (SuppressRHSDiags)
4856 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004857 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004858 job.Kind = Job::BinOpVisitedLHSKind;
4859 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004860 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004861 }
4862
4863 case Job::BinOpVisitedLHSKind: {
4864 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4865 EvalResult RHS;
4866 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004867 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004868 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004869 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004870 }
4871 }
4872
4873 llvm_unreachable("Invalid Job::Kind!");
4874}
4875
4876bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4877 if (E->isAssignmentOp())
4878 return Error(E);
4879
4880 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4881 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004882
Anders Carlsson286f85e2008-11-16 07:17:21 +00004883 QualType LHSTy = E->getLHS()->getType();
4884 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004885
4886 if (LHSTy->isAnyComplexType()) {
4887 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004888 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004889
Richard Smith745f5142012-01-27 01:14:48 +00004890 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4891 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004892 return false;
4893
Richard Smith745f5142012-01-27 01:14:48 +00004894 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004895 return false;
4896
4897 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004898 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004899 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004900 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004901 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4902
John McCall2de56d12010-08-25 11:45:40 +00004903 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004904 return Success((CR_r == APFloat::cmpEqual &&
4905 CR_i == APFloat::cmpEqual), E);
4906 else {
John McCall2de56d12010-08-25 11:45:40 +00004907 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004908 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004909 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004910 CR_r == APFloat::cmpLessThan ||
4911 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004912 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004913 CR_i == APFloat::cmpLessThan ||
4914 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004915 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004916 } else {
John McCall2de56d12010-08-25 11:45:40 +00004917 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004918 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4919 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4920 else {
John McCall2de56d12010-08-25 11:45:40 +00004921 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004922 "Invalid compex comparison.");
4923 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4924 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4925 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004926 }
4927 }
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Anders Carlsson286f85e2008-11-16 07:17:21 +00004929 if (LHSTy->isRealFloatingType() &&
4930 RHSTy->isRealFloatingType()) {
4931 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Richard Smith745f5142012-01-27 01:14:48 +00004933 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4934 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004935 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Richard Smith745f5142012-01-27 01:14:48 +00004937 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004938 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004939
Anders Carlsson286f85e2008-11-16 07:17:21 +00004940 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004941
Anders Carlsson286f85e2008-11-16 07:17:21 +00004942 switch (E->getOpcode()) {
4943 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004944 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004945 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004946 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004947 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004948 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004949 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004950 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004951 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004952 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004953 E);
John McCall2de56d12010-08-25 11:45:40 +00004954 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004955 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004956 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004957 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004958 || CR == APFloat::cmpLessThan
4959 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004960 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004961 }
Mike Stump1eb44332009-09-09 15:08:12 +00004962
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004963 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004964 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004965 LValue LHSValue, RHSValue;
4966
4967 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4968 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004969 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004970
Richard Smith745f5142012-01-27 01:14:48 +00004971 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004972 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004973
Richard Smith625b8072011-10-31 01:37:14 +00004974 // Reject differing bases from the normal codepath; we special-case
4975 // comparisons to null.
4976 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004977 if (E->getOpcode() == BO_Sub) {
4978 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004979 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4980 return false;
4981 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4982 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4983 if (!LHSExpr || !RHSExpr)
4984 return false;
4985 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4986 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4987 if (!LHSAddrExpr || !RHSAddrExpr)
4988 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004989 // Make sure both labels come from the same function.
4990 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4991 RHSAddrExpr->getLabel()->getDeclContext())
4992 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004993 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004994 return true;
4995 }
Richard Smith9e36b532011-10-31 05:11:32 +00004996 // Inequalities and subtractions between unrelated pointers have
4997 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004998 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004999 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00005000 // A constant address may compare equal to the address of a symbol.
5001 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00005002 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00005003 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5004 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00005005 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005006 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00005007 // distinct addresses. In clang, the result of such a comparison is
5008 // unspecified, so it is not a constant expression. However, we do know
5009 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00005010 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5011 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00005012 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005013 // We can't tell whether weak symbols will end up pointing to the same
5014 // object.
5015 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00005016 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005017 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00005018 // (Note that clang defaults to -fmerge-all-constants, which can
5019 // lead to inconsistent results for comparisons involving the address
5020 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005021 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005022 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005023
Richard Smith15efc4d2012-02-01 08:10:20 +00005024 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5025 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5026
Richard Smithf15fda02012-02-02 01:16:57 +00005027 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5028 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5029
John McCall2de56d12010-08-25 11:45:40 +00005030 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005031 // C++11 [expr.add]p6:
5032 // Unless both pointers point to elements of the same array object, or
5033 // one past the last element of the array object, the behavior is
5034 // undefined.
5035 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5036 !AreElementsOfSameArray(getType(LHSValue.Base),
5037 LHSDesignator, RHSDesignator))
5038 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5039
Chris Lattner4992bdd2010-04-20 17:13:14 +00005040 QualType Type = E->getLHS()->getType();
5041 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005042
Richard Smith180f4792011-11-10 06:34:14 +00005043 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005044 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005045 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005046
Richard Smith15efc4d2012-02-01 08:10:20 +00005047 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5048 // and produce incorrect results when it overflows. Such behavior
5049 // appears to be non-conforming, but is common, so perhaps we should
5050 // assume the standard intended for such cases to be undefined behavior
5051 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005052
Richard Smith15efc4d2012-02-01 08:10:20 +00005053 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5054 // overflow in the final conversion to ptrdiff_t.
5055 APSInt LHS(
5056 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5057 APSInt RHS(
5058 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5059 APSInt ElemSize(
5060 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5061 APSInt TrueResult = (LHS - RHS) / ElemSize;
5062 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5063
5064 if (Result.extend(65) != TrueResult)
5065 HandleOverflow(Info, E, TrueResult, E->getType());
5066 return Success(Result, E);
5067 }
Richard Smith82f28582012-01-31 06:41:30 +00005068
5069 // C++11 [expr.rel]p3:
5070 // Pointers to void (after pointer conversions) can be compared, with a
5071 // result defined as follows: If both pointers represent the same
5072 // address or are both the null pointer value, the result is true if the
5073 // operator is <= or >= and false otherwise; otherwise the result is
5074 // unspecified.
5075 // We interpret this as applying to pointers to *cv* void.
5076 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005077 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005078 CCEDiag(E, diag::note_constexpr_void_comparison);
5079
Richard Smithf15fda02012-02-02 01:16:57 +00005080 // C++11 [expr.rel]p2:
5081 // - If two pointers point to non-static data members of the same object,
5082 // or to subobjects or array elements fo such members, recursively, the
5083 // pointer to the later declared member compares greater provided the
5084 // two members have the same access control and provided their class is
5085 // not a union.
5086 // [...]
5087 // - Otherwise pointer comparisons are unspecified.
5088 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5089 E->isRelationalOp()) {
5090 bool WasArrayIndex;
5091 unsigned Mismatch =
5092 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5093 RHSDesignator, WasArrayIndex);
5094 // At the point where the designators diverge, the comparison has a
5095 // specified value if:
5096 // - we are comparing array indices
5097 // - we are comparing fields of a union, or fields with the same access
5098 // Otherwise, the result is unspecified and thus the comparison is not a
5099 // constant expression.
5100 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5101 Mismatch < RHSDesignator.Entries.size()) {
5102 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5103 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5104 if (!LF && !RF)
5105 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5106 else if (!LF)
5107 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5108 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5109 << RF->getParent() << RF;
5110 else if (!RF)
5111 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5112 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5113 << LF->getParent() << LF;
5114 else if (!LF->getParent()->isUnion() &&
5115 LF->getAccess() != RF->getAccess())
5116 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5117 << LF << LF->getAccess() << RF << RF->getAccess()
5118 << LF->getParent();
5119 }
5120 }
5121
Eli Friedmana3169882012-04-16 04:30:08 +00005122 // The comparison here must be unsigned, and performed with the same
5123 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005124 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5125 uint64_t CompareLHS = LHSOffset.getQuantity();
5126 uint64_t CompareRHS = RHSOffset.getQuantity();
5127 assert(PtrSize <= 64 && "Unexpected pointer width");
5128 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5129 CompareLHS &= Mask;
5130 CompareRHS &= Mask;
5131
Eli Friedman28503762012-04-16 19:23:57 +00005132 // If there is a base and this is a relational operator, we can only
5133 // compare pointers within the object in question; otherwise, the result
5134 // depends on where the object is located in memory.
5135 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5136 QualType BaseTy = getType(LHSValue.Base);
5137 if (BaseTy->isIncompleteType())
5138 return Error(E);
5139 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5140 uint64_t OffsetLimit = Size.getQuantity();
5141 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5142 return Error(E);
5143 }
5144
Richard Smith625b8072011-10-31 01:37:14 +00005145 switch (E->getOpcode()) {
5146 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005147 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5148 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5149 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5150 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5151 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5152 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005153 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005154 }
5155 }
Richard Smithb02e4622012-02-01 01:42:44 +00005156
5157 if (LHSTy->isMemberPointerType()) {
5158 assert(E->isEqualityOp() && "unexpected member pointer operation");
5159 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5160
5161 MemberPtr LHSValue, RHSValue;
5162
5163 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5164 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5165 return false;
5166
5167 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5168 return false;
5169
5170 // C++11 [expr.eq]p2:
5171 // If both operands are null, they compare equal. Otherwise if only one is
5172 // null, they compare unequal.
5173 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5174 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5175 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5176 }
5177
5178 // Otherwise if either is a pointer to a virtual member function, the
5179 // result is unspecified.
5180 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5181 if (MD->isVirtual())
5182 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5183 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5184 if (MD->isVirtual())
5185 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5186
5187 // Otherwise they compare equal if and only if they would refer to the
5188 // same member of the same most derived object or the same subobject if
5189 // they were dereferenced with a hypothetical object of the associated
5190 // class type.
5191 bool Equal = LHSValue == RHSValue;
5192 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5193 }
5194
Richard Smith26f2cac2012-02-14 22:35:28 +00005195 if (LHSTy->isNullPtrType()) {
5196 assert(E->isComparisonOp() && "unexpected nullptr operation");
5197 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5198 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5199 // are compared, the result is true of the operator is <=, >= or ==, and
5200 // false otherwise.
5201 BinaryOperator::Opcode Opcode = E->getOpcode();
5202 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5203 }
5204
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005205 assert((!LHSTy->isIntegralOrEnumerationType() ||
5206 !RHSTy->isIntegralOrEnumerationType()) &&
5207 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5208 // We can't continue from here for non-integral types.
5209 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005210}
5211
Ken Dyck8b752f12010-01-27 17:10:57 +00005212CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005213 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5214 // result shall be the alignment of the referenced type."
5215 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5216 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005217
5218 // __alignof is defined to return the preferred alignment.
5219 return Info.Ctx.toCharUnitsFromBits(
5220 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005221}
5222
Ken Dyck8b752f12010-01-27 17:10:57 +00005223CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005224 E = E->IgnoreParens();
5225
5226 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005227 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005228 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005229 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5230 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005231
Chris Lattneraf707ab2009-01-24 21:53:27 +00005232 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005233 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5234 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005235
Chris Lattnere9feb472009-01-24 21:09:06 +00005236 return GetAlignOfType(E->getType());
5237}
5238
5239
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005240/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5241/// a result as the expression's type.
5242bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5243 const UnaryExprOrTypeTraitExpr *E) {
5244 switch(E->getKind()) {
5245 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005246 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005247 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005248 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005249 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005250 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005251
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005252 case UETT_VecStep: {
5253 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005254
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005255 if (Ty->isVectorType()) {
5256 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005257
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005258 // The vec_step built-in functions that take a 3-component
5259 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5260 if (n == 3)
5261 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005262
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005263 return Success(n, E);
5264 } else
5265 return Success(1, E);
5266 }
5267
5268 case UETT_SizeOf: {
5269 QualType SrcTy = E->getTypeOfArgument();
5270 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5271 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005272 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5273 SrcTy = Ref->getPointeeType();
5274
Richard Smith180f4792011-11-10 06:34:14 +00005275 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005276 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005277 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005278 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005279 }
5280 }
5281
5282 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005283}
5284
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005285bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005286 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005287 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005288 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005289 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005290 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005291 for (unsigned i = 0; i != n; ++i) {
5292 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5293 switch (ON.getKind()) {
5294 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005295 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005296 APSInt IdxResult;
5297 if (!EvaluateInteger(Idx, IdxResult, Info))
5298 return false;
5299 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5300 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005301 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005302 CurrentType = AT->getElementType();
5303 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5304 Result += IdxResult.getSExtValue() * ElementSize;
5305 break;
5306 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005307
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005308 case OffsetOfExpr::OffsetOfNode::Field: {
5309 FieldDecl *MemberDecl = ON.getField();
5310 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005311 if (!RT)
5312 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005313 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005314 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005315 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005316 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005317 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005318 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005319 CurrentType = MemberDecl->getType().getNonReferenceType();
5320 break;
5321 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005322
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005323 case OffsetOfExpr::OffsetOfNode::Identifier:
5324 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005325
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005326 case OffsetOfExpr::OffsetOfNode::Base: {
5327 CXXBaseSpecifier *BaseSpec = ON.getBase();
5328 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005329 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005330
5331 // Find the layout of the class whose base we are looking into.
5332 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005333 if (!RT)
5334 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005335 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005336 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005337 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5338
5339 // Find the base class itself.
5340 CurrentType = BaseSpec->getType();
5341 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5342 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005343 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005344
5345 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005346 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005347 break;
5348 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005349 }
5350 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005351 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005352}
5353
Chris Lattnerb542afe2008-07-11 19:10:17 +00005354bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005355 switch (E->getOpcode()) {
5356 default:
5357 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5358 // See C99 6.6p3.
5359 return Error(E);
5360 case UO_Extension:
5361 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5362 // If so, we could clear the diagnostic ID.
5363 return Visit(E->getSubExpr());
5364 case UO_Plus:
5365 // The result is just the value.
5366 return Visit(E->getSubExpr());
5367 case UO_Minus: {
5368 if (!Visit(E->getSubExpr()))
5369 return false;
5370 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005371 const APSInt &Value = Result.getInt();
5372 if (Value.isSigned() && Value.isMinSignedValue())
5373 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5374 E->getType());
5375 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005376 }
5377 case UO_Not: {
5378 if (!Visit(E->getSubExpr()))
5379 return false;
5380 if (!Result.isInt()) return Error(E);
5381 return Success(~Result.getInt(), E);
5382 }
5383 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005384 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005385 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005386 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005387 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005388 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005389 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005390}
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Chris Lattner732b2232008-07-12 01:15:53 +00005392/// HandleCast - This is used to evaluate implicit or explicit casts where the
5393/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005394bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5395 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005396 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005397 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005398
Eli Friedman46a52322011-03-25 00:43:55 +00005399 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005400 case CK_BaseToDerived:
5401 case CK_DerivedToBase:
5402 case CK_UncheckedDerivedToBase:
5403 case CK_Dynamic:
5404 case CK_ToUnion:
5405 case CK_ArrayToPointerDecay:
5406 case CK_FunctionToPointerDecay:
5407 case CK_NullToPointer:
5408 case CK_NullToMemberPointer:
5409 case CK_BaseToDerivedMemberPointer:
5410 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005411 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005412 case CK_ConstructorConversion:
5413 case CK_IntegralToPointer:
5414 case CK_ToVoid:
5415 case CK_VectorSplat:
5416 case CK_IntegralToFloating:
5417 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005418 case CK_CPointerToObjCPointerCast:
5419 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005420 case CK_AnyPointerToBlockPointerCast:
5421 case CK_ObjCObjectLValueCast:
5422 case CK_FloatingRealToComplex:
5423 case CK_FloatingComplexToReal:
5424 case CK_FloatingComplexCast:
5425 case CK_FloatingComplexToIntegralComplex:
5426 case CK_IntegralRealToComplex:
5427 case CK_IntegralComplexCast:
5428 case CK_IntegralComplexToFloatingComplex:
5429 llvm_unreachable("invalid cast kind for integral value");
5430
Eli Friedmane50c2972011-03-25 19:07:11 +00005431 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005432 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005433 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005434 case CK_ARCProduceObject:
5435 case CK_ARCConsumeObject:
5436 case CK_ARCReclaimReturnedObject:
5437 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005438 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005439 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005440
Richard Smith7d580a42012-01-17 21:17:26 +00005441 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005442 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005443 case CK_AtomicToNonAtomic:
5444 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005445 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005446 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005447
5448 case CK_MemberPointerToBoolean:
5449 case CK_PointerToBoolean:
5450 case CK_IntegralToBoolean:
5451 case CK_FloatingToBoolean:
5452 case CK_FloatingComplexToBoolean:
5453 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005454 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005455 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005456 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005457 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005458 }
5459
Eli Friedman46a52322011-03-25 00:43:55 +00005460 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005461 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005462 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005463
Eli Friedmanbe265702009-02-20 01:15:07 +00005464 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005465 // Allow casts of address-of-label differences if they are no-ops
5466 // or narrowing. (The narrowing case isn't actually guaranteed to
5467 // be constant-evaluatable except in some narrow cases which are hard
5468 // to detect here. We let it through on the assumption the user knows
5469 // what they are doing.)
5470 if (Result.isAddrLabelDiff())
5471 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005472 // Only allow casts of lvalues if they are lossless.
5473 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5474 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005475
Richard Smithf72fccf2012-01-30 22:27:01 +00005476 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5477 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005478 }
Mike Stump1eb44332009-09-09 15:08:12 +00005479
Eli Friedman46a52322011-03-25 00:43:55 +00005480 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005481 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5482
John McCallefdb83e2010-05-07 21:00:08 +00005483 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005484 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005485 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005486
Daniel Dunbardd211642009-02-19 22:24:01 +00005487 if (LV.getLValueBase()) {
5488 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005489 // FIXME: Allow a larger integer size than the pointer size, and allow
5490 // narrowing back down to pointer width in subsequent integral casts.
5491 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005492 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005493 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005494
Richard Smithb755a9d2011-11-16 07:18:12 +00005495 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005496 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005497 return true;
5498 }
5499
Ken Dycka7305832010-01-15 12:37:54 +00005500 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5501 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005502 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005503 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005504
Eli Friedman46a52322011-03-25 00:43:55 +00005505 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005506 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005507 if (!EvaluateComplex(SubExpr, C, Info))
5508 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005509 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005510 }
Eli Friedman2217c872009-02-22 11:46:18 +00005511
Eli Friedman46a52322011-03-25 00:43:55 +00005512 case CK_FloatingToIntegral: {
5513 APFloat F(0.0);
5514 if (!EvaluateFloat(SubExpr, F, Info))
5515 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005516
Richard Smithc1c5f272011-12-13 06:39:58 +00005517 APSInt Value;
5518 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5519 return false;
5520 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005521 }
5522 }
Mike Stump1eb44332009-09-09 15:08:12 +00005523
Eli Friedman46a52322011-03-25 00:43:55 +00005524 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005525}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005526
Eli Friedman722c7172009-02-28 03:59:05 +00005527bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5528 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005529 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005530 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5531 return false;
5532 if (!LV.isComplexInt())
5533 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005534 return Success(LV.getComplexIntReal(), E);
5535 }
5536
5537 return Visit(E->getSubExpr());
5538}
5539
Eli Friedman664a1042009-02-27 04:45:43 +00005540bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005541 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005542 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005543 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5544 return false;
5545 if (!LV.isComplexInt())
5546 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005547 return Success(LV.getComplexIntImag(), E);
5548 }
5549
Richard Smith8327fad2011-10-24 18:44:57 +00005550 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005551 return Success(0, E);
5552}
5553
Douglas Gregoree8aff02011-01-04 17:33:58 +00005554bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5555 return Success(E->getPackLength(), E);
5556}
5557
Sebastian Redl295995c2010-09-10 20:55:47 +00005558bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5559 return Success(E->getValue(), E);
5560}
5561
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005562//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005563// Float Evaluation
5564//===----------------------------------------------------------------------===//
5565
5566namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005567class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005568 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005569 APFloat &Result;
5570public:
5571 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005572 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005573
Richard Smith1aa0be82012-03-03 22:46:17 +00005574 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005575 Result = V.getFloat();
5576 return true;
5577 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005578
Richard Smith51201882011-12-30 21:15:51 +00005579 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005580 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5581 return true;
5582 }
5583
Chris Lattner019f4e82008-10-06 05:28:25 +00005584 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005585
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005586 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005587 bool VisitBinaryOperator(const BinaryOperator *E);
5588 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005589 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005590
John McCallabd3a852010-05-07 22:08:54 +00005591 bool VisitUnaryReal(const UnaryOperator *E);
5592 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005593
Richard Smith51201882011-12-30 21:15:51 +00005594 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005595};
5596} // end anonymous namespace
5597
5598static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005599 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005600 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005601}
5602
Jay Foad4ba2a172011-01-12 09:06:06 +00005603static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005604 QualType ResultTy,
5605 const Expr *Arg,
5606 bool SNaN,
5607 llvm::APFloat &Result) {
5608 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5609 if (!S) return false;
5610
5611 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5612
5613 llvm::APInt fill;
5614
5615 // Treat empty strings as if they were zero.
5616 if (S->getString().empty())
5617 fill = llvm::APInt(32, 0);
5618 else if (S->getString().getAsInteger(0, fill))
5619 return false;
5620
5621 if (SNaN)
5622 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5623 else
5624 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5625 return true;
5626}
5627
Chris Lattner019f4e82008-10-06 05:28:25 +00005628bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005629 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005630 default:
5631 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5632
Chris Lattner019f4e82008-10-06 05:28:25 +00005633 case Builtin::BI__builtin_huge_val:
5634 case Builtin::BI__builtin_huge_valf:
5635 case Builtin::BI__builtin_huge_vall:
5636 case Builtin::BI__builtin_inf:
5637 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005638 case Builtin::BI__builtin_infl: {
5639 const llvm::fltSemantics &Sem =
5640 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005641 Result = llvm::APFloat::getInf(Sem);
5642 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005643 }
Mike Stump1eb44332009-09-09 15:08:12 +00005644
John McCalldb7b72a2010-02-28 13:00:19 +00005645 case Builtin::BI__builtin_nans:
5646 case Builtin::BI__builtin_nansf:
5647 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005648 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5649 true, Result))
5650 return Error(E);
5651 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005652
Chris Lattner9e621712008-10-06 06:31:58 +00005653 case Builtin::BI__builtin_nan:
5654 case Builtin::BI__builtin_nanf:
5655 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005656 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005657 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005658 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5659 false, Result))
5660 return Error(E);
5661 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005662
5663 case Builtin::BI__builtin_fabs:
5664 case Builtin::BI__builtin_fabsf:
5665 case Builtin::BI__builtin_fabsl:
5666 if (!EvaluateFloat(E->getArg(0), Result, Info))
5667 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005668
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005669 if (Result.isNegative())
5670 Result.changeSign();
5671 return true;
5672
Mike Stump1eb44332009-09-09 15:08:12 +00005673 case Builtin::BI__builtin_copysign:
5674 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005675 case Builtin::BI__builtin_copysignl: {
5676 APFloat RHS(0.);
5677 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5678 !EvaluateFloat(E->getArg(1), RHS, Info))
5679 return false;
5680 Result.copySign(RHS);
5681 return true;
5682 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005683 }
5684}
5685
John McCallabd3a852010-05-07 22:08:54 +00005686bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005687 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5688 ComplexValue CV;
5689 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5690 return false;
5691 Result = CV.FloatReal;
5692 return true;
5693 }
5694
5695 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005696}
5697
5698bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005699 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5700 ComplexValue CV;
5701 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5702 return false;
5703 Result = CV.FloatImag;
5704 return true;
5705 }
5706
Richard Smith8327fad2011-10-24 18:44:57 +00005707 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005708 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5709 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005710 return true;
5711}
5712
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005713bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005714 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005715 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005716 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005717 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005718 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005719 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5720 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005721 Result.changeSign();
5722 return true;
5723 }
5724}
Chris Lattner019f4e82008-10-06 05:28:25 +00005725
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005726bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005727 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5728 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005729
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005730 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005731 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5732 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005733 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005734 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005735 return false;
5736
5737 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005738 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005739 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005740 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005741 break;
John McCall2de56d12010-08-25 11:45:40 +00005742 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005743 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005744 break;
John McCall2de56d12010-08-25 11:45:40 +00005745 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005746 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005747 break;
John McCall2de56d12010-08-25 11:45:40 +00005748 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005749 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005750 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005751 }
Richard Smith7b48a292012-02-01 05:53:12 +00005752
5753 if (Result.isInfinity() || Result.isNaN())
5754 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5755 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005756}
5757
5758bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5759 Result = E->getValue();
5760 return true;
5761}
5762
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005763bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5764 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005765
Eli Friedman2a523ee2011-03-25 00:54:52 +00005766 switch (E->getCastKind()) {
5767 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005768 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005769
5770 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005771 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005772 return EvaluateInteger(SubExpr, IntResult, Info) &&
5773 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5774 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005775 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005776
5777 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005778 if (!Visit(SubExpr))
5779 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005780 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5781 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005782 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005783
Eli Friedman2a523ee2011-03-25 00:54:52 +00005784 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005785 ComplexValue V;
5786 if (!EvaluateComplex(SubExpr, V, Info))
5787 return false;
5788 Result = V.getComplexFloatReal();
5789 return true;
5790 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005791 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005792}
5793
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005794//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005795// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005796//===----------------------------------------------------------------------===//
5797
5798namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005799class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005800 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005801 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005802
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005803public:
John McCallf4cf1a12010-05-07 17:22:02 +00005804 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005805 : ExprEvaluatorBaseTy(info), Result(Result) {}
5806
Richard Smith1aa0be82012-03-03 22:46:17 +00005807 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005808 Result.setFrom(V);
5809 return true;
5810 }
Mike Stump1eb44332009-09-09 15:08:12 +00005811
Eli Friedman7ead5c72012-01-10 04:58:17 +00005812 bool ZeroInitialization(const Expr *E);
5813
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005814 //===--------------------------------------------------------------------===//
5815 // Visitor Methods
5816 //===--------------------------------------------------------------------===//
5817
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005818 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005819 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005820 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005821 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005822 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005823};
5824} // end anonymous namespace
5825
John McCallf4cf1a12010-05-07 17:22:02 +00005826static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5827 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005828 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005829 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005830}
5831
Eli Friedman7ead5c72012-01-10 04:58:17 +00005832bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005833 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005834 if (ElemTy->isRealFloatingType()) {
5835 Result.makeComplexFloat();
5836 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5837 Result.FloatReal = Zero;
5838 Result.FloatImag = Zero;
5839 } else {
5840 Result.makeComplexInt();
5841 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5842 Result.IntReal = Zero;
5843 Result.IntImag = Zero;
5844 }
5845 return true;
5846}
5847
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005848bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5849 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005850
5851 if (SubExpr->getType()->isRealFloatingType()) {
5852 Result.makeComplexFloat();
5853 APFloat &Imag = Result.FloatImag;
5854 if (!EvaluateFloat(SubExpr, Imag, Info))
5855 return false;
5856
5857 Result.FloatReal = APFloat(Imag.getSemantics());
5858 return true;
5859 } else {
5860 assert(SubExpr->getType()->isIntegerType() &&
5861 "Unexpected imaginary literal.");
5862
5863 Result.makeComplexInt();
5864 APSInt &Imag = Result.IntImag;
5865 if (!EvaluateInteger(SubExpr, Imag, Info))
5866 return false;
5867
5868 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5869 return true;
5870 }
5871}
5872
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005873bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005874
John McCall8786da72010-12-14 17:51:41 +00005875 switch (E->getCastKind()) {
5876 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005877 case CK_BaseToDerived:
5878 case CK_DerivedToBase:
5879 case CK_UncheckedDerivedToBase:
5880 case CK_Dynamic:
5881 case CK_ToUnion:
5882 case CK_ArrayToPointerDecay:
5883 case CK_FunctionToPointerDecay:
5884 case CK_NullToPointer:
5885 case CK_NullToMemberPointer:
5886 case CK_BaseToDerivedMemberPointer:
5887 case CK_DerivedToBaseMemberPointer:
5888 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005889 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005890 case CK_ConstructorConversion:
5891 case CK_IntegralToPointer:
5892 case CK_PointerToIntegral:
5893 case CK_PointerToBoolean:
5894 case CK_ToVoid:
5895 case CK_VectorSplat:
5896 case CK_IntegralCast:
5897 case CK_IntegralToBoolean:
5898 case CK_IntegralToFloating:
5899 case CK_FloatingToIntegral:
5900 case CK_FloatingToBoolean:
5901 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005902 case CK_CPointerToObjCPointerCast:
5903 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005904 case CK_AnyPointerToBlockPointerCast:
5905 case CK_ObjCObjectLValueCast:
5906 case CK_FloatingComplexToReal:
5907 case CK_FloatingComplexToBoolean:
5908 case CK_IntegralComplexToReal:
5909 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005910 case CK_ARCProduceObject:
5911 case CK_ARCConsumeObject:
5912 case CK_ARCReclaimReturnedObject:
5913 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005914 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005915 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005916
John McCall8786da72010-12-14 17:51:41 +00005917 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005918 case CK_AtomicToNonAtomic:
5919 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005920 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005921 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005922
5923 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005924 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005925 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005926 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005927
5928 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005929 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005930 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005931 return false;
5932
John McCall8786da72010-12-14 17:51:41 +00005933 Result.makeComplexFloat();
5934 Result.FloatImag = APFloat(Real.getSemantics());
5935 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005936 }
5937
John McCall8786da72010-12-14 17:51:41 +00005938 case CK_FloatingComplexCast: {
5939 if (!Visit(E->getSubExpr()))
5940 return false;
5941
5942 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5943 QualType From
5944 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5945
Richard Smithc1c5f272011-12-13 06:39:58 +00005946 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5947 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005948 }
5949
5950 case CK_FloatingComplexToIntegralComplex: {
5951 if (!Visit(E->getSubExpr()))
5952 return false;
5953
5954 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5955 QualType From
5956 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5957 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005958 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5959 To, Result.IntReal) &&
5960 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5961 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005962 }
5963
5964 case CK_IntegralRealToComplex: {
5965 APSInt &Real = Result.IntReal;
5966 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5967 return false;
5968
5969 Result.makeComplexInt();
5970 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5971 return true;
5972 }
5973
5974 case CK_IntegralComplexCast: {
5975 if (!Visit(E->getSubExpr()))
5976 return false;
5977
5978 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5979 QualType From
5980 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5981
Richard Smithf72fccf2012-01-30 22:27:01 +00005982 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5983 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005984 return true;
5985 }
5986
5987 case CK_IntegralComplexToFloatingComplex: {
5988 if (!Visit(E->getSubExpr()))
5989 return false;
5990
5991 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5992 QualType From
5993 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5994 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005995 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5996 To, Result.FloatReal) &&
5997 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5998 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005999 }
6000 }
6001
6002 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00006003}
6004
John McCallf4cf1a12010-05-07 17:22:02 +00006005bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006006 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00006007 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6008
Richard Smith745f5142012-01-27 01:14:48 +00006009 bool LHSOK = Visit(E->getLHS());
6010 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00006011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006012
John McCallf4cf1a12010-05-07 17:22:02 +00006013 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00006014 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00006015 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006016
Daniel Dunbar3f279872009-01-29 01:32:56 +00006017 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6018 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006019 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006020 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006021 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006022 if (Result.isComplexFloat()) {
6023 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6024 APFloat::rmNearestTiesToEven);
6025 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6026 APFloat::rmNearestTiesToEven);
6027 } else {
6028 Result.getComplexIntReal() += RHS.getComplexIntReal();
6029 Result.getComplexIntImag() += RHS.getComplexIntImag();
6030 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006031 break;
John McCall2de56d12010-08-25 11:45:40 +00006032 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006033 if (Result.isComplexFloat()) {
6034 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6035 APFloat::rmNearestTiesToEven);
6036 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6037 APFloat::rmNearestTiesToEven);
6038 } else {
6039 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6040 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6041 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006042 break;
John McCall2de56d12010-08-25 11:45:40 +00006043 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006044 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006045 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006046 APFloat &LHS_r = LHS.getComplexFloatReal();
6047 APFloat &LHS_i = LHS.getComplexFloatImag();
6048 APFloat &RHS_r = RHS.getComplexFloatReal();
6049 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006050
Daniel Dunbar3f279872009-01-29 01:32:56 +00006051 APFloat Tmp = LHS_r;
6052 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6053 Result.getComplexFloatReal() = Tmp;
6054 Tmp = LHS_i;
6055 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6056 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6057
6058 Tmp = LHS_r;
6059 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6060 Result.getComplexFloatImag() = Tmp;
6061 Tmp = LHS_i;
6062 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6063 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6064 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006065 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006066 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006067 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6068 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006069 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006070 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6071 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6072 }
6073 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006074 case BO_Div:
6075 if (Result.isComplexFloat()) {
6076 ComplexValue LHS = Result;
6077 APFloat &LHS_r = LHS.getComplexFloatReal();
6078 APFloat &LHS_i = LHS.getComplexFloatImag();
6079 APFloat &RHS_r = RHS.getComplexFloatReal();
6080 APFloat &RHS_i = RHS.getComplexFloatImag();
6081 APFloat &Res_r = Result.getComplexFloatReal();
6082 APFloat &Res_i = Result.getComplexFloatImag();
6083
6084 APFloat Den = RHS_r;
6085 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6086 APFloat Tmp = RHS_i;
6087 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6088 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6089
6090 Res_r = LHS_r;
6091 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6092 Tmp = LHS_i;
6093 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6094 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6095 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6096
6097 Res_i = LHS_i;
6098 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6099 Tmp = LHS_r;
6100 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6101 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6102 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6103 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006104 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6105 return Error(E, diag::note_expr_divide_by_zero);
6106
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006107 ComplexValue LHS = Result;
6108 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6109 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6110 Result.getComplexIntReal() =
6111 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6112 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6113 Result.getComplexIntImag() =
6114 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6115 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6116 }
6117 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006118 }
6119
John McCallf4cf1a12010-05-07 17:22:02 +00006120 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006121}
6122
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006123bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6124 // Get the operand value into 'Result'.
6125 if (!Visit(E->getSubExpr()))
6126 return false;
6127
6128 switch (E->getOpcode()) {
6129 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006130 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006131 case UO_Extension:
6132 return true;
6133 case UO_Plus:
6134 // The result is always just the subexpr.
6135 return true;
6136 case UO_Minus:
6137 if (Result.isComplexFloat()) {
6138 Result.getComplexFloatReal().changeSign();
6139 Result.getComplexFloatImag().changeSign();
6140 }
6141 else {
6142 Result.getComplexIntReal() = -Result.getComplexIntReal();
6143 Result.getComplexIntImag() = -Result.getComplexIntImag();
6144 }
6145 return true;
6146 case UO_Not:
6147 if (Result.isComplexFloat())
6148 Result.getComplexFloatImag().changeSign();
6149 else
6150 Result.getComplexIntImag() = -Result.getComplexIntImag();
6151 return true;
6152 }
6153}
6154
Eli Friedman7ead5c72012-01-10 04:58:17 +00006155bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6156 if (E->getNumInits() == 2) {
6157 if (E->getType()->isComplexType()) {
6158 Result.makeComplexFloat();
6159 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6160 return false;
6161 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6162 return false;
6163 } else {
6164 Result.makeComplexInt();
6165 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6166 return false;
6167 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6168 return false;
6169 }
6170 return true;
6171 }
6172 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6173}
6174
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006175//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006176// Void expression evaluation, primarily for a cast to void on the LHS of a
6177// comma operator
6178//===----------------------------------------------------------------------===//
6179
6180namespace {
6181class VoidExprEvaluator
6182 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6183public:
6184 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6185
Richard Smith1aa0be82012-03-03 22:46:17 +00006186 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006187
6188 bool VisitCastExpr(const CastExpr *E) {
6189 switch (E->getCastKind()) {
6190 default:
6191 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6192 case CK_ToVoid:
6193 VisitIgnoredValue(E->getSubExpr());
6194 return true;
6195 }
6196 }
6197};
6198} // end anonymous namespace
6199
6200static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6201 assert(E->isRValue() && E->getType()->isVoidType());
6202 return VoidExprEvaluator(Info).Visit(E);
6203}
6204
6205//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006206// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006207//===----------------------------------------------------------------------===//
6208
Richard Smith1aa0be82012-03-03 22:46:17 +00006209static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006210 // In C, function designators are not lvalues, but we evaluate them as if they
6211 // are.
6212 if (E->isGLValue() || E->getType()->isFunctionType()) {
6213 LValue LV;
6214 if (!EvaluateLValue(E, LV, Info))
6215 return false;
6216 LV.moveInto(Result);
6217 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006218 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006219 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006220 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006221 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006222 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006223 } else if (E->getType()->hasPointerRepresentation()) {
6224 LValue LV;
6225 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006226 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006227 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006228 } else if (E->getType()->isRealFloatingType()) {
6229 llvm::APFloat F(0.0);
6230 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006231 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006232 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006233 } else if (E->getType()->isAnyComplexType()) {
6234 ComplexValue C;
6235 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006236 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006237 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006238 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006239 MemberPtr P;
6240 if (!EvaluateMemberPointer(E, P, Info))
6241 return false;
6242 P.moveInto(Result);
6243 return true;
Richard Smith51201882011-12-30 21:15:51 +00006244 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006245 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006246 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006247 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006248 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006249 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006250 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006251 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006252 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006253 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6254 return false;
6255 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006256 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006257 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006258 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006259 << E->getType();
6260 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006261 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006262 if (!EvaluateVoid(E, Info))
6263 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006264 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006265 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006266 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006267 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006268 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006269 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006270 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006271
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006272 return true;
6273}
6274
Richard Smith83587db2012-02-15 02:18:13 +00006275/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6276/// cases, the in-place evaluation is essential, since later initializers for
6277/// an object can indirectly refer to subobjects which were initialized earlier.
6278static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6279 const Expr *E, CheckConstantExpressionKind CCEK,
6280 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006281 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006282 return false;
6283
6284 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006285 // Evaluate arrays and record types in-place, so that later initializers can
6286 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006287 if (E->getType()->isArrayType())
6288 return EvaluateArray(E, This, Result, Info);
6289 else if (E->getType()->isRecordType())
6290 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006291 }
6292
6293 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006294 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006295}
6296
Richard Smithf48fdb02011-12-09 22:58:01 +00006297/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6298/// lvalue-to-rvalue cast if it is an lvalue.
6299static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006300 if (!CheckLiteralType(Info, E))
6301 return false;
6302
Richard Smith1aa0be82012-03-03 22:46:17 +00006303 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006304 return false;
6305
6306 if (E->isGLValue()) {
6307 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006308 LV.setFrom(Info.Ctx, Result);
6309 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006310 return false;
6311 }
6312
Richard Smith1aa0be82012-03-03 22:46:17 +00006313 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006314 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006315}
Richard Smithc49bd112011-10-28 17:51:58 +00006316
Richard Smith51f47082011-10-29 00:50:52 +00006317/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006318/// any crazy technique (that has nothing to do with language standards) that
6319/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006320/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6321/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006322bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006323 // Fast-path evaluations of integer literals, since we sometimes see files
6324 // containing vast quantities of these.
6325 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6326 Result.Val = APValue(APSInt(L->getValue(),
6327 L->getType()->isUnsignedIntegerType()));
6328 return true;
6329 }
6330
Richard Smith2d6a5672012-01-14 04:30:29 +00006331 // FIXME: Evaluating values of large array and record types can cause
6332 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006333 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006334 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006335 return false;
6336
Richard Smithf48fdb02011-12-09 22:58:01 +00006337 EvalInfo Info(Ctx, Result);
6338 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006339}
6340
Jay Foad4ba2a172011-01-12 09:06:06 +00006341bool Expr::EvaluateAsBooleanCondition(bool &Result,
6342 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006343 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006344 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006345 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006346}
6347
Richard Smith80d4b552011-12-28 19:48:30 +00006348bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6349 SideEffectsKind AllowSideEffects) const {
6350 if (!getType()->isIntegralOrEnumerationType())
6351 return false;
6352
Richard Smithc49bd112011-10-28 17:51:58 +00006353 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006354 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6355 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006356 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006357
Richard Smithc49bd112011-10-28 17:51:58 +00006358 Result = ExprResult.Val.getInt();
6359 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006360}
6361
Jay Foad4ba2a172011-01-12 09:06:06 +00006362bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006363 EvalInfo Info(Ctx, Result);
6364
John McCallefdb83e2010-05-07 21:00:08 +00006365 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006366 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6367 !CheckLValueConstantExpression(Info, getExprLoc(),
6368 Ctx.getLValueReferenceType(getType()), LV))
6369 return false;
6370
Richard Smith1aa0be82012-03-03 22:46:17 +00006371 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006372 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006373}
6374
Richard Smith099e7f62011-12-19 06:19:21 +00006375bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6376 const VarDecl *VD,
6377 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006378 // FIXME: Evaluating initializers for large array and record types can cause
6379 // performance problems. Only do so in C++11 for now.
6380 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006381 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006382 return false;
6383
Richard Smith099e7f62011-12-19 06:19:21 +00006384 Expr::EvalStatus EStatus;
6385 EStatus.Diag = &Notes;
6386
6387 EvalInfo InitInfo(Ctx, EStatus);
6388 InitInfo.setEvaluatingDecl(VD, Value);
6389
6390 LValue LVal;
6391 LVal.set(VD);
6392
Richard Smith51201882011-12-30 21:15:51 +00006393 // C++11 [basic.start.init]p2:
6394 // Variables with static storage duration or thread storage duration shall be
6395 // zero-initialized before any other initialization takes place.
6396 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006397 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006398 !VD->getType()->isReferenceType()) {
6399 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006400 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6401 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006402 return false;
6403 }
6404
Richard Smith83587db2012-02-15 02:18:13 +00006405 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6406 /*AllowNonLiteralTypes=*/true) ||
6407 EStatus.HasSideEffects)
6408 return false;
6409
6410 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6411 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006412}
6413
Richard Smith51f47082011-10-29 00:50:52 +00006414/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6415/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006416bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006417 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006418 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006419}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006420
Jay Foad4ba2a172011-01-12 09:06:06 +00006421bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006422 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006423}
6424
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006425APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006426 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006427 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006428 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006429 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006430 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006431
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006432 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006433}
John McCalld905f5a2010-05-07 05:32:02 +00006434
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006435 bool Expr::EvalResult::isGlobalLValue() const {
6436 assert(Val.isLValue());
6437 return IsGlobalLValue(Val.getLValueBase());
6438 }
6439
6440
John McCalld905f5a2010-05-07 05:32:02 +00006441/// isIntegerConstantExpr - this recursive routine will test if an expression is
6442/// an integer constant expression.
6443
6444/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6445/// comma, etc
6446///
6447/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6448/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6449/// cast+dereference.
6450
6451// CheckICE - This function does the fundamental ICE checking: the returned
6452// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6453// Note that to reduce code duplication, this helper does no evaluation
6454// itself; the caller checks whether the expression is evaluatable, and
6455// in the rare cases where CheckICE actually cares about the evaluated
6456// value, it calls into Evalute.
6457//
6458// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006459// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006460// 1: This expression is not an ICE, but if it isn't evaluated, it's
6461// a legal subexpression for an ICE. This return value is used to handle
6462// the comma operator in C99 mode.
6463// 2: This expression is not an ICE, and is not a legal subexpression for one.
6464
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006465namespace {
6466
John McCalld905f5a2010-05-07 05:32:02 +00006467struct ICEDiag {
6468 unsigned Val;
6469 SourceLocation Loc;
6470
6471 public:
6472 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6473 ICEDiag() : Val(0) {}
6474};
6475
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006476}
6477
6478static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006479
6480static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6481 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006482 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006483 !EVResult.Val.isInt()) {
6484 return ICEDiag(2, E->getLocStart());
6485 }
6486 return NoDiag();
6487}
6488
6489static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6490 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006491 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006492 return ICEDiag(2, E->getLocStart());
6493 }
6494
6495 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006496#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006497#define STMT(Node, Base) case Expr::Node##Class:
6498#define EXPR(Node, Base)
6499#include "clang/AST/StmtNodes.inc"
6500 case Expr::PredefinedExprClass:
6501 case Expr::FloatingLiteralClass:
6502 case Expr::ImaginaryLiteralClass:
6503 case Expr::StringLiteralClass:
6504 case Expr::ArraySubscriptExprClass:
6505 case Expr::MemberExprClass:
6506 case Expr::CompoundAssignOperatorClass:
6507 case Expr::CompoundLiteralExprClass:
6508 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006509 case Expr::DesignatedInitExprClass:
6510 case Expr::ImplicitValueInitExprClass:
6511 case Expr::ParenListExprClass:
6512 case Expr::VAArgExprClass:
6513 case Expr::AddrLabelExprClass:
6514 case Expr::StmtExprClass:
6515 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006516 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006517 case Expr::CXXDynamicCastExprClass:
6518 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006519 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006520 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006521 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006522 case Expr::CXXThisExprClass:
6523 case Expr::CXXThrowExprClass:
6524 case Expr::CXXNewExprClass:
6525 case Expr::CXXDeleteExprClass:
6526 case Expr::CXXPseudoDestructorExprClass:
6527 case Expr::UnresolvedLookupExprClass:
6528 case Expr::DependentScopeDeclRefExprClass:
6529 case Expr::CXXConstructExprClass:
6530 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006531 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006532 case Expr::CXXTemporaryObjectExprClass:
6533 case Expr::CXXUnresolvedConstructExprClass:
6534 case Expr::CXXDependentScopeMemberExprClass:
6535 case Expr::UnresolvedMemberExprClass:
6536 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006537 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006538 case Expr::ObjCArrayLiteralClass:
6539 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006540 case Expr::ObjCEncodeExprClass:
6541 case Expr::ObjCMessageExprClass:
6542 case Expr::ObjCSelectorExprClass:
6543 case Expr::ObjCProtocolExprClass:
6544 case Expr::ObjCIvarRefExprClass:
6545 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006546 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006547 case Expr::ObjCIsaExprClass:
6548 case Expr::ShuffleVectorExprClass:
6549 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006550 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006551 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006552 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006553 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006554 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006555 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006556 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006557 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006558 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006559 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006560 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006561 return ICEDiag(2, E->getLocStart());
6562
Douglas Gregoree8aff02011-01-04 17:33:58 +00006563 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006564 case Expr::GNUNullExprClass:
6565 // GCC considers the GNU __null value to be an integral constant expression.
6566 return NoDiag();
6567
John McCall91a57552011-07-15 05:09:51 +00006568 case Expr::SubstNonTypeTemplateParmExprClass:
6569 return
6570 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6571
John McCalld905f5a2010-05-07 05:32:02 +00006572 case Expr::ParenExprClass:
6573 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006574 case Expr::GenericSelectionExprClass:
6575 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006576 case Expr::IntegerLiteralClass:
6577 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006578 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006579 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006580 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006581 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006582 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006583 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006584 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006585 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006586 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006587 return NoDiag();
6588 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006589 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006590 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6591 // constant expressions, but they can never be ICEs because an ICE cannot
6592 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006593 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006594 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006595 return CheckEvalInICE(E, Ctx);
6596 return ICEDiag(2, E->getLocStart());
6597 }
Richard Smith359c89d2012-02-24 22:12:32 +00006598 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006599 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6600 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006601 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006602 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006603 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006604 // Parameter variables are never constants. Without this check,
6605 // getAnyInitializer() can find a default argument, which leads
6606 // to chaos.
6607 if (isa<ParmVarDecl>(D))
6608 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6609
6610 // C++ 7.1.5.1p2
6611 // A variable of non-volatile const-qualified integral or enumeration
6612 // type initialized by an ICE can be used in ICEs.
6613 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006614 if (!Dcl->getType()->isIntegralOrEnumerationType())
6615 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6616
Richard Smith099e7f62011-12-19 06:19:21 +00006617 const VarDecl *VD;
6618 // Look for a declaration of this variable that has an initializer, and
6619 // check whether it is an ICE.
6620 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6621 return NoDiag();
6622 else
6623 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006624 }
6625 }
6626 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006627 }
John McCalld905f5a2010-05-07 05:32:02 +00006628 case Expr::UnaryOperatorClass: {
6629 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6630 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006631 case UO_PostInc:
6632 case UO_PostDec:
6633 case UO_PreInc:
6634 case UO_PreDec:
6635 case UO_AddrOf:
6636 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006637 // C99 6.6/3 allows increment and decrement within unevaluated
6638 // subexpressions of constant expressions, but they can never be ICEs
6639 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006640 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006641 case UO_Extension:
6642 case UO_LNot:
6643 case UO_Plus:
6644 case UO_Minus:
6645 case UO_Not:
6646 case UO_Real:
6647 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006648 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006649 }
6650
6651 // OffsetOf falls through here.
6652 }
6653 case Expr::OffsetOfExprClass: {
6654 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006655 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006656 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006657 // compliance: we should warn earlier for offsetof expressions with
6658 // array subscripts that aren't ICEs, and if the array subscripts
6659 // are ICEs, the value of the offsetof must be an integer constant.
6660 return CheckEvalInICE(E, Ctx);
6661 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006662 case Expr::UnaryExprOrTypeTraitExprClass: {
6663 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6664 if ((Exp->getKind() == UETT_SizeOf) &&
6665 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006666 return ICEDiag(2, E->getLocStart());
6667 return NoDiag();
6668 }
6669 case Expr::BinaryOperatorClass: {
6670 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6671 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006672 case BO_PtrMemD:
6673 case BO_PtrMemI:
6674 case BO_Assign:
6675 case BO_MulAssign:
6676 case BO_DivAssign:
6677 case BO_RemAssign:
6678 case BO_AddAssign:
6679 case BO_SubAssign:
6680 case BO_ShlAssign:
6681 case BO_ShrAssign:
6682 case BO_AndAssign:
6683 case BO_XorAssign:
6684 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006685 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6686 // constant expressions, but they can never be ICEs because an ICE cannot
6687 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006688 return ICEDiag(2, E->getLocStart());
6689
John McCall2de56d12010-08-25 11:45:40 +00006690 case BO_Mul:
6691 case BO_Div:
6692 case BO_Rem:
6693 case BO_Add:
6694 case BO_Sub:
6695 case BO_Shl:
6696 case BO_Shr:
6697 case BO_LT:
6698 case BO_GT:
6699 case BO_LE:
6700 case BO_GE:
6701 case BO_EQ:
6702 case BO_NE:
6703 case BO_And:
6704 case BO_Xor:
6705 case BO_Or:
6706 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006707 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6708 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006709 if (Exp->getOpcode() == BO_Div ||
6710 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006711 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006712 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006713 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006714 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006715 if (REval == 0)
6716 return ICEDiag(1, E->getLocStart());
6717 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006718 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006719 if (LEval.isMinSignedValue())
6720 return ICEDiag(1, E->getLocStart());
6721 }
6722 }
6723 }
John McCall2de56d12010-08-25 11:45:40 +00006724 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006725 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006726 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6727 // if it isn't evaluated.
6728 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6729 return ICEDiag(1, E->getLocStart());
6730 } else {
6731 // In both C89 and C++, commas in ICEs are illegal.
6732 return ICEDiag(2, E->getLocStart());
6733 }
6734 }
6735 if (LHSResult.Val >= RHSResult.Val)
6736 return LHSResult;
6737 return RHSResult;
6738 }
John McCall2de56d12010-08-25 11:45:40 +00006739 case BO_LAnd:
6740 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006741 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6742 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6743 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6744 // Rare case where the RHS has a comma "side-effect"; we need
6745 // to actually check the condition to see whether the side
6746 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006747 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006748 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006749 return RHSResult;
6750 return NoDiag();
6751 }
6752
6753 if (LHSResult.Val >= RHSResult.Val)
6754 return LHSResult;
6755 return RHSResult;
6756 }
6757 }
6758 }
6759 case Expr::ImplicitCastExprClass:
6760 case Expr::CStyleCastExprClass:
6761 case Expr::CXXFunctionalCastExprClass:
6762 case Expr::CXXStaticCastExprClass:
6763 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006764 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006765 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006766 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006767 if (isa<ExplicitCastExpr>(E)) {
6768 if (const FloatingLiteral *FL
6769 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6770 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6771 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6772 APSInt IgnoredVal(DestWidth, !DestSigned);
6773 bool Ignored;
6774 // If the value does not fit in the destination type, the behavior is
6775 // undefined, so we are not required to treat it as a constant
6776 // expression.
6777 if (FL->getValue().convertToInteger(IgnoredVal,
6778 llvm::APFloat::rmTowardZero,
6779 &Ignored) & APFloat::opInvalidOp)
6780 return ICEDiag(2, E->getLocStart());
6781 return NoDiag();
6782 }
6783 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006784 switch (cast<CastExpr>(E)->getCastKind()) {
6785 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006786 case CK_AtomicToNonAtomic:
6787 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006788 case CK_NoOp:
6789 case CK_IntegralToBoolean:
6790 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006791 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006792 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006793 return ICEDiag(2, E->getLocStart());
6794 }
John McCalld905f5a2010-05-07 05:32:02 +00006795 }
John McCall56ca35d2011-02-17 10:25:35 +00006796 case Expr::BinaryConditionalOperatorClass: {
6797 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6798 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6799 if (CommonResult.Val == 2) return CommonResult;
6800 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6801 if (FalseResult.Val == 2) return FalseResult;
6802 if (CommonResult.Val == 1) return CommonResult;
6803 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006804 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006805 return FalseResult;
6806 }
John McCalld905f5a2010-05-07 05:32:02 +00006807 case Expr::ConditionalOperatorClass: {
6808 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6809 // If the condition (ignoring parens) is a __builtin_constant_p call,
6810 // then only the true side is actually considered in an integer constant
6811 // expression, and it is fully evaluated. This is an important GNU
6812 // extension. See GCC PR38377 for discussion.
6813 if (const CallExpr *CallCE
6814 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006815 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6816 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006817 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006818 if (CondResult.Val == 2)
6819 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006820
Richard Smithf48fdb02011-12-09 22:58:01 +00006821 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6822 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006823
John McCalld905f5a2010-05-07 05:32:02 +00006824 if (TrueResult.Val == 2)
6825 return TrueResult;
6826 if (FalseResult.Val == 2)
6827 return FalseResult;
6828 if (CondResult.Val == 1)
6829 return CondResult;
6830 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6831 return NoDiag();
6832 // Rare case where the diagnostics depend on which side is evaluated
6833 // Note that if we get here, CondResult is 0, and at least one of
6834 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006835 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006836 return FalseResult;
6837 }
6838 return TrueResult;
6839 }
6840 case Expr::CXXDefaultArgExprClass:
6841 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6842 case Expr::ChooseExprClass: {
6843 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6844 }
6845 }
6846
David Blaikie30263482012-01-20 21:50:17 +00006847 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006848}
6849
Richard Smithf48fdb02011-12-09 22:58:01 +00006850/// Evaluate an expression as a C++11 integral constant expression.
6851static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6852 const Expr *E,
6853 llvm::APSInt *Value,
6854 SourceLocation *Loc) {
6855 if (!E->getType()->isIntegralOrEnumerationType()) {
6856 if (Loc) *Loc = E->getExprLoc();
6857 return false;
6858 }
6859
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006860 APValue Result;
6861 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006862 return false;
6863
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006864 assert(Result.isInt() && "pointer cast to int is not an ICE");
6865 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006866 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006867}
6868
Richard Smithdd1f29b2011-12-12 09:28:41 +00006869bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006870 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006871 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6872
John McCalld905f5a2010-05-07 05:32:02 +00006873 ICEDiag d = CheckICE(this, Ctx);
6874 if (d.Val != 0) {
6875 if (Loc) *Loc = d.Loc;
6876 return false;
6877 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006878 return true;
6879}
6880
6881bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6882 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006883 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006884 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6885
6886 if (!isIntegerConstantExpr(Ctx, Loc))
6887 return false;
6888 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006889 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006890 return true;
6891}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006892
Richard Smith70488e22012-02-14 21:38:30 +00006893bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6894 return CheckICE(this, Ctx).Val == 0;
6895}
6896
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006897bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6898 SourceLocation *Loc) const {
6899 // We support this checking in C++98 mode in order to diagnose compatibility
6900 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006901 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006902
Richard Smith70488e22012-02-14 21:38:30 +00006903 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006904 Expr::EvalStatus Status;
6905 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6906 Status.Diag = &Diags;
6907 EvalInfo Info(Ctx, Status);
6908
6909 APValue Scratch;
6910 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6911
6912 if (!Diags.empty()) {
6913 IsConstExpr = false;
6914 if (Loc) *Loc = Diags[0].first;
6915 } else if (!IsConstExpr) {
6916 // FIXME: This shouldn't happen.
6917 if (Loc) *Loc = getExprLoc();
6918 }
6919
6920 return IsConstExpr;
6921}
Richard Smith745f5142012-01-27 01:14:48 +00006922
6923bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6924 llvm::SmallVectorImpl<
6925 PartialDiagnosticAt> &Diags) {
6926 // FIXME: It would be useful to check constexpr function templates, but at the
6927 // moment the constant expression evaluator cannot cope with the non-rigorous
6928 // ASTs which we build for dependent expressions.
6929 if (FD->isDependentContext())
6930 return true;
6931
6932 Expr::EvalStatus Status;
6933 Status.Diag = &Diags;
6934
6935 EvalInfo Info(FD->getASTContext(), Status);
6936 Info.CheckingPotentialConstantExpression = true;
6937
6938 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6939 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6940
6941 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6942 // is a temporary being used as the 'this' pointer.
6943 LValue This;
6944 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006945 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006946
Richard Smith745f5142012-01-27 01:14:48 +00006947 ArrayRef<const Expr*> Args;
6948
6949 SourceLocation Loc = FD->getLocation();
6950
Richard Smith1aa0be82012-03-03 22:46:17 +00006951 APValue Scratch;
6952 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006953 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006954 else
Richard Smith745f5142012-01-27 01:14:48 +00006955 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6956 Args, FD->getBody(), Info, Scratch);
6957
6958 return Diags.empty();
6959}